1pub fn hexits(bytes: &[u8]) -> String {
17 let mut out = String::with_capacity(bytes.len() * 2);
18 for b in bytes {
19 out.push(char::from_digit(u32::from(b >> 4), 16).expect("a nibble is a hexit"));
20 out.push(char::from_digit(u32::from(b & 0xf), 16).expect("a nibble is a hexit"));
21 }
22 out.to_ascii_uppercase()
23}
24
25pub fn literal(bytes: &[u8]) -> String {
27 format!("X'{}'", hexits(bytes))
28}
29
30pub fn from_hexits(text: &str) -> Option<Vec<u8>> {
36 let mut nibbles: Vec<u8> = Vec::with_capacity(text.len());
37 for c in text.chars() {
38 if c.is_ascii_whitespace() {
39 continue;
40 }
41 nibbles.push(c.to_digit(16)? as u8);
42 }
43 if !nibbles.len().is_multiple_of(2) {
44 return None;
45 }
46 Some(nibbles.chunks(2).map(|p| (p[0] << 4) | p[1]).collect())
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn a_byte_string_writes_two_hexits_a_byte() {
55 assert_eq!(literal(&[0x00, 0xab, 0x00]), "X'00AB00'");
56 assert_eq!(literal(&[]), "X''");
57 }
58
59 #[test]
60 fn the_spelling_reads_back_as_what_was_written() {
61 for case in [&[][..], &[0][..], &[0xde, 0xad, 0xbe, 0xef][..]] {
62 assert_eq!(from_hexits(&hexits(case)).as_deref(), Some(case));
63 }
64 }
65
66 #[test]
67 fn either_case_of_hexit_reads_and_space_is_dropped() {
68 assert_eq!(from_hexits("00ab00"), Some(vec![0x00, 0xab, 0x00]));
69 assert_eq!(from_hexits("00 AB 00"), Some(vec![0x00, 0xab, 0x00]));
70 }
71
72 #[test]
73 fn half_a_byte_and_a_digit_that_is_not_a_hexit_are_not_byte_strings() {
74 assert_eq!(from_hexits("abc"), None);
75 assert_eq!(from_hexits("zz"), None);
76 }
77}