use std::fmt::Write as _;
use std::path::Path;
#[must_use]
pub fn path_text(path: &Path) -> String {
let mut out = String::new();
push_path(&mut out, path);
out
}
fn push_text(out: &mut String, text: &str) {
for ch in text.chars() {
if ch == '\\' {
out.push_str("\\x5C");
} else {
out.push(ch);
}
}
}
#[must_use]
pub fn bytes_text(bytes: &[u8]) -> String {
let mut out = String::new();
push_bytes(&mut out, bytes);
out
}
fn push_bytes(out: &mut String, bytes: &[u8]) {
for chunk in bytes.utf8_chunks() {
push_text(out, chunk.valid());
for byte in chunk.invalid() {
let _ = write!(out, "\\x{byte:02X}");
}
}
}
#[cfg(unix)]
fn push_path(out: &mut String, path: &Path) {
use std::os::unix::ffi::OsStrExt;
push_bytes(out, path.as_os_str().as_bytes());
}
#[cfg(windows)]
fn push_path(out: &mut String, path: &Path) {
use std::path::Component;
for component in path.components() {
match component {
Component::RootDir => out.push('/'),
other => {
if !out.is_empty() && !out.ends_with('/') {
out.push('/');
}
push_wide(out, other.as_os_str());
}
}
}
}
#[cfg(windows)]
fn push_wide(out: &mut String, text: &std::ffi::OsStr) {
use std::os::windows::ffi::OsStrExt;
for unit in char::decode_utf16(text.encode_wide()) {
match unit {
Ok(ch) => push_text(out, ch.encode_utf8(&mut [0; 4])),
Err(unpaired) => {
let _ = write!(out, "\\u{:04X}", unpaired.unpaired_surrogate());
}
}
}
}
#[cfg(not(any(unix, windows)))]
fn push_path(out: &mut String, path: &Path) {
push_text(out, &path.to_string_lossy());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_text_is_unchanged_but_for_backslashes() {
assert_eq!(path_text(Path::new("a/b é.txt")), "a/b é.txt");
#[cfg(unix)]
assert_eq!(path_text(Path::new("x\\y")), "x\\x5Cy");
#[cfg(windows)]
assert_eq!(path_text(Path::new("x\\y")), "x/y");
}
#[test]
fn bytes_are_escaped_the_same_on_every_platform() {
assert_eq!(bytes_text(b"x\\y"), "x\\x5Cy");
assert_eq!(bytes_text(b"a/b"), "a/b");
assert_eq!(bytes_text(b"caf\xe9"), "caf\\xE9");
assert_ne!(bytes_text(b"caf\xe9"), bytes_text(b"caf\xe8"));
assert_ne!(bytes_text(b"\xff"), bytes_text(b"\\xFF"));
}
#[cfg(windows)]
#[test]
fn windows_components_are_joined_with_a_forward_slash() {
assert_eq!(path_text(Path::new(r"x\y\z")), "x/y/z");
assert_eq!(path_text(Path::new(r"x/y\z")), "x/y/z");
assert_eq!(path_text(Path::new(r"a\.\b")), "a/b");
assert_eq!(
path_text(Path::new("x/y/z")),
path_text(Path::new(r"x\y\z"))
);
}
#[cfg(unix)]
#[test]
fn distinct_invalid_bytes_render_distinctly() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let render = |bytes: &[u8]| path_text(Path::new(OsStr::from_bytes(bytes)));
assert_eq!(render(b"a\xffb"), "a\\xFFb");
assert_eq!(render(b"a\xfeb"), "a\\xFEb");
assert_ne!(render(b"a\xffb"), render(b"a\\xFFb"));
}
}