1mod error;
2mod ffi;
3
4use std::{num::NonZeroU8, os::unix, path::Path};
5
6pub use error::Error;
7use o3::{alloc, mem::rc};
8
9use crate::io::fs::{self, metadata::Metadata, open};
10
11const MAX_COMPONENT_BYTES: usize = 255;
12const _: () = assert!(MAX_COMPONENT_BYTES == u8::MAX as usize);
13
14#[derive(Clone, Copy)]
15pub struct Component<'a> {
16 bytes: &'a [u8],
17}
18
19pub struct Owned {
20 pub(super) bytes: Box<std::ffi::CStr>,
21}
22
23#[derive(Clone, Copy)]
24pub struct Relative<'a> {
25 bytes: &'a [u8],
26 leaf_len: NonZeroU8,
27}
28
29pub struct Confined {
30 pub(super) directory: fs::Dir,
31 pub(super) path: Owned,
32}
33
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub enum ConfineError {
36 Allocation(alloc::Error),
37 Retain(rc::Error),
38}
39
40#[derive(Clone, Copy, Debug, Eq, PartialEq)]
41pub enum ConcatError {
42 Length { length: usize, limit: usize },
43 Allocation(alloc::Error),
44}
45
46#[derive(Clone, Copy, Debug, Eq, PartialEq)]
47pub enum RelativeOpenError {
48 Length { length: usize, limit: usize },
49 Allocation(alloc::Error),
50 Retain(rc::Error),
51}
52
53#[derive(Clone, Copy, Debug, Eq, PartialEq)]
54pub enum CopyError {
55 Nul { position: usize },
56 Allocation(alloc::Error),
57}
58
59pub trait CStrExt: Sized {
61 fn try_copy(path: &Path) -> Result<Self, CopyError>;
62}
63
64impl CStrExt for Box<std::ffi::CStr> {
65 fn try_copy(path: &Path) -> Result<Self, CopyError> {
66 let bytes = unix::ffi::OsStrExt::as_bytes(path.as_os_str());
67 if let Ok(prefix) = std::ffi::CStr::from_bytes_until_nul(bytes) {
68 return Err(CopyError::Nul {
69 position: prefix.to_bytes().len(),
70 });
71 }
72 ffi::copy(bytes, &[]).map_err(CopyError::Allocation)
73 }
74}
75
76#[derive(Clone, Copy)]
77pub struct Entry<'a> {
78 directory: &'a fs::Dir,
79 name: &'a Owned,
80}
81
82#[derive(Clone, Copy)]
83pub struct Rename<'a> {
84 directory: &'a fs::Dir,
85 old: &'a Owned,
86 new: &'a Owned,
87}
88
89impl<'a> Component<'a> {
90 pub fn parse_os(value: &'a std::ffi::OsStr) -> Result<Self, Error> {
91 Self::parse_bytes(unix::ffi::OsStrExt::as_bytes(value))
92 }
93
94 pub const fn parse_bytes(bytes: &'a [u8]) -> Result<Self, Error> {
95 if let Some(offset) = position(bytes, b'/') {
96 return Err(Error::Nested { offset });
97 }
98 if let Some(position) = position(bytes, 0) {
99 return Err(Error::Nul { position });
100 }
101 match component_len(bytes, 0) {
102 Ok(_) => Ok(Self { bytes }),
103 Err(cause) => Err(cause),
104 }
105 }
106
107 pub fn try_to_owned(self) -> Result<Owned, alloc::Error> {
108 let bytes = ffi::copy(self.bytes, &[])?;
109 Ok(Owned { bytes })
110 }
111
112 pub fn try_concat(self, suffix: Component<'_>) -> Result<Owned, ConcatError> {
113 let bytes = try_join(self.bytes, self.bytes.len(), suffix.bytes)?;
114 Ok(Owned { bytes })
115 }
116}
117
118const fn position(bytes: &[u8], needle: u8) -> Option<usize> {
119 let mut index = 0;
120 while index < bytes.len() {
121 if bytes[index] == needle {
122 return Some(index);
123 }
124 index += 1;
125 }
126 None
127}
128
129const fn component_len(bytes: &[u8], offset: usize) -> Result<NonZeroU8, Error> {
130 match bytes {
131 [b'.'] => Err(Error::NoComponent { length: 1 }),
132 [b'.', b'.'] => Err(Error::Parent { offset }),
133 _ if bytes.len() > MAX_COMPONENT_BYTES => Err(Error::Component {
134 offset,
135 length: bytes.len(),
136 limit: MAX_COMPONENT_BYTES,
137 }),
138 _ => match NonZeroU8::new(bytes.len() as u8) {
139 Some(len) => Ok(len),
140 None => Err(Error::Empty),
141 },
142 }
143}
144
145impl<'a> Relative<'a> {
146 pub fn parse(bytes: &'a [u8]) -> Result<Self, Error> {
147 let mut offset = 0;
148 for part in bytes.split_inclusive(|b| matches!(b, b'/' | 0)) {
149 match part.split_last() {
150 Some((&0, prefix)) => {
151 return Err(Error::Nul {
152 position: offset + prefix.len(),
153 });
154 }
155 Some((&b'/', name)) => {
156 component_len(name, offset)?;
157 offset += part.len();
158 }
159 _ => {
160 let leaf_len = component_len(part, offset)?;
161 return Ok(Self { bytes, leaf_len });
162 }
163 }
164 }
165 Err(Error::Empty)
166 }
167
168 pub fn open(
169 self,
170 dir: &fs::Dir,
171 suffix: Option<Component<'_>>,
172 options: open::Options,
173 ) -> Result<fs::raw::OpenRequest<()>, RelativeOpenError> {
174 let suffix = suffix.map_or(&[][..], |part| part.bytes);
175 let bytes =
176 try_join(self.bytes, usize::from(self.leaf_len.get()), suffix).map_err(|error| {
177 match error {
178 ConcatError::Length { length, limit } => {
179 RelativeOpenError::Length { length, limit }
180 }
181 ConcatError::Allocation(cause) => RelativeOpenError::Allocation(cause),
182 }
183 })?;
184 let dir = dir.try_retain().map_err(RelativeOpenError::Retain)?;
185 Ok(fs::raw::OpenRequest::at::<true>(dir, bytes, options))
186 }
187}
188
189fn try_join(
190 base: &[u8],
191 leaf_len: usize,
192 suffix: &[u8],
193) -> Result<Box<std::ffi::CStr>, ConcatError> {
194 let length = leaf_len + suffix.len();
195 if length > MAX_COMPONENT_BYTES {
196 return Err(ConcatError::Length {
197 length,
198 limit: MAX_COMPONENT_BYTES,
199 });
200 }
201 ffi::copy(base, suffix).map_err(ConcatError::Allocation)
202}
203
204impl Owned {
205 pub(crate) fn as_c_str(&self) -> &std::ffi::CStr {
206 &self.bytes
207 }
208}
209
210impl Confined {
211 pub(in crate::io::fs) fn new(dir: fs::Dir, path: Owned) -> Self {
212 Self {
213 directory: dir,
214 path,
215 }
216 }
217
218 pub fn into_owned(self) -> Owned {
219 self.path
220 }
221}
222
223impl<'a> Entry<'a> {
224 pub(in crate::io::fs) fn new(dir: &'a fs::Dir, name: &'a Owned) -> Self {
225 Self {
226 directory: dir,
227 name,
228 }
229 }
230
231 pub(crate) fn directory(self) -> &'a fs::Dir {
232 self.directory
233 }
234
235 pub(crate) fn name(self) -> &'a std::ffi::CStr {
236 self.name.as_c_str()
237 }
238
239 pub fn metadata(self) -> Result<Metadata, crate::Errno> {
241 use std::os::fd::AsFd as _;
242
243 use dope_sys::io::file::File as _;
244
245 crate::Backend::metadata_at(Some(self.directory.as_fd()), self.name.as_c_str())
246 .map(Metadata::new)
247 }
248}
249
250impl<'a> Rename<'a> {
251 pub(in crate::io::fs) fn new(dir: &'a fs::Dir, old: &'a Owned, new: &'a Owned) -> Self {
252 Self {
253 directory: dir,
254 old,
255 new,
256 }
257 }
258
259 pub(crate) fn directory(self) -> &'a fs::Dir {
260 self.directory
261 }
262
263 pub(crate) fn old(self) -> &'a std::ffi::CStr {
264 self.old.as_c_str()
265 }
266
267 pub(crate) fn new_name(self) -> &'a std::ffi::CStr {
268 self.new.as_c_str()
269 }
270}
271
272const _: () = {
273 assert!(std::mem::size_of::<Owned>() == 2 * std::mem::size_of::<usize>());
274 assert!(std::mem::size_of::<Confined>() == 3 * std::mem::size_of::<usize>());
275 assert!(std::mem::size_of::<Entry<'_>>() == 2 * std::mem::size_of::<usize>());
276 assert!(std::mem::size_of::<Rename<'_>>() == 3 * std::mem::size_of::<usize>());
277};