torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
use crate::bencode::BencodeValue;

pub fn encode(value: &BencodeValue) -> Vec<u8> {
    let mut out = Vec::new();
    encode_into(value, &mut out);
    out
}

fn encode_into(value: &BencodeValue, out: &mut Vec<u8>) {
    match value {
        BencodeValue::Int(v) => {
            out.push(b'i');
            out.extend(itoa::Buffer::new().format(*v).as_bytes());
            out.push(b'e');
        }
        BencodeValue::Bytes(bytes) => {
            out.extend(bytes.len().to_string().as_bytes());
            out.push(b':');
            out.extend(bytes);
        }
        BencodeValue::List(items) => {
            out.push(b'l');
            for item in items {
                encode_into(item, out);
            }
            out.push(b'e');
        }
        BencodeValue::Dict(map) => {
            out.push(b'd');
            for (key, val) in map {
                encode_into(&BencodeValue::Bytes(key.clone()), out);
                encode_into(val, out);
            }
            out.push(b'e');
        }
    }
}

mod itoa {
    pub struct Buffer {
        bytes: [u8; 32],
    }

    impl Buffer {
        pub fn new() -> Self {
            Self { bytes: [0; 32] }
        }

        pub fn format(&mut self, value: i64) -> &str {
            let mut idx = self.bytes.len();
            let negative = value < 0;
            let mut n = if negative {
                value.unsigned_abs()
            } else {
                value as u64
            };

            if n == 0 {
                idx -= 1;
                self.bytes[idx] = b'0';
            } else {
                while n > 0 {
                    idx -= 1;
                    self.bytes[idx] = b'0' + (n % 10) as u8;
                    n /= 10;
                }
            }

            if negative {
                idx -= 1;
                self.bytes[idx] = b'-';
            }

            std::str::from_utf8(&self.bytes[idx..]).expect("ascii digits")
        }
    }
}

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

    #[test]
    fn roundtrip() {
        let original = BencodeValue::Dict(std::collections::BTreeMap::from([(
            b"name".to_vec(),
            BencodeValue::Bytes(b"test".to_vec()),
        )]));
        let encoded = encode(&original);
        let decoded = decode(&encoded).expect("decode");
        assert_eq!(original, decoded);
    }
}