exarch_core/path_text.rs
1//! Injective text for paths.
2
3use std::fmt::Write as _;
4use std::path::Path;
5
6/// Renders a path as text so that two distinct paths never render alike.
7///
8/// Valid text is kept as it is, except that a backslash is written `\x5C` on
9/// Unix, where it is an ordinary character of a name. On Windows a backslash
10/// is a separator, so the components of the path are joined with `/` and the
11/// same entry name reads alike on every host (`x\y` renders as `x/y`).
12/// Each byte of a Unix path that is not part of valid UTF-8 is written
13/// `\xNN` (upper-case hex), and each unpaired UTF-16 unit of a Windows path is
14/// written `\uNNNN`. Because the escape character is itself escaped, the
15/// rendering is injective: a literal `a\xFFb` renders as `a\x5CxFFb`, never as
16/// the path `a<0xFF>b`.
17///
18/// Use this wherever a path is shown or serialized as text and refusing it
19/// would hide the finding that reports it (listings, verification issues,
20/// progress callbacks). A front end that can hold raw paths keeps them
21/// lossless instead, as Python does with `os.fsdecode`.
22///
23/// # Examples
24///
25/// ```
26/// use std::path::Path;
27///
28/// use exarch_core::path_text;
29///
30/// assert_eq!(
31/// path_text(Path::new("dir/caf\u{e9}.txt")),
32/// "dir/caf\u{e9}.txt"
33/// );
34/// # #[cfg(unix)]
35/// # {
36/// assert_eq!(path_text(Path::new("a\\b")), "a\\x5Cb");
37/// use std::ffi::OsStr;
38/// use std::os::unix::ffi::OsStrExt;
39///
40/// let raw = Path::new(OsStr::from_bytes(b"a\xffb"));
41/// assert_eq!(path_text(raw), "a\\xFFb");
42/// assert_ne!(path_text(raw), path_text(Path::new("a\\xFFb")));
43/// # }
44/// ```
45#[must_use]
46pub fn path_text(path: &Path) -> String {
47 let mut out = String::new();
48 push_path(&mut out, path);
49 out
50}
51
52fn push_text(out: &mut String, text: &str) {
53 for ch in text.chars() {
54 if ch == '\\' {
55 out.push_str("\\x5C");
56 } else {
57 out.push(ch);
58 }
59 }
60}
61
62/// Renders raw bytes of an archive name as text, by the rules of
63/// [`path_text`].
64///
65/// Valid UTF-8 is kept as it is except for backslashes (`\x5C`), and each
66/// invalid byte is written `\xNN`. Use it for names that are held as bytes, as
67/// they are stored in the archive, so two names that differ only in invalid
68/// bytes never render alike.
69///
70/// # Examples
71///
72/// ```
73/// use exarch_core::bytes_text;
74///
75/// assert_eq!(bytes_text(b"caf\xc3\xa9"), "caf\u{e9}");
76/// assert_eq!(bytes_text(b"caf\xe9"), "caf\\xE9");
77/// assert_ne!(bytes_text(b"caf\xe9"), bytes_text(b"caf\xe8"));
78/// ```
79#[must_use]
80pub fn bytes_text(bytes: &[u8]) -> String {
81 let mut out = String::new();
82 push_bytes(&mut out, bytes);
83 out
84}
85
86fn push_bytes(out: &mut String, bytes: &[u8]) {
87 for chunk in bytes.utf8_chunks() {
88 push_text(out, chunk.valid());
89 for byte in chunk.invalid() {
90 // Writing to a String cannot fail.
91 let _ = write!(out, "\\x{byte:02X}");
92 }
93 }
94}
95
96#[cfg(unix)]
97fn push_path(out: &mut String, path: &Path) {
98 use std::os::unix::ffi::OsStrExt;
99
100 push_bytes(out, path.as_os_str().as_bytes());
101}
102
103/// On Windows the components of the path are joined with `/`, whatever
104/// separator the path was spelled with, so a name reads the same on every
105/// host. A component of a normalized name never holds a `\`, which on Windows
106/// is a separator, so no two paths share a rendering.
107#[cfg(windows)]
108fn push_path(out: &mut String, path: &Path) {
109 use std::path::Component;
110
111 for component in path.components() {
112 match component {
113 Component::RootDir => out.push('/'),
114 other => {
115 if !out.is_empty() && !out.ends_with('/') {
116 out.push('/');
117 }
118 push_wide(out, other.as_os_str());
119 }
120 }
121 }
122}
123
124#[cfg(windows)]
125fn push_wide(out: &mut String, text: &std::ffi::OsStr) {
126 use std::os::windows::ffi::OsStrExt;
127
128 for unit in char::decode_utf16(text.encode_wide()) {
129 match unit {
130 Ok(ch) => push_text(out, ch.encode_utf8(&mut [0; 4])),
131 Err(unpaired) => {
132 // Writing to a String cannot fail.
133 let _ = write!(out, "\\u{:04X}", unpaired.unpaired_surrogate());
134 }
135 }
136 }
137}
138
139#[cfg(not(any(unix, windows)))]
140fn push_path(out: &mut String, path: &Path) {
141 push_text(out, &path.to_string_lossy());
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147
148 #[test]
149 fn valid_text_is_unchanged_but_for_backslashes() {
150 assert_eq!(path_text(Path::new("a/b é.txt")), "a/b é.txt");
151 #[cfg(unix)]
152 assert_eq!(path_text(Path::new("x\\y")), "x\\x5Cy");
153 #[cfg(windows)]
154 assert_eq!(path_text(Path::new("x\\y")), "x/y");
155 }
156
157 #[test]
158 fn bytes_are_escaped_the_same_on_every_platform() {
159 assert_eq!(bytes_text(b"x\\y"), "x\\x5Cy");
160 assert_eq!(bytes_text(b"a/b"), "a/b");
161 assert_eq!(bytes_text(b"caf\xe9"), "caf\\xE9");
162 assert_ne!(bytes_text(b"caf\xe9"), bytes_text(b"caf\xe8"));
163 assert_ne!(bytes_text(b"\xff"), bytes_text(b"\\xFF"));
164 }
165
166 #[cfg(windows)]
167 #[test]
168 fn windows_components_are_joined_with_a_forward_slash() {
169 assert_eq!(path_text(Path::new(r"x\y\z")), "x/y/z");
170 assert_eq!(path_text(Path::new(r"x/y\z")), "x/y/z");
171 assert_eq!(path_text(Path::new(r"a\.\b")), "a/b");
172 assert_eq!(
173 path_text(Path::new("x/y/z")),
174 path_text(Path::new(r"x\y\z"))
175 );
176 }
177
178 #[cfg(unix)]
179 #[test]
180 fn distinct_invalid_bytes_render_distinctly() {
181 use std::ffi::OsStr;
182 use std::os::unix::ffi::OsStrExt;
183
184 let render = |bytes: &[u8]| path_text(Path::new(OsStr::from_bytes(bytes)));
185 assert_eq!(render(b"a\xffb"), "a\\xFFb");
186 assert_eq!(render(b"a\xfeb"), "a\\xFEb");
187 assert_ne!(render(b"a\xffb"), render(b"a\\xFFb"));
188 }
189}