Skip to main content

abi_application/
iterator.rs

1use crate::{
2    Directory, Status, XILA_RIGHT_READ,
3    registry::{self, Handle},
4};
5use core::ffi::c_char;
6use file_system::Entry;
7use virtual_file_system::SynchronousDirectory;
8
9/// Opaque owned listing with at most one pending VFS entry for buffer retries.
10pub struct DirectoryIterator {
11    inner: SynchronousDirectory<'static>,
12    pending: Option<Entry>,
13}
14
15impl Handle for DirectoryIterator {
16    unsafe fn close(raw: *mut Self) {
17        // SAFETY: the registry holds only live listings that `xila_directory_iterator_open` made.
18        let _ = unsafe { xila_directory_iterator_close(raw) };
19    }
20}
21
22/// Open a relative directory for listing with READ authority; empty means itself.
23/// # Safety
24/// Directory must be live; path readable for length. Output must be aligned,
25/// writable and disjoint from inputs. Calls must be serialized.
26pub unsafe extern "C" fn xila_directory_iterator_open(
27    directory: *const Directory,
28    path: *const c_char,
29    length: usize,
30    output: *mut *mut DirectoryIterator,
31) -> Status {
32    if directory.is_null() || output.is_null() {
33        return Status::InvalidArgument;
34    }
35    // SAFETY: checked non-null above; the caller guarantees the object is live.
36    let directory = unsafe { &*directory };
37    let result = (|| {
38        let path = unsafe { directory.resolve(path, length, XILA_RIGHT_READ, false)? };
39        // Passed by value: the open owns the path, so a cancellation drops it.
40        let inner = SynchronousDirectory::open(directory.vfs, directory.task, path)?;
41        Ok::<_, Status>(DirectoryIterator {
42            inner,
43            pending: None,
44        })
45    })();
46    match result {
47        Ok(value) => {
48            unsafe {
49                output.write(registry::register(value));
50            }
51            Status::Ok
52        }
53        Err(error) => error,
54    }
55}
56
57/// Copy a name without a trailing NUL, skipping dot entries. End leaves outputs
58/// unchanged. BufferTooSmall writes only required name_length and retains the entry.
59/// # Safety
60/// Iterator must be live and exclusively accessed. Buffer must be writable for
61/// capacity bytes (null allowed only at zero capacity). Outputs must be aligned,
62/// writable and disjoint from each other, the buffer and iterator.
63pub unsafe extern "C" fn xila_directory_iterator_next(
64    iterator: *mut DirectoryIterator,
65    name_buffer: *mut c_char,
66    capacity: usize,
67    name_length: *mut usize,
68    kind: *mut u32,
69) -> Status {
70    if iterator.is_null()
71        || name_length.is_null()
72        || kind.is_null()
73        || (capacity != 0 && name_buffer.is_null())
74        || capacity > isize::MAX as usize
75    {
76        return Status::InvalidArgument;
77    }
78    let iterator = unsafe { &mut *iterator };
79    while iterator.pending.is_none() {
80        match iterator.inner.read() {
81            Ok(Some(entry)) if entry.name == "." || entry.name == ".." => continue,
82            Ok(Some(entry)) => iterator.pending = Some(entry),
83            Ok(None) => return Status::End,
84            Err(error) => return error.into(),
85        }
86    }
87    let Some(entry) = &iterator.pending else {
88        unreachable!();
89    };
90    if entry.name.len() > capacity {
91        unsafe {
92            name_length.write(entry.name.len());
93        }
94        return Status::BufferTooSmall;
95    }
96    if !entry.name.is_empty() {
97        unsafe {
98            core::ptr::copy_nonoverlapping(
99                entry.name.as_ptr(),
100                name_buffer.cast(),
101                entry.name.len(),
102            );
103        }
104    }
105    unsafe {
106        name_length.write(entry.name.len());
107        kind.write(crate::kind_value(entry.kind));
108    }
109    iterator.pending = None;
110    Status::Ok
111}
112
113/// Rewind, discarding a pending entry only on success.
114/// # Safety
115/// Iterator must be live and exclusively accessed.
116pub unsafe extern "C" fn xila_directory_iterator_rewind(
117    iterator: *mut DirectoryIterator,
118) -> Status {
119    if iterator.is_null() {
120        return Status::InvalidArgument;
121    }
122    let iterator = unsafe { &mut *iterator };
123    match iterator.inner.rewind() {
124        Ok(()) => {
125            iterator.pending = None;
126            Status::Ok
127        }
128        Err(error) => error.into(),
129    }
130}
131
132/// Close and free the iterator even on close error; null succeeds.
133/// # Safety
134/// Non-null iterator must be owned, live and released once; no concurrent calls.
135pub unsafe extern "C" fn xila_directory_iterator_close(iterator: *mut DirectoryIterator) -> Status {
136    if iterator.is_null() {
137        return Status::Ok;
138    }
139    // Closed in place, as a file is: see `xila_file_close`.
140    let result = unsafe { &mut (*iterator).inner }.close_in_place();
141    drop(unsafe { registry::reclaim(iterator) });
142    result.map_or_else(Status::from, |()| Status::Ok)
143}