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
42#[derive(Clone, Copy, Debug, Default)]
44#[repr(u8)]
45pub enum DirentKind {
46 #[default]
47 Unspecified = 0,
48
49 CharDev = 2,
50 Directory = 4,
51 BlockDev = 6,
52 Regular = 8,
53 Symlink = 10,
54 Socket = 12,
55}
56
57impl DirentKind {
58 pub fn try_from_raw(raw: u8) -> Option<Self> {
60 Some(match raw {
61 0 => Self::Unspecified,
62
63 2 => Self::CharDev,
64 4 => Self::Directory,
65 6 => Self::BlockDev,
66 8 => Self::Regular,
67 10 => Self::Symlink,
68 12 => Self::Socket,
69
70 _ => return None,
71 })
72 }
73}
74
75pub struct DirentIter<'a>(&'a [u8]);
76
77impl<'a> DirentIter<'a> {
78 pub const fn new(buffer: &'a [u8]) -> Self {
79 Self(buffer)
80 }
81}
82#[derive(Debug)]
83pub struct Invalid;
84
85impl<'a> Iterator for DirentIter<'a> {
86 type Item = Result<(&'a DirentHeader, &'a [u8]), Invalid>;
87
88 fn next(&mut self) -> Option<Self::Item> {
89 if self.0.len() < size_of::<DirentHeader>() {
90 return None;
91 }
92 let header = unsafe { &*(self.0.as_ptr().cast::<DirentHeader>()) };
93 if self.0.len() < usize::from(header.record_len) {
94 return Some(Err(Invalid));
95 }
96 let (this, remaining) = self.0.split_at(usize::from(header.record_len));
97 self.0 = remaining;
98
99 let name_and_nul = &this[size_of::<DirentHeader>()..];
100 let name = &name_and_nul[..name_and_nul.len() - 1];
101
102 Some(Ok((header, name)))
103 }
104}
105
106#[derive(Debug)]
107pub struct DirentBuf<B> {
108 buffer: B,
109
110 header_size: u16,
115
116 written: usize,
117}
118pub trait Buffer<'a>: Sized + 'a {
120 fn empty() -> Self;
121 fn length(&self) -> usize;
122
123 fn split_at(self, index: usize) -> Option<[Self; 2]>;
128
129 fn copy_from_slice_exact(self, src: &[u8]) -> Result<()>;
134
135 fn zero_out(self) -> Result<()>;
140}
141impl<'a> Buffer<'a> for &'a mut [u8] {
142 fn empty() -> Self {
143 &mut []
144 }
145 fn length(&self) -> usize {
146 self.len()
147 }
148
149 fn split_at(self, index: usize) -> Option<[Self; 2]> {
150 self.split_at_mut_checked(index).map(|(a, b)| [a, b])
151 }
152 fn copy_from_slice_exact(self, src: &[u8]) -> Result<()> {
153 self.copy_from_slice(src);
154 Ok(())
155 }
156 fn zero_out(self) -> Result<()> {
157 self.fill(0);
158 Ok(())
159 }
160}
161
162pub struct DirEntry<'name> {
163 pub inode: u64,
164 pub next_opaque_id: u64,
165 pub name: &'name str,
166 pub kind: DirentKind,
167}
168
169impl<'a, B: Buffer<'a>> DirentBuf<B> {
170 pub fn new(buffer: B, header_size: u16) -> Option<Self> {
171 if usize::from(header_size) < size_of::<DirentHeader>() {
172 return None;
173 }
174
175 Some(Self {
176 buffer,
177 header_size,
178 written: 0,
179 })
180 }
181 pub fn entry(&mut self, entry: DirEntry<'_>) -> Result<()> {
182 let name16 = u16::try_from(entry.name.len()).map_err(|_| Error::new(EINVAL))?;
183 let record_len = self
184 .header_size
185 .checked_add(name16)
186 .and_then(|l| l.checked_add(1))
189 .ok_or(Error::new(ENAMETOOLONG))?;
190
191 let [this, remaining] = core::mem::replace(&mut self.buffer, B::empty())
192 .split_at(usize::from(record_len))
193 .ok_or(Error::new(EINVAL))?;
194
195 let [this_header_variable, this_name_and_nul] = this
196 .split_at(usize::from(self.header_size))
197 .expect("already know header_size + ... >= header_size");
198
199 let [this_name, this_name_nul] = this_name_and_nul
200 .split_at(usize::from(name16))
201 .expect("already know name.len() <= name.len() + 1");
202
203 let [this_header, this_header_extra] = this_header_variable
207 .split_at(size_of::<DirentHeader>())
208 .expect("already checked header_size <= size_of Header");
209
210 this_header.copy_from_slice_exact(&DirentHeader {
211 record_len,
212 next_opaque_id: entry.next_opaque_id,
213 inode: entry.inode,
214 kind: entry.kind as u8,
215 })?;
216 this_header_extra.zero_out()?;
217 this_name.copy_from_slice_exact(entry.name.as_bytes())?;
218 this_name_nul.copy_from_slice_exact(&[0])?;
219
220 self.written += usize::from(record_len);
221 self.buffer = remaining;
222
223 Ok(())
224 }
225 pub fn finalize(self) -> usize {
226 self.written
227 }
228}