ibrahim-tcp 1.0.0

High-performance lightweight TCP protocol with reliability, compression, and fault tolerance
Documentation
use crate::Packet;
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
    time::{Duration, Instant},
};

#[derive(Clone)]
pub struct AckManager {
    pending: Arc<Mutex<HashMap<u64, (Instant, Packet)>>>,
}

impl AckManager {
    pub fn new() -> Self {
        Self {
            pending: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub fn track(&self, pkt: &Packet) {
        self.pending
            .lock()
            .unwrap()
            .insert(pkt.id, (Instant::now(), pkt.clone()));
    }

    pub fn confirm(&self, id: u64) {
        self.pending.lock().unwrap().remove(&id);
    }

    pub fn retries(&self) -> Vec<Packet> {
        let mut resend = Vec::new();
        let now = Instant::now();
        let mut pending = self.pending.lock().unwrap();
        for (id, (t, pkt)) in pending.iter_mut() {
            if now.duration_since(*t) > Duration::from_secs(3) {
                *t = now;
                resend.push(pkt.clone());
            }
        }
        resend
    }
}