Skip to content

Commit e7db0b8

Browse files
committed
wip
1 parent 54c6918 commit e7db0b8

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

src/core/torrent/repositories.rs

+24-6
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,16 @@ use crate::core::torrent::{Entry, SwarmStats};
1010
use crate::shared::bit_torrent::info_hash::InfoHash;
1111
use crate::shared::mem_size::{MemSize, POINTER_SIZE};
1212

13+
// todo: config
14+
const MAX_MEMORY_LIMIT: Option<usize> = Some(4_000_000_000);
15+
1316
const INFO_HASH_SIZE: usize = size_of::<InfoHash>();
1417

1518
/// Total memory impact of adding a new empty torrent ([torrent::Entry]) to a map.
1619
const TORRENT_INSERTION_SIZE_COST: usize = 216;
1720
/// Total memory impact of adding a new peer ([peer::Peer]) to a map.
1821
const PEER_INSERTION_SIZE_COST: usize = 132;
1922

20-
// todo: config
21-
const MAX_MEMORY_LIMIT: Option<usize> = Some(4_000_000_000);
22-
2323
pub trait Repository {
2424
fn new() -> Self;
2525

@@ -407,13 +407,29 @@ impl RepositoryDashmap {
407407
mem_size_shard
408408
}
409409

410+
fn shift_torrent_to_front_on_shard_priority_list(&self, shard_idx: usize, info_hash: &InfoHash) {
411+
let mut priority_list = self.shard_priority_list.get(shard_idx).unwrap().lock().unwrap();
412+
413+
let mut index = None;
414+
415+
for (i, torrent) in priority_list.iter().enumerate() {
416+
if torrent == info_hash {
417+
index = Some(i);
418+
}
419+
}
420+
421+
if let Some(index) = index {
422+
let _torrent = priority_list.remove(index);
423+
}
424+
425+
priority_list.push_front(info_hash.to_owned());
426+
}
427+
410428
fn insert_torrent(&self, info_hash: &InfoHash) -> Option<Entry> {
411429
let hash = self.torrents.hash_usize(info_hash);
412430
let shard_idx = self.torrents.determine_shard(hash);
413431

414-
let mut priority_list = self.shard_priority_list.get(shard_idx).unwrap().lock().unwrap();
415-
416-
priority_list.push_front(info_hash.to_owned());
432+
self.shift_torrent_to_front_on_shard_priority_list(shard_idx, info_hash);
417433

418434
self.torrents.insert(info_hash.to_owned(), Entry::new())
419435
}
@@ -441,6 +457,8 @@ impl Repository for RepositoryDashmap {
441457
if !self.torrents.contains_key(info_hash) {
442458
self.check_do_free_memory_on_shard(shard_idx, TORRENT_INSERTION_SIZE_COST);
443459
self.insert_torrent(info_hash);
460+
} else {
461+
self.shift_torrent_to_front_on_shard_priority_list(shard_idx, info_hash);
444462
}
445463

446464
let peer_exists = self.torrents.get(info_hash).unwrap().peers.contains_key(&peer.peer_id);

0 commit comments

Comments
 (0)