Skip to main content

reddb_server/utils/
hex.rs

1//! Tiny hex encoder used wherever a byte slice needs to be rendered
2//! as a hex string. Centralised so the same `bytes.iter().map(|b|
3//! format!("{:02x}", b)).collect()` doesn't get re-typed across the
4//! crate.
5
6/// Encode `bytes` as a lowercase hex string.
7#[inline]
8pub fn to_hex(bytes: &[u8]) -> String {
9    let mut out = String::with_capacity(bytes.len() * 2);
10    for b in bytes {
11        out.push_str(&format!("{:02x}", b));
12    }
13    out
14}
15
16/// Encode the first `n` bytes (or fewer) as lowercase hex. Useful
17/// for short identifiers like `bearer:<sha256-prefix>` labels.
18#[inline]
19pub fn to_hex_prefix(bytes: &[u8], n: usize) -> String {
20    let mut out = String::with_capacity(n.min(bytes.len()) * 2);
21    for b in bytes.iter().take(n) {
22        out.push_str(&format!("{:02x}", b));
23    }
24    out
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30
31    #[test]
32    fn empty_input_yields_empty_string() {
33        assert_eq!(to_hex(&[]), "");
34    }
35
36    #[test]
37    fn known_bytes_round_trip() {
38        assert_eq!(to_hex(&[0x01, 0x02, 0xab, 0xff]), "0102abff");
39    }
40
41    #[test]
42    fn prefix_caps_at_n() {
43        assert_eq!(to_hex_prefix(&[0xde, 0xad, 0xbe, 0xef], 2), "dead");
44        assert_eq!(to_hex_prefix(&[0xde, 0xad], 8), "dead");
45    }
46}