Skip to main content

virtual_file_system/
synchronous_directory.rs

1use core::mem::forget;
2use exported_file_system::{
3    AccessFlags, AttributeFlags, AttributeOperations, Attributes, StateFlags, Statistics,
4};
5use file_system::{Context, DirectoryOperations, Entry, Flags, Path, Size};
6use task::TaskIdentifier;
7
8use crate::{
9    IoErrorKind, ItemStatic, Result, VirtualFileSystem, blocking_operation, suspend_on,
10    suspend_on_cancellable,
11};
12
13pub struct SynchronousDirectory<'a> {
14    closed: bool,
15    virtual_file_system: &'a VirtualFileSystem,
16    pub(crate) directory: &'static dyn file_system::FileSystemOperations,
17    pub(crate) flags: Flags,
18    pub(crate) context: Context,
19}
20
21impl<'a> SynchronousDirectory<'a> {
22    pub fn new(
23        virtual_file_system: &'a VirtualFileSystem,
24        directory: &'static dyn file_system::FileSystemOperations,
25        flags: Flags,
26        context: Context,
27    ) -> Self {
28        Self {
29            closed: false,
30            virtual_file_system,
31            directory,
32            flags,
33            context,
34        }
35    }
36
37    fn blocking_operation<O>(
38        &mut self,
39        mut operation: impl FnMut(&mut Self) -> Result<O>,
40    ) -> Result<O> {
41        blocking_operation(self.flags, || operation(self))
42    }
43
44    pub fn create(
45        virtual_file_system: &'a VirtualFileSystem,
46        task: TaskIdentifier,
47        path: impl AsRef<Path>,
48    ) -> Result<()> {
49        suspend_on_cancellable(async move {
50            virtual_file_system
51                .create_directory(task, &path.as_ref())
52                .await
53        })
54    }
55
56    /// Open a directory. As for [`crate::SynchronousFile::open`], a cancellation in a
57    /// stackful coroutine drops the wait, the path it owns and the lock it may hold.
58    pub fn open(
59        virtual_file_system: &'a VirtualFileSystem,
60        task: TaskIdentifier,
61        path: impl AsRef<Path>,
62    ) -> Result<Self> {
63        let mut directory = suspend_on_cancellable(async move {
64            virtual_file_system
65                .open_directory(task, &path.as_ref())
66                .await
67        })?
68        .into_synchronous_directory();
69
70        directory.flags = directory.flags.set_status(StateFlags::empty());
71
72        Ok(directory)
73    }
74
75    pub fn read(&mut self) -> Result<Option<Entry>> {
76        let entry = self.blocking_operation(|directory| {
77            DirectoryOperations::read(directory.directory, &mut directory.context)
78        })?;
79
80        Ok(entry)
81    }
82
83    pub fn get_statistics(&mut self) -> Result<Statistics> {
84        self.blocking_operation(|directory| {
85            let mut attributes = Attributes::new().set_mask(AttributeFlags::all());
86
87            AttributeOperations::get_attributes(
88                directory.directory,
89                &mut directory.context,
90                &mut attributes,
91            )?;
92
93            Statistics::from_attributes(&attributes).ok_or(IoErrorKind::InputOutput)
94        })
95    }
96
97    pub fn get_position(&mut self) -> Result<Size> {
98        self.blocking_operation(|directory| {
99            DirectoryOperations::get_position(directory.directory, &mut directory.context)
100        })
101    }
102
103    pub fn set_position(&mut self, position: Size) -> Result<()> {
104        self.blocking_operation(|directory| {
105            DirectoryOperations::set_position(directory.directory, &mut directory.context, position)
106        })?;
107
108        Ok(())
109    }
110
111    pub fn rewind(&mut self) -> Result<()> {
112        self.blocking_operation(|directory| {
113            DirectoryOperations::rewind(directory.directory, &mut directory.context)
114        })
115    }
116
117    pub fn get_access(&self) -> Result<AccessFlags> {
118        Ok(self.flags.get_access())
119    }
120
121    pub fn get_state(&self) -> Result<StateFlags> {
122        Ok(self.flags.get_state())
123    }
124
125    pub fn close_internal(&mut self, virtual_file_system: &VirtualFileSystem) -> Result<()> {
126        if self.closed {
127            return Ok(());
128        }
129        let result = suspend_on(virtual_file_system.close(
130            &ItemStatic::Directory(self.directory),
131            None,
132            &mut self.context,
133        ));
134        // Marked only once the close has run, as for a file: a close that is cancelled
135        // while it waits is closed again by the next owner, not skipped.
136        self.closed = true;
137        result
138    }
139
140    /// Close using the retained VFS without consuming the listing, so that its owner can
141    /// keep it where a cancellation can still reach it until the close is done. Closing
142    /// again, or dropping, does nothing more once this has returned.
143    pub fn close_in_place(&mut self) -> Result<()> {
144        self.close_internal(self.virtual_file_system)
145    }
146
147    /// Close using the retained VFS, reporting any close error.
148    pub fn close_owned(self) -> Result<()> {
149        let virtual_file_system = self.virtual_file_system;
150        self.close(virtual_file_system)
151    }
152
153    pub fn close(mut self, virtual_file_system: &VirtualFileSystem) -> Result<()> {
154        let result = self.close_internal(virtual_file_system);
155        forget(self);
156
157        result
158    }
159}
160
161impl Drop for SynchronousDirectory<'_> {
162    /// Closes a listing that was not closed, without waiting, as a file's drop does.
163    fn drop(&mut self) {
164        if self.closed {
165            return;
166        }
167        self.closed = true;
168        let _ = self
169            .virtual_file_system
170            .close_without_waiting(
171                &ItemStatic::Directory(self.directory),
172                None,
173                &mut self.context,
174            )
175            .map_err(|e| {
176                log::error!("Error closing directory: {}", e);
177            });
178    }
179}
180
181impl Iterator for SynchronousDirectory<'_> {
182    type Item = Entry;
183
184    fn next(&mut self) -> Option<Self::Item> {
185        self.read().unwrap()
186    }
187}