Skip to main content

virtual_file_system/
file.rs

1use super::VirtualFileSystem;
2use crate::{IoErrorKind, ItemStatic, Result, SynchronousFile, poll, suspend_on};
3use alloc::{vec, vec::Vec};
4use embedded_io_async::ErrorType;
5use exported_file_system::{AccessFlags, ControlCommand, CreateFlags, Permissions};
6use file_system::{Context, Flags, Inode, Path, Position, Size, StateFlags, Statistics};
7use task::TaskIdentifier;
8use users::{GroupIdentifier, UserIdentifier};
9
10/// File structure.
11///
12/// This structure is used to represent a file in the virtual file system.
13/// This is a wrapper around the virtual file system file identifier.
14#[derive(Debug)]
15pub struct File<'a>(SynchronousFile<'a>);
16
17impl<'a> File<'a> {
18    /// Wrap an existing file for async I/O, preserving its cursor, flags and authority.
19    pub const fn from_synchronous_file(file: SynchronousFile<'a>) -> Self {
20        Self(file)
21    }
22
23    pub fn as_synchronous_file_mut(&mut self) -> &mut SynchronousFile<'a> {
24        &mut self.0
25    }
26}
27
28impl ErrorType for File<'_> {
29    type Error = IoErrorKind;
30}
31
32impl embedded_io_async::Write for File<'_> {
33    async fn write(&mut self, buf: &[u8]) -> core::result::Result<usize, Self::Error> {
34        File::write(self, buf).await
35    }
36
37    async fn flush(&mut self) -> core::result::Result<(), Self::Error> {
38        File::flush(self).await
39    }
40}
41
42impl core::fmt::Write for File<'_> {
43    fn write_str(&mut self, s: &str) -> core::fmt::Result {
44        if let Err(e) = suspend_on(self.write(s.as_bytes())) {
45            log::error!("Error writing string to file: {}", e);
46            return Err(core::fmt::Error);
47        }
48        Ok(())
49    }
50}
51
52impl<'a> File<'a> {
53    fn nonblocking(&self) -> bool {
54        self.0.state().contains(StateFlags::NonBlocking)
55    }
56
57    pub(crate) fn new(
58        virtual_file_system: &'a VirtualFileSystem,
59        item: ItemStatic,
60        flags: Flags,
61        context: Context,
62    ) -> Self {
63        Self(SynchronousFile::new(
64            virtual_file_system,
65            item,
66            0,
67            flags,
68            context,
69        ))
70    }
71
72    pub(crate) const fn with_device_inode(mut self, inode: Inode) -> Self {
73        self.0.device_inode = Some(inode);
74        self
75    }
76
77    pub(crate) fn with_authority(mut self, authority: task::TaskAuthority<'static>) -> Self {
78        self.0.authority = Some(authority);
79        self
80    }
81
82    pub async fn open(
83        virtual_file_system: &'a VirtualFileSystem,
84        task: task::TaskIdentifier,
85        path: impl AsRef<Path>,
86        flags: Flags,
87    ) -> Result<Self> {
88        let file_identifier = virtual_file_system
89            .open(&path.as_ref(), flags, task)
90            .await?;
91
92        Ok(file_identifier)
93    }
94
95    /// Open a file; a file that the call creates gets `permissions` from its
96    /// creation on (see `VirtualFileSystem::open_with_permissions`).
97    pub async fn open_with_permissions(
98        virtual_file_system: &'a VirtualFileSystem,
99        task: task::TaskIdentifier,
100        path: impl AsRef<Path>,
101        flags: Flags,
102        permissions: Permissions,
103    ) -> Result<Self> {
104        virtual_file_system
105            .open_with_permissions(&path.as_ref(), flags, task, permissions)
106            .await
107    }
108
109    pub async fn create_unnamed_pipe(
110        file_system: &'a VirtualFileSystem,
111        size: usize,
112        status: StateFlags,
113    ) -> Result<(Self, Self)> {
114        file_system.create_unnamed_pipe(size, status).await
115    }
116
117    pub async fn set_position(&mut self, position: &Position) -> Result<Size> {
118        poll(|| self.0.set_position(position)).await
119    }
120
121    // - Operations
122
123    pub async fn write(&mut self, buffer: &[u8]) -> Result<usize> {
124        self.write_with_offset(buffer, None).await
125    }
126
127    /// Transfer at an explicit offset without changing this opening's cursor.
128    pub async fn write_at(&mut self, buffer: &[u8], offset: Size) -> Result<usize> {
129        self.write_with_offset(buffer, Some(offset)).await
130    }
131
132    /// Transfer using an explicit offset, or the opening's cursor when absent.
133    pub async fn write_with_offset(
134        &mut self,
135        buffer: &[u8],
136        offset: Option<Size>,
137    ) -> Result<usize> {
138        if self.nonblocking() {
139            return match offset {
140                Some(offset) => self.0.write_at(buffer, offset),
141                None => self.0.write(buffer),
142            };
143        }
144        crate::operation::write(&mut self.0, buffer, offset).await
145    }
146
147    /// Fill the entire slice, returning an I/O error on premature EOF.
148    /// Close explicitly on success or failure; preserve the I/O error if close
149    /// also fails.
150    pub async fn read_slice_from_path(
151        virtual_file_system: &VirtualFileSystem,
152        task: TaskIdentifier,
153        path: impl AsRef<Path>,
154        buffer: &mut [u8],
155    ) -> Result<()> {
156        Self::read_slice_from_path_inner(virtual_file_system, task, path.as_ref(), buffer, false)
157            .await
158    }
159
160    /// Fill the entire slice from a mounted character device. A missing device
161    /// or an opened handle of another kind returns `UnavailableDriver`.
162    pub async fn read_slice_from_character_device(
163        virtual_file_system: &VirtualFileSystem,
164        task: TaskIdentifier,
165        path: impl AsRef<Path>,
166        buffer: &mut [u8],
167    ) -> Result<()> {
168        Self::read_slice_from_path_inner(virtual_file_system, task, path.as_ref(), buffer, true)
169            .await
170    }
171
172    async fn read_slice_from_path_inner(
173        virtual_file_system: &VirtualFileSystem,
174        task: TaskIdentifier,
175        path: &Path,
176        buffer: &mut [u8],
177        require_character_device: bool,
178    ) -> Result<()> {
179        let mut file = match File::open(
180            virtual_file_system,
181            task,
182            path,
183            Flags::new(AccessFlags::Read, None, None),
184        )
185        .await
186        {
187            Err(IoErrorKind::NotFound | IoErrorKind::StaleHandle) if require_character_device => {
188                return Err(IoErrorKind::DeviceUnavailable);
189            }
190            opened => opened?,
191        };
192
193        let result = async {
194            if require_character_device && !matches!(file.0.item, ItemStatic::CharacterDevice(_)) {
195                return Err(IoErrorKind::DeviceUnavailable);
196            }
197            let mut offset = 0;
198            while offset < buffer.len() {
199                let count = file.read(&mut buffer[offset..]).await?;
200                if count == 0 {
201                    return Err(IoErrorKind::InputOutput);
202                }
203                offset += count;
204            }
205            Ok(())
206        }
207        .await;
208        let close = file.close(virtual_file_system).await;
209        result.and(close)
210    }
211
212    pub async fn read_from_path(
213        virtual_file_system: &VirtualFileSystem,
214        task: TaskIdentifier,
215        path: impl AsRef<Path>,
216        buffer: &mut Vec<u8>,
217    ) -> Result<()> {
218        Self::read_from_path_inner(virtual_file_system, task, path.as_ref(), buffer).await
219    }
220
221    async fn read_from_path_inner(
222        virtual_file_system: &VirtualFileSystem,
223        task: TaskIdentifier,
224        path: &Path,
225        buffer: &mut Vec<u8>,
226    ) -> Result<()> {
227        buffer.clear();
228
229        let mut file = File::open(
230            virtual_file_system,
231            task,
232            path,
233            Flags::new(AccessFlags::Read, None, None),
234        )
235        .await?;
236
237        let result = file.read_to_end(buffer, 256).await.map(|_| ());
238        let close = file.close(virtual_file_system).await;
239        result.and(close)
240    }
241
242    /// Write the entire buffer, retrying short writes and rejecting zero progress.
243    /// Close explicitly on success or failure.
244    pub async fn write_to_path(
245        virtual_file_system: &VirtualFileSystem,
246        task: task::TaskIdentifier,
247        path: impl AsRef<Path>,
248        buffer: &[u8],
249    ) -> Result<()> {
250        Self::write_to_path_inner(virtual_file_system, task, path.as_ref(), buffer).await
251    }
252
253    async fn write_to_path_inner(
254        virtual_file_system: &VirtualFileSystem,
255        task: task::TaskIdentifier,
256        path: &Path,
257        buffer: &[u8],
258    ) -> Result<()> {
259        let mut file = File::open(
260            virtual_file_system,
261            task,
262            path,
263            Flags::new(AccessFlags::Write, Some(CreateFlags::CREATE_TRUNCATE), None),
264        )
265        .await?;
266
267        let result = async {
268            let mut offset = 0;
269            while offset < buffer.len() {
270                let count = file.write(&buffer[offset..]).await?;
271                if count == 0 {
272                    return Err(IoErrorKind::WriteZero);
273                }
274                offset += count;
275            }
276            Ok(())
277        }
278        .await;
279        let close = file.close(virtual_file_system).await;
280        result.and(close)
281    }
282
283    pub async fn write_line(&mut self, buffer: &[u8]) -> Result<usize> {
284        let mut written = 0;
285        for part in [buffer, b"\n".as_slice()] {
286            let mut offset = 0;
287            while offset < part.len() {
288                match self.write(&part[offset..]).await {
289                    Ok(0) => return Err(IoErrorKind::WriteZero),
290                    Ok(count) => {
291                        offset += count;
292                        written += count;
293                    }
294                    Err(IoErrorKind::WouldBlock) if self.nonblocking() && written > 0 => {
295                        return Ok(written);
296                    }
297                    Err(error) => return Err(error),
298                }
299            }
300        }
301        Ok(written)
302    }
303
304    pub async fn display_content<W: embedded_io_async::Write>(
305        &mut self,
306        w: &mut W,
307        buffer_size: usize,
308    ) -> Result<()> {
309        let mut buffer = vec![0u8; buffer_size];
310        loop {
311            let bytes_read = self.read(&mut buffer).await?;
312
313            if bytes_read == 0 {
314                break;
315            }
316
317            w.write(&buffer[..bytes_read])
318                .await
319                .map_err(|_| IoErrorKind::WriteZero)?;
320        }
321
322        Ok(())
323    }
324
325    pub async fn read(&mut self, buffer: &mut [u8]) -> Result<usize> {
326        self.read_with_offset(buffer, None).await
327    }
328
329    /// Transfer at an explicit offset without changing this opening's cursor.
330    pub async fn read_at(&mut self, buffer: &mut [u8], offset: Size) -> Result<usize> {
331        self.read_with_offset(buffer, Some(offset)).await
332    }
333
334    /// Transfer using an explicit offset, or the opening's cursor when absent.
335    pub async fn read_with_offset(
336        &mut self,
337        buffer: &mut [u8],
338        offset: Option<Size>,
339    ) -> Result<usize> {
340        if self.nonblocking() {
341            return match offset {
342                Some(offset) => self.0.read_at(buffer, offset),
343                None => self.0.read(buffer),
344            };
345        }
346        crate::operation::read(&mut self.0, buffer, offset).await
347    }
348
349    pub async fn read_until(&mut self, buffer: &mut [u8], delimiter: &[u8]) -> Result<usize> {
350        if self.nonblocking() {
351            return self.0.read_until(buffer, delimiter);
352        }
353        crate::operation::read_until(&mut self.0, buffer, delimiter).await
354    }
355
356    pub async fn read_to_end(&mut self, buffer: &mut Vec<u8>, chunk_size: usize) -> Result<usize> {
357        if chunk_size == 0 {
358            return Err(IoErrorKind::InvalidArgument);
359        }
360        let mut chunk = vec![0; chunk_size];
361        let mut total = 0;
362        loop {
363            match self.read(&mut chunk).await {
364                Ok(0) => return Ok(total),
365                Ok(count) => {
366                    buffer.extend_from_slice(&chunk[..count]);
367                    total += count;
368                }
369                Err(IoErrorKind::WouldBlock) if self.nonblocking() && total > 0 => {
370                    return Ok(total);
371                }
372                Err(error) => return Err(error),
373            }
374        }
375    }
376
377    pub async fn flush(&mut self) -> Result<()> {
378        if self.nonblocking() {
379            return self.0.flush();
380        }
381        crate::operation::flush(&mut self.0).await
382    }
383
384    pub async fn duplicate(&self) -> Result<Self> {
385        Ok(Self(poll(|| self.0.duplicate()).await?))
386    }
387
388    pub async fn get_statistics(&mut self) -> Result<Statistics> {
389        poll(|| self.0.get_statistics()).await
390    }
391
392    pub async fn set_owner(
393        &mut self,
394        user: Option<UserIdentifier>,
395        group: Option<GroupIdentifier>,
396    ) -> Result<()> {
397        poll(|| self.0.set_owner(user, group)).await
398    }
399
400    pub async fn set_permissions(&mut self, permissions: Permissions) -> Result<()> {
401        poll(|| self.0.set_permissions(permissions)).await
402    }
403
404    pub async fn control<C>(&mut self, command: C, argument: &C::Input) -> Result<C::Output>
405    where
406        C: ControlCommand,
407        C::Output: Default,
408    {
409        if self.nonblocking() {
410            return self.0.control(command, argument);
411        }
412        crate::operation::control(&mut self.0, command, argument).await
413    }
414
415    pub fn get_access(&self) -> Result<AccessFlags> {
416        Ok(self.0.flags.get_access())
417    }
418
419    pub async fn close(self, virtual_file_system: &VirtualFileSystem) -> crate::Result<()> {
420        self.0.close(virtual_file_system)
421    }
422
423    pub fn into_synchronous_file(self) -> SynchronousFile<'a> {
424        self.0
425    }
426}
427
428pub struct FileControlIterator<'a, C> {
429    file: &'a mut File<'a>,
430    get_command: C,
431    index: usize,
432    count: usize,
433}
434
435impl<'a, C> FileControlIterator<'a, C>
436where
437    C: ControlCommand<Input = usize>,
438    C::Output: Default,
439{
440    pub async fn new<Cc>(file: &'a mut File<'a>, count_command: Cc, get_command: C) -> Result<Self>
441    where
442        Cc: ControlCommand<Input = (), Output = usize>,
443    {
444        let count: usize = file.control(count_command, &()).await?;
445
446        Ok(Self {
447            file,
448            get_command,
449            index: 0,
450            count,
451        })
452    }
453
454    pub async fn next(&mut self) -> Result<Option<C::Output>> {
455        if self.index >= self.count {
456            return Ok(None);
457        }
458
459        let result = self.file.control(self.get_command, &self.index).await?;
460
461        self.index += 1;
462
463        Ok(Some(result))
464    }
465}