mod error;
mod ffi;
use std::{num::NonZeroU8, os::unix, path::Path};
pub use error::Error;
use o3::{alloc, mem::rc};
use crate::io::fs::{self, metadata::Metadata, open};
const MAX_COMPONENT_BYTES: usize = 255;
const _: () = assert!(MAX_COMPONENT_BYTES == u8::MAX as usize);
#[derive(Clone, Copy)]
pub struct Component<'a> {
bytes: &'a [u8],
}
pub struct Owned {
pub(super) bytes: Box<std::ffi::CStr>,
}
#[derive(Clone, Copy)]
pub struct Relative<'a> {
bytes: &'a [u8],
leaf_len: NonZeroU8,
}
pub struct Confined {
pub(super) directory: fs::Dir,
pub(super) path: Owned,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ConfineError {
Allocation(alloc::Error),
Retain(rc::Error),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ConcatError {
Length { length: usize, limit: usize },
Allocation(alloc::Error),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RelativeOpenError {
Length { length: usize, limit: usize },
Allocation(alloc::Error),
Retain(rc::Error),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CopyError {
Nul { position: usize },
Allocation(alloc::Error),
}
pub trait CStrExt: Sized {
fn try_copy(path: &Path) -> Result<Self, CopyError>;
}
impl CStrExt for Box<std::ffi::CStr> {
fn try_copy(path: &Path) -> Result<Self, CopyError> {
let bytes = unix::ffi::OsStrExt::as_bytes(path.as_os_str());
if let Ok(prefix) = std::ffi::CStr::from_bytes_until_nul(bytes) {
return Err(CopyError::Nul {
position: prefix.to_bytes().len(),
});
}
ffi::copy(bytes, &[]).map_err(CopyError::Allocation)
}
}
#[derive(Clone, Copy)]
pub struct Entry<'a> {
directory: &'a fs::Dir,
name: &'a Owned,
}
#[derive(Clone, Copy)]
pub struct Rename<'a> {
directory: &'a fs::Dir,
old: &'a Owned,
new: &'a Owned,
}
impl<'a> Component<'a> {
pub fn parse_os(value: &'a std::ffi::OsStr) -> Result<Self, Error> {
Self::parse_bytes(unix::ffi::OsStrExt::as_bytes(value))
}
pub const fn parse_bytes(bytes: &'a [u8]) -> Result<Self, Error> {
if let Some(offset) = position(bytes, b'/') {
return Err(Error::Nested { offset });
}
if let Some(position) = position(bytes, 0) {
return Err(Error::Nul { position });
}
match component_len(bytes, 0) {
Ok(_) => Ok(Self { bytes }),
Err(cause) => Err(cause),
}
}
pub fn try_to_owned(self) -> Result<Owned, alloc::Error> {
let bytes = ffi::copy(self.bytes, &[])?;
Ok(Owned { bytes })
}
pub fn try_concat(self, suffix: Component<'_>) -> Result<Owned, ConcatError> {
let bytes = try_join(self.bytes, self.bytes.len(), suffix.bytes)?;
Ok(Owned { bytes })
}
}
const fn position(bytes: &[u8], needle: u8) -> Option<usize> {
let mut index = 0;
while index < bytes.len() {
if bytes[index] == needle {
return Some(index);
}
index += 1;
}
None
}
const fn component_len(bytes: &[u8], offset: usize) -> Result<NonZeroU8, Error> {
match bytes {
[b'.'] => Err(Error::NoComponent { length: 1 }),
[b'.', b'.'] => Err(Error::Parent { offset }),
_ if bytes.len() > MAX_COMPONENT_BYTES => Err(Error::Component {
offset,
length: bytes.len(),
limit: MAX_COMPONENT_BYTES,
}),
_ => match NonZeroU8::new(bytes.len() as u8) {
Some(len) => Ok(len),
None => Err(Error::Empty),
},
}
}
impl<'a> Relative<'a> {
pub fn parse(bytes: &'a [u8]) -> Result<Self, Error> {
let mut offset = 0;
for part in bytes.split_inclusive(|b| matches!(b, b'/' | 0)) {
match part.split_last() {
Some((&0, prefix)) => {
return Err(Error::Nul {
position: offset + prefix.len(),
});
}
Some((&b'/', name)) => {
component_len(name, offset)?;
offset += part.len();
}
_ => {
let leaf_len = component_len(part, offset)?;
return Ok(Self { bytes, leaf_len });
}
}
}
Err(Error::Empty)
}
pub fn open(
self,
dir: &fs::Dir,
suffix: Option<Component<'_>>,
options: open::Options,
) -> Result<fs::raw::OpenRequest<()>, RelativeOpenError> {
let suffix = suffix.map_or(&[][..], |part| part.bytes);
let bytes =
try_join(self.bytes, usize::from(self.leaf_len.get()), suffix).map_err(|error| {
match error {
ConcatError::Length { length, limit } => {
RelativeOpenError::Length { length, limit }
}
ConcatError::Allocation(cause) => RelativeOpenError::Allocation(cause),
}
})?;
let dir = dir.try_retain().map_err(RelativeOpenError::Retain)?;
Ok(fs::raw::OpenRequest::at::<true>(dir, bytes, options))
}
}
fn try_join(
base: &[u8],
leaf_len: usize,
suffix: &[u8],
) -> Result<Box<std::ffi::CStr>, ConcatError> {
let length = leaf_len + suffix.len();
if length > MAX_COMPONENT_BYTES {
return Err(ConcatError::Length {
length,
limit: MAX_COMPONENT_BYTES,
});
}
ffi::copy(base, suffix).map_err(ConcatError::Allocation)
}
impl Owned {
pub(crate) fn as_c_str(&self) -> &std::ffi::CStr {
&self.bytes
}
}
impl Confined {
pub(in crate::io::fs) fn new(dir: fs::Dir, path: Owned) -> Self {
Self {
directory: dir,
path,
}
}
pub fn into_owned(self) -> Owned {
self.path
}
}
impl<'a> Entry<'a> {
pub(in crate::io::fs) fn new(dir: &'a fs::Dir, name: &'a Owned) -> Self {
Self {
directory: dir,
name,
}
}
pub(crate) fn directory(self) -> &'a fs::Dir {
self.directory
}
pub(crate) fn name(self) -> &'a std::ffi::CStr {
self.name.as_c_str()
}
pub fn metadata(self) -> Result<Metadata, crate::Errno> {
use std::os::fd::AsFd as _;
use dope_sys::io::file::File as _;
crate::Backend::metadata_at(Some(self.directory.as_fd()), self.name.as_c_str())
.map(Metadata::new)
}
}
impl<'a> Rename<'a> {
pub(in crate::io::fs) fn new(dir: &'a fs::Dir, old: &'a Owned, new: &'a Owned) -> Self {
Self {
directory: dir,
old,
new,
}
}
pub(crate) fn directory(self) -> &'a fs::Dir {
self.directory
}
pub(crate) fn old(self) -> &'a std::ffi::CStr {
self.old.as_c_str()
}
pub(crate) fn new_name(self) -> &'a std::ffi::CStr {
self.new.as_c_str()
}
}
const _: () = {
assert!(std::mem::size_of::<Owned>() == 2 * std::mem::size_of::<usize>());
assert!(std::mem::size_of::<Confined>() == 3 * std::mem::size_of::<usize>());
assert!(std::mem::size_of::<Entry<'_>>() == 2 * std::mem::size_of::<usize>());
assert!(std::mem::size_of::<Rename<'_>>() == 3 * std::mem::size_of::<usize>());
};