oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Paths as the operating system takes them.

use core::ffi::CStr;

/// A path argument.
///
/// A path is a byte string, in the system's own encoding on Linux, macOS and
/// WASI (anything but NUL is allowed, UTF-8 is usual) and in UTF-8 on Windows,
/// where oscall converts it to UTF-16. Windows names that are not valid
/// Unicode are accepted the way `std` encodes them (WTF-8).
///
/// Implemented for `str`, `[u8]` and `CStr`, with the `alloc` feature for
/// `String` and `Vec<u8>`, and with the `std` feature for `Path`, `PathBuf`,
/// `OsStr` and `OsString`.
pub trait AsPath {
    /// The bytes of the path, with no trailing NUL.
    fn as_path_bytes(&self) -> &[u8];
}

impl AsPath for [u8] {
    #[inline]
    fn as_path_bytes(&self) -> &[u8] {
        self
    }
}

impl AsPath for str {
    #[inline]
    fn as_path_bytes(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsPath for CStr {
    #[inline]
    fn as_path_bytes(&self) -> &[u8] {
        self.to_bytes()
    }
}

impl<const N: usize> AsPath for [u8; N] {
    #[inline]
    fn as_path_bytes(&self) -> &[u8] {
        self
    }
}

impl<T: AsPath + ?Sized> AsPath for &T {
    #[inline]
    fn as_path_bytes(&self) -> &[u8] {
        T::as_path_bytes(self)
    }
}

#[cfg(feature = "alloc")]
impl AsPath for alloc::string::String {
    #[inline]
    fn as_path_bytes(&self) -> &[u8] {
        self.as_bytes()
    }
}

#[cfg(feature = "alloc")]
impl AsPath for alloc::vec::Vec<u8> {
    #[inline]
    fn as_path_bytes(&self) -> &[u8] {
        self
    }
}

#[cfg(feature = "alloc")]
impl AsPath for alloc::ffi::CString {
    #[inline]
    fn as_path_bytes(&self) -> &[u8] {
        self.to_bytes()
    }
}

#[cfg(feature = "std")]
mod std_impls {
    use std::ffi::{OsStr, OsString};
    use std::path::{Path, PathBuf};

    use super::AsPath;

    // `as_encoded_bytes` is the raw bytes on Unix-like systems and WTF-8 on
    // Windows: exactly the two encodings `AsPath` documents.
    impl AsPath for OsStr {
        #[inline]
        fn as_path_bytes(&self) -> &[u8] {
            self.as_encoded_bytes()
        }
    }

    impl AsPath for OsString {
        #[inline]
        fn as_path_bytes(&self) -> &[u8] {
            self.as_encoded_bytes()
        }
    }

    impl AsPath for Path {
        #[inline]
        fn as_path_bytes(&self) -> &[u8] {
            self.as_os_str().as_encoded_bytes()
        }
    }

    impl AsPath for PathBuf {
        #[inline]
        fn as_path_bytes(&self) -> &[u8] {
            self.as_os_str().as_encoded_bytes()
        }
    }
}

/// Paths up to this many bytes (or UTF-16 units) are converted on the stack.
/// Longer ones need the `alloc` feature and fail with `InvalidFilename`
/// without it.
#[allow(dead_code)]
const STACK_LEN: usize = 512;

/// Calls `f` with `path` as a NUL-terminated C string.
///
/// Fails with `InvalidInput` if the path contains a NUL.
#[cfg(not(any(windows, target_family = "wasm")))]
#[allow(dead_code)]
pub(crate) fn with_cstr<R>(
    path: &[u8],
    f: impl FnOnce(&CStr) -> crate::Result<R>,
) -> crate::Result<R> {
    use crate::ErrorKind;

    if path.contains(&0) {
        return Err(ErrorKind::InvalidInput.into());
    }
    if path.len() < STACK_LEN {
        let mut buf = [0u8; STACK_LEN];
        buf[..path.len()].copy_from_slice(path);
        // SAFETY: `path` has no NUL and the buffer is zero-filled after it.
        return f(unsafe { CStr::from_bytes_with_nul_unchecked(&buf[..=path.len()]) });
    }
    #[cfg(feature = "alloc")]
    {
        let mut buf = alloc::vec::Vec::new();
        buf.try_reserve_exact(path.len() + 1)
            .map_err(|_| ErrorKind::OutOfMemory)?;
        buf.extend_from_slice(path);
        buf.push(0);
        // SAFETY: `path` has no NUL and one was appended.
        f(unsafe { CStr::from_bytes_with_nul_unchecked(&buf) })
    }
    #[cfg(not(feature = "alloc"))]
    Err(ErrorKind::InvalidFilename.into())
}

/// Calls `f` with `path` converted to NUL-terminated UTF-16 (the slice
/// includes the NUL).
///
/// Fails with `InvalidInput` if the path contains a NUL or is not WTF-8.
#[cfg(any(windows, test))]
#[allow(dead_code)]
pub(crate) fn with_wide<R>(
    path: &[u8],
    f: impl FnOnce(&[u16]) -> crate::Result<R>,
) -> crate::Result<R> {
    use crate::ErrorKind;

    // UTF-16 never has more units than WTF-8 has bytes.
    if path.len() < STACK_LEN {
        let mut buf = [0u16; STACK_LEN];
        let len = wtf8_to_wide(path, &mut buf).ok_or(ErrorKind::InvalidInput)?;
        return f(&buf[..=len]);
    }
    #[cfg(feature = "alloc")]
    {
        let mut buf = alloc::vec::Vec::new();
        buf.try_reserve_exact(path.len() + 1)
            .map_err(|_| ErrorKind::OutOfMemory)?;
        buf.resize(path.len() + 1, 0u16);
        let len = wtf8_to_wide(path, &mut buf).ok_or(ErrorKind::InvalidInput)?;
        f(&buf[..=len])
    }
    #[cfg(not(feature = "alloc"))]
    Err(ErrorKind::InvalidFilename.into())
}

/// Converts WTF-8 (UTF-8 that may also encode lone surrogates) to UTF-16,
/// and returns the number of units written. `out` must be longer than
/// `src`; the unit after the last one written is left untouched.
///
/// `None` if `src` is malformed or contains a NUL.
#[cfg(any(windows, test))]
#[allow(dead_code)]
fn wtf8_to_wide(src: &[u8], out: &mut [u16]) -> Option<usize> {
    let mut len = 0;
    let mut i = 0;
    while i < src.len() {
        let b = src[i];
        let (extra, min, mut cp) = match b {
            0 => return None,
            0x01..=0x7f => (0, 0, b as u32),
            0xc2..=0xdf => (1, 0x80, (b & 0x1f) as u32),
            0xe0..=0xef => (2, 0x800, (b & 0x0f) as u32),
            0xf0..=0xf4 => (3, 0x1_0000, (b & 0x07) as u32),
            _ => return None,
        };
        for _ in 0..extra {
            i += 1;
            let c = *src.get(i)?;
            if c & 0xc0 != 0x80 {
                return None;
            }
            cp = cp << 6 | (c & 0x3f) as u32;
        }
        i += 1;
        if cp < min || cp > 0x10_ffff {
            return None;
        }
        if cp >= 0x1_0000 {
            let cp = cp - 0x1_0000;
            out[len] = 0xd800 | (cp >> 10) as u16;
            out[len + 1] = 0xdc00 | (cp & 0x3ff) as u16;
            len += 2;
        } else {
            // Includes lone surrogates, which WTF-8 encodes like any other
            // three-byte code point.
            out[len] = cp as u16;
            len += 1;
        }
    }
    Some(len)
}

/// Converts UTF-16 that may hold lone surrogates to WTF-8, and returns the
/// number of bytes written, or `None` if `out` is too small. Three bytes per
/// unit always suffice.
#[cfg(any(windows, test))]
#[allow(dead_code)]
pub(crate) fn wide_to_wtf8(src: &[u16], out: &mut [u8]) -> Option<usize> {
    let mut len = 0;
    let mut i = 0;
    while i < src.len() {
        let mut cp = src[i] as u32;
        i += 1;
        if (0xd800..0xdc00).contains(&cp)
            && let Some(&low) = src.get(i)
            && (0xdc00..0xe000).contains(&low)
        {
            cp = 0x1_0000 + ((cp - 0xd800) << 10 | (low as u32 - 0xdc00));
            i += 1;
        }
        let n = match cp {
            0..0x80 => 1,
            0x80..0x800 => 2,
            0x800..0x1_0000 => 3,
            _ => 4,
        };
        let dst = out.get_mut(len..len + n)?;
        match n {
            1 => dst[0] = cp as u8,
            2 => {
                dst[0] = 0xc0 | (cp >> 6) as u8;
                dst[1] = 0x80 | (cp & 0x3f) as u8;
            }
            3 => {
                dst[0] = 0xe0 | (cp >> 12) as u8;
                dst[1] = 0x80 | (cp >> 6 & 0x3f) as u8;
                dst[2] = 0x80 | (cp & 0x3f) as u8;
            }
            _ => {
                dst[0] = 0xf0 | (cp >> 18) as u8;
                dst[1] = 0x80 | (cp >> 12 & 0x3f) as u8;
                dst[2] = 0x80 | (cp >> 6 & 0x3f) as u8;
                dst[3] = 0x80 | (cp & 0x3f) as u8;
            }
        }
        len += n;
    }
    Some(len)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ErrorKind;

    #[test]
    #[cfg(not(any(windows, target_family = "wasm")))]
    fn cstr() {
        assert_eq!(
            with_cstr(b"/tmp/x", |p| Ok(p.to_bytes_with_nul().len())),
            Ok(7)
        );
        assert_eq!(with_cstr(b"", |p| Ok(p.to_bytes_with_nul().len())), Ok(1));
        assert_eq!(
            with_cstr(b"a\0b", |_| Ok(())).unwrap_err().kind(),
            ErrorKind::InvalidInput
        );
        let long = [b'a'; 5000];
        let result = with_cstr(&long, |p| Ok(p.to_bytes().len()));
        if cfg!(feature = "alloc") {
            assert_eq!(result, Ok(5000));
        } else {
            assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidFilename);
        }
    }

    #[test]
    fn wide() {
        let check = |s: &str| {
            let mut expected = [0u16; 64];
            let mut n = 0;
            for unit in s.encode_utf16() {
                expected[n] = unit;
                n += 1;
            }
            with_wide(s.as_bytes(), |w| {
                assert_eq!(w, &expected[..=n]);
                let mut back = [0u8; 64];
                let len = wide_to_wtf8(&w[..n], &mut back).unwrap();
                assert_eq!(&back[..len], s.as_bytes());
                Ok(())
            })
            .unwrap();
        };
        check("");
        check("C:\\dir\\file.txt");
        check("h\u{e9}llo \u{4e16}\u{754c} \u{1f600}");

        // A lone surrogate survives the round trip.
        let lone = [0xed, 0xa0, 0x80, b'x'];
        with_wide(&lone, |w| {
            assert_eq!(w, [0xd800, b'x' as u16, 0]);
            let mut back = [0u8; 8];
            assert_eq!(wide_to_wtf8(&w[..2], &mut back), Some(4));
            assert_eq!(back[..4], lone);
            Ok(())
        })
        .unwrap();

        for bad in [
            &b"a\0b"[..],
            b"\xff",
            b"\xc3",
            b"\xc0\x80",
            b"\xf5\x80\x80\x80",
        ] {
            assert_eq!(
                with_wide(bad, |_| Ok(())).unwrap_err().kind(),
                ErrorKind::InvalidInput
            );
        }
        let mut small = [0u8; 2];
        assert_eq!(wide_to_wtf8(&[0x4e16], &mut small), None);
    }
}