Skip to main content

zu_common/
bytes.rs

1//! Byte strings, GV35: how one is written down and how one is read
2//! back.
3//!
4//! A byte string is a sequence of octets, and there is no encoding to
5//! guess at: the value is the bytes. What there is, is a spelling, and
6//! ISO 21.3 gives it as `X'00AB'`, two hexits to a byte. Writing and
7//! reading that spelling is the whole of this module, and it is here
8//! rather than beside the lexer because the same spelling comes back
9//! out of a result column, so a value that went in as `X'00ab'` and
10//! came back as `X'00AB'` is the same value and reads as one.
11
12/// The hexits of a byte string, upper case, no quotes and no `X`.
13///
14/// Upper case because ISO writes the literal that way, and a reader
15/// comparing two of these is comparing text: one case is one answer.
16pub 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
25/// The literal a byte string is written as, quotes and `X` and all.
26pub fn literal(bytes: &[u8]) -> String {
27    format!("X'{}'", hexits(bytes))
28}
29
30/// The bytes a run of hexits names, `None` for anything that is not a
31/// run of hexits or names half a byte.
32///
33/// Space is allowed anywhere and dropped, which is what the standard's
34/// production allows and what lets a long literal be written in groups.
35pub 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}