torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use bytes::Bytes;

use crate::error::{Error, Result};
use crate::types::BlockKey;

#[derive(Debug, Default)]
pub struct MemoryTier {
    blocks: HashMap<BlockKey, Bytes>,
    bytes_used: usize,
    byte_limit: usize,
}

impl MemoryTier {
    pub fn new(byte_limit: usize) -> Self {
        Self {
            blocks: HashMap::new(),
            bytes_used: 0,
            byte_limit,
        }
    }

    pub fn get(&self, key: BlockKey) -> Option<Bytes> {
        self.blocks.get(&key).cloned()
    }

    pub fn insert(&mut self, key: BlockKey, data: Bytes) -> Result<()> {
        let new_size = data.len();
        if let Some(old) = self.blocks.get(&key) {
            self.bytes_used = self.bytes_used.saturating_sub(old.len());
        }
        // Do not evict other dirty keys — they may still be awaiting flush.
        if self.bytes_used.saturating_add(new_size) > self.byte_limit {
            // Restore accounting if we already subtracted an overwrite.
            if let Some(old) = self.blocks.get(&key) {
                self.bytes_used = self.bytes_used.saturating_add(old.len());
            }
            return Err(Error::Store("memory cache budget exceeded".into()));
        }
        self.bytes_used = self.bytes_used.saturating_add(new_size);
        self.blocks.insert(key, data);
        Ok(())
    }

    pub fn remove(&mut self, key: BlockKey) {
        if let Some(data) = self.blocks.remove(&key) {
            self.bytes_used = self.bytes_used.saturating_sub(data.len());
        }
    }

    pub fn bytes_used(&self) -> usize {
        self.bytes_used
    }
}

pub type SharedMemoryTier = Arc<RwLock<MemoryTier>>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn enforces_byte_limit() {
        let mut mem = MemoryTier::new(10);
        mem.insert(BlockKey { piece: 0, offset: 0 }, Bytes::from(vec![0u8; 6]))
            .expect("insert");
        assert!(mem
            .insert(BlockKey { piece: 0, offset: 1 }, Bytes::from(vec![0u8; 6]))
            .is_err());
        assert!(mem.get(BlockKey { piece: 0, offset: 0 }).is_some());
    }
}