mz_testdrive/format/bytes.rs
1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use anyhow::bail;
11
12/// Unescapes a testdrive byte string.
13///
14/// The escape character is `\` and the only interesting escape sequence is
15/// `\xNN`, where each `N` is a valid hexadecimal digit. All other characters
16/// following a backslash are taken literally.
17pub fn unescape(s: &[u8]) -> Result<Vec<u8>, anyhow::Error> {
18 let mut out = vec![];
19 let mut s = s.iter().copied().fuse();
20 while let Some(b) = s.next() {
21 match b {
22 // NOTE: the escaped byte must be consumed in the arm body, not in
23 // a match guard. A guard's `s.next()` runs even when the guard
24 // fails, silently eating the byte after the backslash.
25 b'\\' => match s.next() {
26 Some(b'x') => match (next_hex(&mut s), next_hex(&mut s)) {
27 (Some(c1), Some(c0)) => out.push((c1 << 4) + c0),
28 _ => bail!("invalid hexadecimal escape"),
29 },
30 Some(b) => out.push(b),
31 None => bail!("trailing backslash in byte string"),
32 },
33 _ => out.push(b),
34 }
35 }
36 Ok(out)
37}
38
39/// Retrieves the value of the next hexadecimal digit in `iter`, if the next
40/// byte is a valid hexadecimal digit.
41fn next_hex<I>(iter: &mut I) -> Option<u8>
42where
43 I: Iterator<Item = u8>,
44{
45 iter.next().and_then(|c| match c {
46 b'A'..=b'F' => Some(c - b'A' + 10),
47 b'a'..=b'f' => Some(c - b'a' + 10),
48 b'0'..=b'9' => Some(c - b'0'),
49 _ => None,
50 })
51}