1use core::{
2 mem::size_of,
3 ops::{Deref, DerefMut},
4 slice,
5};
6
7use crate::{
8 error::{Error, Result, EINVAL},
9 ENAMETOOLONG,
10};
11
12#[derive(Clone, Copy, Debug, Default)]
13#[repr(packed)]
14pub struct DirentHeader {
15 pub inode: u64,
16 pub next_opaque_id: u64,
20 pub record_len: u16,
23 pub kind: u8,
27}
28
29impl Deref for DirentHeader {
30 type Target = [u8];
31 fn deref(&self) -> &[u8] {
32 unsafe { slice::from_raw_parts(self as *const Self as *const u8, size_of::<Self>()) }
33 }
34}
35
36impl DerefMut for DirentHeader {
37 fn deref_mut(&mut self) -> &mut [u8] {
38 unsafe { slice::from_raw_parts_mut(self as *mut Self as *mut u8, size_of::<Self>()) }
39 }
40}
41#[derive(Clone, Copy, Debug, Default)]
42#[repr(u8)]
43pub enum DirentKind {
44 #[default]
45 Unspecified = 0,
46
47 Regular = 1,
48 Directory = 2,
49 Symlink = 3,
50 BlockDev = 4,
51 CharDev = 5,
52 Socket = 6,
53}
54impl DirentKind {
55 pub fn try_from_raw(raw: u8) -> Option<Self> {
57 Some(match raw {
58 0 => Self::Unspecified,
59
60 1 => Self::Regular,
61 2 => Self::Directory,
62 3 => Self::Symlink,
63 4 => Self::BlockDev,
64 5 => Self::CharDev,
65 6 => Self::Socket,
66
67 _ => return None,
68 })
69 }
70}
71
72pub struct DirentIter<'a>(&'a [u8]);
73
74impl<'a> DirentIter<'a> {
75 pub const fn new(buffer: &'a [u8]) -> Self {
76 Self(buffer)
77 }
78}
79#[derive(Debug)]
80pub struct Invalid;
81
82impl<'a> Iterator for DirentIter<'a> {
83 type Item = Result<(&'a DirentHeader, &'a [u8]), Invalid>;
84
85 fn next(&mut self) -> Option<Self::Item> {
86 if self.0.len() < size_of::<DirentHeader>() {
87 return None;
88 }
89 let header = unsafe { &*(self.0.as_ptr().cast::<DirentHeader>()) };
90 if self.0.len() < usize::from(header.record_len) {
91 return Some(Err(Invalid));
92 }
93 let (this, remaining) = self.0.split_at(usize::from(header.record_len));
94 self.0 = remaining;
95
96 let name_and_nul = &this[size_of::<DirentHeader>()..];
97 let name = &name_and_nul[..name_and_nul.len() - 1];
98
99 Some(Ok((header, name)))
100 }
101}
102
103#[derive(Debug)]
104pub struct DirentBuf<B> {
105 buffer: B,
106
107 header_size: u16,
112
113 written: usize,
114}
115pub trait Buffer<'a>: Sized + 'a {
117 fn empty() -> Self;
118 fn length(&self) -> usize;
119
120 fn split_at(self, index: usize) -> Option<[Self; 2]>;
125
126 fn copy_from_slice_exact(self, src: &[u8]) -> Result<()>;
131
132 fn zero_out(self) -> Result<()>;
137}
138impl<'a> Buffer<'a> for &'a mut [u8] {
139 fn empty() -> Self {
140 &mut []
141 }
142 fn length(&self) -> usize {
143 self.len()
144 }
145
146 fn split_at(self, index: usize) -> Option<[Self; 2]> {
147 self.split_at_mut_checked(index).map(|(a, b)| [a, b])
148 }
149 fn copy_from_slice_exact(self, src: &[u8]) -> Result<()> {
150 self.copy_from_slice(src);
151 Ok(())
152 }
153 fn zero_out(self) -> Result<()> {
154 self.fill(0);
155 Ok(())
156 }
157}
158
159pub struct DirEntry<'name> {
160 pub inode: u64,
161 pub next_opaque_id: u64,
162 pub name: &'name str,
163 pub kind: DirentKind,
164}
165
166impl<'a, B: Buffer<'a>> DirentBuf<B> {
167 pub fn new(buffer: B, header_size: u16) -> Option<Self> {
168 if usize::from(header_size) < size_of::<DirentHeader>() {
169 return None;
170 }
171
172 Some(Self {
173 buffer,
174 header_size,
175 written: 0,
176 })
177 }
178 pub fn entry(&mut self, entry: DirEntry<'_>) -> Result<()> {
179 let name16 = u16::try_from(entry.name.len()).map_err(|_| Error::new(EINVAL))?;
180 let record_len = self
181 .header_size
182 .checked_add(name16)
183 .and_then(|l| l.checked_add(1))
186 .ok_or(Error::new(ENAMETOOLONG))?;
187
188 let [this, remaining] = core::mem::replace(&mut self.buffer, B::empty())
189 .split_at(usize::from(record_len))
190 .ok_or(Error::new(EINVAL))?;
191
192 let [this_header_variable, this_name_and_nul] = this
193 .split_at(usize::from(self.header_size))
194 .expect("already know header_size + ... >= header_size");
195
196 let [this_name, this_name_nul] = this_name_and_nul
197 .split_at(usize::from(name16))
198 .expect("already know name.len() <= name.len() + 1");
199
200 let [this_header, this_header_extra] = this_header_variable
204 .split_at(size_of::<DirentHeader>())
205 .expect("already checked header_size <= size_of Header");
206
207 this_header.copy_from_slice_exact(&DirentHeader {
208 record_len,
209 next_opaque_id: entry.next_opaque_id,
210 inode: entry.inode,
211 kind: entry.kind as u8,
212 })?;
213 this_header_extra.zero_out()?;
214 this_name.copy_from_slice_exact(entry.name.as_bytes())?;
215 this_name_nul.copy_from_slice_exact(&[0])?;
216
217 self.written += usize::from(record_len);
218 self.buffer = remaining;
219
220 Ok(())
221 }
222 pub fn finalize(self) -> usize {
223 self.written
224 }
225}