use core::ffi::CStr;
pub trait AsPath {
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;
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()
}
}
}
#[allow(dead_code)]
const STACK_LEN: usize = 512;
#[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);
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);
f(unsafe { CStr::from_bytes_with_nul_unchecked(&buf) })
}
#[cfg(not(feature = "alloc"))]
Err(ErrorKind::InvalidFilename.into())
}
#[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;
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())
}
#[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 {
out[len] = cp as u16;
len += 1;
}
}
Some(len)
}
#[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}");
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);
}
}