Skip to main content

rustnet_core/network/
util.rs

1//! Small shared formatting helpers used across the analysis layer.
2
3use std::fmt::Write as _;
4
5/// Encode bytes as a lowercase hex string, with `separator` between bytes
6/// ("" for a compact digest, ":" for MAC/connection-ID style).
7pub fn hex_encode(bytes: &[u8], separator: &str) -> String {
8    let mut out = String::with_capacity(bytes.len() * (2 + separator.len()));
9    for (i, b) in bytes.iter().enumerate() {
10        if i > 0 {
11            out.push_str(separator);
12        }
13        // write! to a String never fails.
14        let _ = write!(out, "{b:02x}");
15    }
16    out
17}
18
19#[cfg(test)]
20mod tests {
21    use super::*;
22
23    #[test]
24    fn test_hex_encode() {
25        assert_eq!(hex_encode(&[0xDE, 0xAD, 0xBE, 0xEF], ""), "deadbeef");
26        assert_eq!(hex_encode(&[0x00, 0xFF], ""), "00ff");
27    }
28
29    #[test]
30    fn test_hex_encode_lowercase_20_byte_info_hash() {
31        // A representative 20-byte info-hash (the size BitTorrent always uses).
32        let info_hash: [u8; 20] = [
33            0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x00, 0xff, 0x01, 0x02, 0x03, 0x04,
34            0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
35        ];
36        assert_eq!(
37            hex_encode(&info_hash, ""),
38            "123456789abcdef000ff0102030405060708090a"
39        );
40    }
41
42    #[test]
43    fn test_hex_encode_empty_slice() {
44        assert_eq!(hex_encode(&[], ""), "");
45    }
46
47    #[test]
48    fn test_hex_encode_pads_single_digit_bytes() {
49        // Locks the `{:02x}` padding contract: 0x00..=0x0f stay two chars.
50        assert_eq!(hex_encode(&[0x00, 0x0a, 0x0f, 0x10], ""), "000a0f10");
51    }
52
53    #[test]
54    fn test_hex_encode_with_separator() {
55        assert_eq!(
56            hex_encode(&[0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], ":"),
57            "aa:bb:cc:dd:ee:ff"
58        );
59        assert_eq!(hex_encode(&[0x01], ":"), "01");
60    }
61}