use super::{ChokingAlgorithm, PeerIdentity};
pub(super) fn optimistically_unchoke_by_identity(
algo: &mut ChokingAlgorithm,
) -> Option<PeerIdentity> {
let index = optimistically_unchoke(algo)?;
algo.peers.get(index).map(PeerIdentity::from)
}
pub(super) fn optimistically_unchoke(algo: &mut ChokingAlgorithm) -> Option<usize> {
let candidates: Vec<usize> = algo
.peers
.iter()
.enumerate()
.filter(|(_, peer)| {
peer.am_choking
&& peer.peer_interested
&& !peer.is_snubbed
&& !algo.snubbed_peers.contains(&(*peer).into())
&& peer.time_since_last_optimistic_unchoke().as_secs()
>= algo.config.optimistic_unchoke_interval_secs
})
.map(|(i, _)| i)
.collect();
if candidates.is_empty() {
return None;
}
let selected = rotate_optimistic_unchoked(algo, &candidates);
if let Some(peer) = algo.peers.get_mut(selected) {
peer.record_optimistic_unchoke();
}
algo.current_optimistic_peer = algo.peers.get(selected).map(PeerIdentity::from);
Some(selected)
}
pub(super) fn rotate_optimistic_unchoked(
algo: &mut ChokingAlgorithm,
eligible_peers: &[usize],
) -> usize {
if eligible_peers.is_empty() {
panic!("rotate_optimistic_unchoked called with empty eligible list");
}
if eligible_peers.len() == 1 {
return eligible_peers[0];
}
let current_pos = algo.current_optimistic_peer.and_then(|curr| {
eligible_peers.iter().position(|&index| {
algo.peers
.get(index)
.is_some_and(|peer| PeerIdentity::from(peer) == curr)
})
});
let next_pos = match current_pos {
Some(pos) => (pos + 1) % eligible_peers.len(),
None => algo.optimistic_rotation_counter % eligible_peers.len(),
};
algo.optimistic_rotation_counter = algo.optimistic_rotation_counter.wrapping_add(1);
eligible_peers[next_pos]
}