@@ -10,16 +10,16 @@ use crate::core::torrent::{Entry, SwarmStats};
10
10
use crate :: shared:: bit_torrent:: info_hash:: InfoHash ;
11
11
use crate :: shared:: mem_size:: { MemSize , POINTER_SIZE } ;
12
12
13
+ // todo: config
14
+ const MAX_MEMORY_LIMIT : Option < usize > = Some ( 4_000_000_000 ) ;
15
+
13
16
const INFO_HASH_SIZE : usize = size_of :: < InfoHash > ( ) ;
14
17
15
18
/// Total memory impact of adding a new empty torrent ([torrent::Entry]) to a map.
16
19
const TORRENT_INSERTION_SIZE_COST : usize = 216 ;
17
20
/// Total memory impact of adding a new peer ([peer::Peer]) to a map.
18
21
const PEER_INSERTION_SIZE_COST : usize = 132 ;
19
22
20
- // todo: config
21
- const MAX_MEMORY_LIMIT : Option < usize > = Some ( 4_000_000_000 ) ;
22
-
23
23
pub trait Repository {
24
24
fn new ( ) -> Self ;
25
25
@@ -407,13 +407,29 @@ impl RepositoryDashmap {
407
407
mem_size_shard
408
408
}
409
409
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
+
410
428
fn insert_torrent ( & self , info_hash : & InfoHash ) -> Option < Entry > {
411
429
let hash = self . torrents . hash_usize ( info_hash) ;
412
430
let shard_idx = self . torrents . determine_shard ( hash) ;
413
431
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) ;
417
433
418
434
self . torrents . insert ( info_hash. to_owned ( ) , Entry :: new ( ) )
419
435
}
@@ -441,6 +457,8 @@ impl Repository for RepositoryDashmap {
441
457
if !self . torrents . contains_key ( info_hash) {
442
458
self . check_do_free_memory_on_shard ( shard_idx, TORRENT_INSERTION_SIZE_COST ) ;
443
459
self . insert_torrent ( info_hash) ;
460
+ } else {
461
+ self . shift_torrent_to_front_on_shard_priority_list ( shard_idx, info_hash) ;
444
462
}
445
463
446
464
let peer_exists = self . torrents . get ( info_hash) . unwrap ( ) . peers . contains_key ( & peer. peer_id ) ;
0 commit comments