oxinav-core 0.5.0

Core logic for OxiNav: file operations, pane state, archives and viewing, with no UI dependency
Documentation
//! Encoding paths as a `text/uri-list` payload.
//!
//! This is what a drag-and-drop or clipboard transfer carries when the thing
//! being transferred is a file: one `file://` URI per line, which is the form
//! browsers and chat clients read to turn a drop into a real file.
//!
//! The encoder works on **bytes** rather than `&str` on purpose. Unix
//! filenames are arbitrary byte strings, not guaranteed UTF-8, and routing
//! them through `to_string_lossy()` would replace the offending bytes with
//! U+FFFD — producing a well-formed URI that points at a file which does not
//! exist. Percent-encoding the raw bytes instead round-trips whatever the
//! filesystem actually holds.

use std::path::PathBuf;

/// Bytes that survive unescaped in a path: RFC 3986's "unreserved" set, plus
/// `/`, which is the path separator and must stay a separator.
fn is_safe(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/')
}

/// Percent-encode one absolute path's bytes into a `file://` URI.
///
/// Takes bytes rather than a `Path` so that non-UTF-8 names can be tested
/// directly, and so nothing has to be lossily converted on the way in.
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 {
            // Uppercase hex: RFC 3986 says producers should normalise to it.
            uri.push_str(&format!("%{byte:02X}"));
        }
    }
    uri
}

/// One `file://` URI per path, CRLF-separated.
///
/// RFC 2483 specifies CRLF line endings and allows a trailing one; receivers
/// are far more consistent about accepting the trailing CRLF than about
/// coping with its absence, so every line gets one. An empty list encodes as
/// the empty string rather than a lone CRLF, so that "nothing to drag" is
/// distinguishable from "one unnamed thing".
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
}

/// A path's raw bytes.
///
/// Unix hands these over directly. Elsewhere there is no byte view of a path,
/// and no drag implementation either, so the lossy conversion there is
/// unreachable rather than merely tolerated.
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() {
        // Encoding `/` would collapse the path into a single opaque segment.
        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() {
        // A raw space ends the URI for most parsers, and `#` would start a
        // fragment — both would truncate the filename rather than fail loudly.
        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() {
        // "æ" is 0xC3 0xA6 in UTF-8, and each byte is escaped separately.
        assert_eq!(
            file_uri_from_bytes("/tmp/æ".as_bytes()),
            "file:///tmp/%C3%A6"
        );
    }

    #[test]
    fn invalid_utf8_round_trips() {
        // The reason this encoder takes bytes: 0xFF is not valid UTF-8, but it
        // is a perfectly legal filename byte, and a lossy conversion would
        // turn it into U+FFFD and name a different file.
        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() {
        // Not a bare CRLF, which would read as one empty URI.
        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");
    }
}