use std::path::PathBuf;
fn is_safe(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/')
}
pub fn file_uri_from_bytes(path: &[u8]) -> String {
let mut uri = String::from("file://");
for &byte in path {
if is_safe(byte) {
uri.push(byte as char);
} else {
uri.push_str(&format!("%{byte:02X}"));
}
}
uri
}
pub fn uri_list(paths: &[PathBuf]) -> String {
let mut out = String::new();
for path in paths {
out.push_str(&file_uri_from_bytes(path_bytes(path)));
out.push_str("\r\n");
}
out
}
fn path_bytes(path: &PathBuf) -> &[u8] {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
path.as_os_str().as_bytes()
}
#[cfg(not(unix))]
{
path.to_str().unwrap_or_default().as_bytes()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_path_is_untouched() {
assert_eq!(
file_uri_from_bytes(b"/home/user/notes.txt"),
"file:///home/user/notes.txt"
);
}
#[test]
fn separators_stay_separators() {
assert!(file_uri_from_bytes(b"/a/b/c").ends_with("/a/b/c"));
}
#[test]
fn unreserved_punctuation_survives() {
assert_eq!(
file_uri_from_bytes(b"/tmp/a-b_c.d~e"),
"file:///tmp/a-b_c.d~e"
);
}
#[test]
fn spaces_and_delimiters_are_escaped() {
assert_eq!(
file_uri_from_bytes(b"/tmp/my file #1 (50%).txt"),
"file:///tmp/my%20file%20%231%20%2850%25%29.txt"
);
}
#[test]
fn question_mark_is_escaped() {
assert_eq!(
file_uri_from_bytes(b"/tmp/what?.txt"),
"file:///tmp/what%3F.txt"
);
}
#[test]
fn non_ascii_is_encoded_per_utf8_byte() {
assert_eq!(
file_uri_from_bytes("/tmp/æ".as_bytes()),
"file:///tmp/%C3%A6"
);
}
#[test]
fn invalid_utf8_round_trips() {
assert_eq!(file_uri_from_bytes(b"/tmp/\xFF"), "file:///tmp/%FF");
}
#[test]
fn hex_escapes_are_uppercase() {
assert_eq!(file_uri_from_bytes(b"/\x1b"), "file:///%1B");
}
#[test]
fn every_line_is_crlf_terminated() {
let list = uri_list(&[PathBuf::from("/a"), PathBuf::from("/b")]);
assert_eq!(list, "file:///a\r\nfile:///b\r\n");
}
#[test]
fn empty_list_is_empty() {
assert_eq!(uri_list(&[]), "");
}
#[cfg(unix)]
#[test]
fn non_utf8_path_survives_the_list() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let path = PathBuf::from(OsString::from_vec(b"/tmp/\xFFname".to_vec()));
assert_eq!(uri_list(&[path]), "file:///tmp/%FFname\r\n");
}
}