fx-torrent 0.10.3

FX Torrent is a feature rich Bittorrent protocol implementation written in rust supporting Linux, MacOS and Windows.
Documentation
use crate::peer::{Error, Result};
use rand::RngExt;
use std::fmt::{Debug, Display, Formatter};

const ID_PREFIX: &str = "-RW0082-";

/// Represents a unique peer identifier for a torrent network.
///
/// The `PeerId` is a 20-byte array generated using a fixed prefix and a random 12-digit suffix.
/// The first 2 characters of the prefix identify the client library and the remaining 4 represent
/// the version number of the client.
///
/// See <https://www.bittorrent.org/beps/bep_0020.html> for more information.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct PeerId([u8; 20]);

impl PeerId {
    /// Creates a new `PeerId` with a randomly generated value.
    ///
    /// The `PeerId` is generated by concatenating a fixed prefix [ID_PREFIX] with a random 12-digit
    /// suffix. The resulting string is converted into a 20-byte array.
    ///
    /// # Returns
    ///
    /// A new `PeerId` instance with a unique identifier.
    pub fn new() -> Self {
        let id = Self::generate_peer_id();

        Self {
            0: id
                .as_bytes()
                .try_into()
                .expect("peer id should be exactly 20 bytes long"),
        }
    }

    /// Get the raw 20-byte value of the `PeerId`.
    ///
    /// # Returns
    ///
    /// A 20-byte array representing the `PeerId`.
    pub fn value(&self) -> [u8; 20] {
        self.0.clone()
    }

    /// Get the slice value of the `PeerId`.
    ///
    /// # Returns
    ///
    /// A 20-byte slice representing the `PeerId`.
    pub fn as_slice(&self) -> &[u8] {
        &self.0
    }

    /// Generates a new peer ID string by concatenating a fixed prefix with a random 12-digit suffix.
    ///
    /// # Returns
    ///
    /// A `String` representing the generated peer ID.
    fn generate_peer_id() -> String {
        let mut rng = rand::rng();
        let suffix: String = (0..12)
            .map(|_| rng.random_range(b'0'..=b'9') as char)
            .collect();

        format!("{}{}", ID_PREFIX, suffix)
    }
}

impl Display for PeerId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", String::from_utf8_lossy(&self.0))
    }
}

impl Debug for PeerId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", String::from_utf8_lossy(&self.0))
    }
}

impl TryFrom<&[u8]> for PeerId {
    type Error = Error;

    fn try_from(value: &[u8]) -> Result<Self> {
        if value.len() != 20 {
            return Err(Error::InvalidPeerId);
        }

        let mut buffer = [0u8; 20];
        buffer.copy_from_slice(value);
        Ok(Self(buffer))
    }
}

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

    #[test]
    fn test_peer_id_new() {
        let result = PeerId::new();

        assert_eq!(20, result.0.len(), "expected the peer id length to be 20");
        assert!(
            result.to_string().starts_with(ID_PREFIX),
            "expected the peer id to start with the fixed prefix"
        );
    }

    #[test]
    fn test_generate_peer_id() {
        let result = PeerId::generate_peer_id();

        assert_eq!(20, result.len(), "expected the peer id length to be 20");
    }

    #[test]
    fn test_peer_id_display() {
        let peer_str = format!("{}123456789012", ID_PREFIX);
        let peer_bytes = peer_str.as_bytes();
        let peer_id = PeerId::try_from(peer_bytes).unwrap();

        let result = peer_id.to_string();

        assert_eq!(peer_str, result.as_str());
    }
}