Elffuss BraidHub

utopia-ia/elffuss-braid public

356f55034aff · 3.6 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Byte strings in braid's small text files.
5//!
6//! Paths are bytes, not text, but the files that record a workspace are
7//! meant to be read by people too. A value is written with every byte
8//! outside printable ASCII, and `%` itself, as `%` and two uppercase hex
9//! digits, so any byte string fits on one line and reads back exactly.
10
11use std::path::{Path, PathBuf};
12
13/// The text form of `bytes`: printable ASCII as it is, any other byte and
14/// `%` as `%XX`.
15pub fn escape(bytes: &[u8]) -> String {
16 let mut text = String::with_capacity(bytes.len());
17 for &byte in bytes {
18 if (0x20..0x7f).contains(&byte) && byte != b'%' {
19 text.push(char::from(byte));
20 } else {
21 text.push('%');
22 text.push(char::from(b"0123456789ABCDEF"[usize::from(byte >> 4)]));
23 text.push(char::from(b"0123456789ABCDEF"[usize::from(byte & 0x0f)]));
24 }
25 }
26 text
27}
28
29/// The bytes that [`escape`] wrote as `text`, or `None` if `text` is not
30/// such a form: a `%` not followed by two hex digits, or a byte that should
31/// have been escaped.
32pub fn unescape(text: &str) -> Option<Vec<u8>> {
33 let bytes = text.as_bytes();
34 let mut out = Vec::with_capacity(bytes.len());
35 let mut i = 0;
36 while i < bytes.len() {
37 let byte = bytes[i];
38 if byte == b'%' {
39 let high = hex_value(*bytes.get(i + 1)?)?;
40 let low = hex_value(*bytes.get(i + 2)?)?;
41 out.push((high << 4) | low);
42 i += 3;
43 } else if (0x20..0x7f).contains(&byte) {
44 out.push(byte);
45 i += 1;
46 } else {
47 return None;
48 }
49 }
50 Some(out)
51}
52
53fn hex_value(digit: u8) -> Option<u8> {
54 match digit {
55 b'0'..=b'9' => Some(digit - b'0'),
56 b'A'..=b'F' => Some(digit - b'A' + 10),
57 b'a'..=b'f' => Some(digit - b'a' + 10),
58 _ => None,
59 }
60}
61
62/// The bytes of a path as the operating system stores it. On systems where
63/// paths are not byte strings, only paths that are valid Unicode have bytes.
64pub fn path_bytes(path: &Path) -> Option<Vec<u8>> {
65 #[cfg(unix)]
66 {
67 use std::os::unix::ffi::OsStrExt;
68 Some(path.as_os_str().as_bytes().to_vec())
69 }
70 #[cfg(not(unix))]
71 {
72 path.to_str().map(|text| text.as_bytes().to_vec())
73 }
74}
75
76/// The path whose bytes are `bytes`, the inverse of [`path_bytes`].
77pub fn path_from_bytes(bytes: &[u8]) -> Option<PathBuf> {
78 #[cfg(unix)]
79 {
80 use std::os::unix::ffi::OsStrExt;
81 Some(PathBuf::from(std::ffi::OsStr::from_bytes(bytes)))
82 }
83 #[cfg(not(unix))]
84 {
85 std::str::from_utf8(bytes).ok().map(PathBuf::from)
86 }
87}
88
89#[cfg(test)]
90mod tests {
91 use super::*;
92
93 #[test]
94 fn escaping_round_trips_every_byte() {
95 let all: Vec<u8> = (0..=255).collect();
96 let text = escape(&all);
97 assert!(text.bytes().all(|byte| (0x20..0x7f).contains(&byte)));
98 assert_eq!(unescape(&text).unwrap(), all);
99 assert_eq!(escape(b"a b/c.txt"), "a b/c.txt");
100 assert_eq!(escape(b"100%\n"), "100%25%0A");
101 assert_eq!(unescape("caf%C3%a9").unwrap(), "caf\u{e9}".as_bytes());
102 }
103
104 #[test]
105 fn malformed_escapes_are_refused() {
106 for bad in ["%", "%4", "%zz", "tab\there", "caf\u{e9}"] {
107 assert_eq!(unescape(bad), None, "{bad:?}");
108 }
109 }
110
111 #[test]
112 fn paths_round_trip() {
113 let path = Path::new("dir/sub dir/file.txt");
114 let bytes = path_bytes(path).unwrap();
115 assert_eq!(path_from_bytes(&bytes).unwrap(), path);
116 }
117}