@@ -389,29 +389,37 @@ impl Repository for RepositoryDashmap {
389389 fn upsert_torrent_with_peer_and_get_stats ( & self , info_hash : & InfoHash , peer : & peer:: Peer ) -> ( SwarmStats , bool ) {
390390 let hash = self . torrents . hash_usize ( & info_hash) ;
391391 let shard_idx = self . torrents . determine_shard ( hash) ;
392+
393+ // Is safe as it tries to get an array item at a certain index that we know exists for sure
392394 let mut shard = unsafe { self . torrents . _yield_write_shard ( shard_idx) } ;
393395
396+ // Remove the torrent from the shard
394397 let mut torrent = shard. remove ( info_hash) . map ( |v| v. into_inner ( ) ) . unwrap_or_default ( ) ;
395398
396399 let stats_updated = torrent. insert_or_update_peer ( peer) ;
397400 let stats = torrent. get_stats ( ) ;
398401
399402 let mut mem_size_shard: usize = 0 ;
400403
404+ // Calculate and set the current mem size of the shard
401405 for torrent in shard. values ( ) {
402406 mem_size_shard += ( 2 * POINTER_SIZE ) + INFO_HASH_SIZE + torrent. get ( ) . get_mem_size ( ) ;
403407 }
404408
409+ // Get the max memory limit per shard
405410 let maybe_max_memory_available = MAX_MEMORY_LIMIT . map ( |v| v / self . torrents . _shard_count ( ) - mem_size_shard) ;
406411
412+ // Calculate the shortage of memory on the shard
407413 let memory_shortage = maybe_max_memory_available
408414 . map ( |v| TORRENT_INSERTION_SIZE_COST . saturating_sub ( v) )
409415 . unwrap_or ( 0 ) ;
410416
417+ // Free the needed memory on the shard if there is a shortage
411418 if memory_shortage > 0 {
412419 let mut amount_freed: usize = 0 ;
413420
414- let mut priority_list = unsafe { self . shard_priority_list . get_unchecked ( shard_idx) } . lock ( ) . unwrap ( ) ;
421+ // Unwrap is safe as we try to get an array item at a certain index that we know exists for sure
422+ let mut priority_list = self . shard_priority_list . get ( shard_idx) . unwrap ( ) . lock ( ) . unwrap ( ) ;
415423
416424 while amount_freed < memory_shortage && !priority_list. is_empty ( ) {
417425 // Can safely unwrap as we check if the priority list is not empty
@@ -423,8 +431,10 @@ impl Repository for RepositoryDashmap {
423431 }
424432 }
425433
434+ // Add or shift the torrent info hash to the top of the shard priority list
426435 self . addshift_torrent_to_front_on_shard_priority_list ( shard_idx, info_hash) ;
427436
437+ // (re)insert (updated) torrent into the shard
428438 shard
429439 . insert ( info_hash. to_owned ( ) , SharedValue :: new ( torrent) )
430440 . map ( |v| v. into_inner ( ) ) ;
0 commit comments