reddb_server/utils/
hex.rs1#[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#[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}