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 b'\\' if s.next() == Some(b'x') => match (next_hex(&mut s), next_hex(&mut s)) {
23 (Some(c1), Some(c0)) => out.push((c1 << 4) + c0),
24 _ => bail!("invalid hexadecimal escape"),
25 },
26 b'\\' => continue,
27 _ => out.push(b),
28 }
29 }
30 Ok(out)
31}
32
33/// Retrieves the value of the next hexadecimal digit in `iter`, if the next
34/// byte is a valid hexadecimal digit.
35fn next_hex<I>(iter: &mut I) -> Option<u8>
36where
37 I: Iterator<Item = u8>,
38{
39 iter.next().and_then(|c| match c {
40 b'A'..=b'F' => Some(c - b'A' + 10),
41 b'a'..=b'f' => Some(c - b'a' + 10),
42 b'0'..=b'9' => Some(c - b'0'),
43 _ => None,
44 })
45}