Skip to main content

weaveffi/rt/
iter.rs

1//! Lazily pulled iterators: the producer's [`Iter`] and the opaque handle a
2//! launcher returns for it.
3
4use std::sync::{Mutex, PoisonError};
5
6use crate::rt::error::{ErrorType, FfiError, MARSHAL_ERROR_CODE};
7use crate::rt::meta::Name;
8use crate::rt::types::FfiType;
9
10/// An owned, type-erased iterator returned by a producer function whose IDL
11/// return type is `iter<T>`.
12///
13/// Build one from any iterator with [`Iter::new`]. The `#[weaveffi::export]`
14/// expansion boxes it behind an opaque [`IterHandle`], pulls one element per
15/// `_next` call, and drops it in `_destroy`. Pulling elements lazily (rather
16/// than materializing a `Vec`) is what distinguishes an `iter<T>` return from
17/// a `[T]` (list) return.
18pub struct Iter<T> {
19    inner: Box<dyn Iterator<Item = T> + Send>,
20}
21
22impl<T> Iter<T> {
23    /// Wrap any `Send + 'static` iterator as a WeaveFFI iterator.
24    ///
25    /// Accepts anything `IntoIterator`, so `Iter::new(vec)`, `Iter::new(0..n)`,
26    /// and `Iter::new(map.into_values())` all work.
27    pub fn new<I>(iter: I) -> Self
28    where
29        I: IntoIterator<Item = T>,
30        I::IntoIter: Send + 'static,
31    {
32        Self {
33            inner: Box::new(iter.into_iter()),
34        }
35    }
36}
37
38impl<T> Iterator for Iter<T> {
39    type Item = T;
40
41    fn next(&mut self) -> Option<T> {
42        self.inner.next()
43    }
44}
45
46impl<T> std::fmt::Debug for Iter<T> {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.debug_struct("Iter").finish_non_exhaustive()
49    }
50}
51
52/// What an iterator-returning callable returns: an [`Iter`], or a `Result`
53/// of one.
54pub trait IterReturn<UT>: Sized {
55    /// The element type.
56    type Item: FfiType<UT>;
57    /// The return's IDL spelling, `iter<T>`.
58    const NAME: Name;
59    /// What the callable throws (see
60    /// [`FfiReturn::DOMAIN`](crate::rt::FfiReturn::DOMAIN)).
61    const DOMAIN: Name = Name::EMPTY;
62    /// The handle the launcher returns.
63    ///
64    /// # Errors
65    ///
66    /// Returns the callable's error.
67    fn into_handle(self) -> Result<*mut IterHandle<Self::Item>, FfiError>;
68}
69
70impl<UT, T: FfiType<UT>> IterReturn<UT> for Iter<T> {
71    type Item = T;
72    const NAME: Name = Name::iter(&T::NAME);
73    fn into_handle(self) -> Result<*mut IterHandle<T>, FfiError> {
74        Ok(iter_into_raw(self))
75    }
76}
77
78impl<UT, T: FfiType<UT>, E: ErrorType<UT>> IterReturn<UT> for Result<Iter<T>, E> {
79    type Item = T;
80    const NAME: Name = Name::iter(&T::NAME);
81    const DOMAIN: Name = E::DOMAIN;
82    fn into_handle(self) -> Result<*mut IterHandle<T>, FfiError> {
83        match self {
84            Ok(iter) => Ok(iter_into_raw(iter)),
85            Err(e) => Err(e.into_ffi()),
86        }
87    }
88}
89
90/// The opaque iterator handle a launcher returns (`{prefix}_..._Iterator*`
91/// in C).
92///
93/// The handle never holds its lock while the producer's `next` runs: `_next`
94/// takes the iterator out, advances it, and puts it back. A `_next` that
95/// arrives while another is advancing the same handle (from another thread,
96/// or re-entrantly from inside the producer's `next`) fails with
97/// [`MARSHAL_ERROR_CODE`] instead of blocking, so no misuse can deadlock.
98#[derive(Debug)]
99pub struct IterHandle<T> {
100    inner: Mutex<Option<Iter<T>>>,
101}
102
103/// Box `iter` behind a new handle for the consumer, who releases it with
104/// `_destroy` (see [`iter_destroy`]).
105#[must_use]
106pub fn iter_into_raw<T>(iter: Iter<T>) -> *mut IterHandle<T> {
107    crate::rt::leak::track(crate::rt::leak::ITERATORS, 1);
108    Box::into_raw(Box::new(IterHandle {
109        inner: Mutex::new(Some(iter)),
110    }))
111}
112
113/// Puts the iterator back into its handle when dropped, including when the
114/// producer's `next` unwinds, so a panic doesn't leave the handle busy.
115struct Advancing<'a, T> {
116    handle: &'a IterHandle<T>,
117    iter: Option<Iter<T>>,
118}
119
120impl<T> Drop for Advancing<'_, T> {
121    fn drop(&mut self) {
122        let mut slot = self
123            .handle
124            .inner
125            .lock()
126            .unwrap_or_else(PoisonError::into_inner);
127        *slot = self.iter.take();
128    }
129}
130
131/// Pull the next element from a handle: `Ok(None)` when the iterator is
132/// exhausted.
133///
134/// A producer panic from an earlier `next` doesn't wedge the handle: the
135/// iterator is put back in whatever state the panic left it.
136///
137/// # Errors
138///
139/// Returns a [`MARSHAL_ERROR_CODE`] error when `handle` is null or another
140/// `_next` is advancing it right now.
141///
142/// # Safety
143///
144/// `handle` must be null or a live pointer from [`iter_into_raw`] that isn't
145/// destroyed during the call.
146pub unsafe fn iter_next<T>(handle: *const IterHandle<T>) -> Result<Option<T>, FfiError> {
147    // SAFETY: the caller guarantees a live handle or null.
148    let Some(handle) = (unsafe { handle.as_ref() }) else {
149        return Err(FfiError::new(MARSHAL_ERROR_CODE, "iterator is null"));
150    };
151    let taken = handle
152        .inner
153        .lock()
154        .unwrap_or_else(PoisonError::into_inner)
155        .take();
156    let Some(iter) = taken else {
157        return Err(FfiError::new(
158            MARSHAL_ERROR_CODE,
159            "iterator is already being advanced (a concurrent or re-entrant _next)",
160        ));
161    };
162    let mut advancing = Advancing {
163        handle,
164        iter: Some(iter),
165    };
166    let item = advancing.iter.as_mut().and_then(Iterator::next);
167    drop(advancing);
168    Ok(item)
169}
170
171/// The body of every iterator's `_destroy` symbol: drop the iterator and its
172/// handle. A null handle is a no-op, and a panicking `Drop` is swallowed
173/// because a destructor has no `out_err` slot and must never unwind into C.
174///
175/// # Safety
176///
177/// `handle` must be null or a live pointer from [`iter_into_raw`], released
178/// exactly once.
179pub unsafe fn iter_destroy<T>(handle: *mut IterHandle<T>) {
180    if handle.is_null() {
181        return;
182    }
183    crate::rt::leak::track(crate::rt::leak::ITERATORS, -1);
184    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
185        // SAFETY: the caller hands back a pointer from `Box::into_raw`
186        // exactly once.
187        drop(unsafe { Box::from_raw(handle) });
188    }));
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    fn next<T>(h: *const IterHandle<T>) -> Option<T> {
196        unsafe { iter_next(h) }.unwrap()
197    }
198
199    #[test]
200    fn pulls_until_exhausted() {
201        let h = iter_into_raw(Iter::new(vec![1, 2]));
202        assert_eq!(next(h), Some(1));
203        assert_eq!(next(h), Some(2));
204        assert_eq!(next(h), None);
205        unsafe {
206            assert!(iter_next::<i32>(std::ptr::null()).is_err());
207            iter_destroy(h);
208            iter_destroy::<i32>(std::ptr::null_mut());
209        }
210    }
211
212    #[test]
213    fn concurrent_next_yields_each_element_once_or_reports_busy() {
214        let h = iter_into_raw(Iter::new(0..10_000u32));
215        let threads: Vec<_> = (0..8)
216            .map(|_| {
217                let shared = crate::rt::ThreadPtr(h);
218                std::thread::spawn(move || {
219                    let h = shared.get();
220                    let mut got = Vec::new();
221                    loop {
222                        match unsafe { iter_next(h) } {
223                            Ok(Some(x)) => got.push(x),
224                            Ok(None) => break,
225                            Err(e) => {
226                                assert_eq!(e.code, MARSHAL_ERROR_CODE);
227                                std::thread::yield_now();
228                            }
229                        }
230                    }
231                    got
232                })
233            })
234            .collect();
235        let mut all: Vec<u32> = threads
236            .into_iter()
237            .flat_map(|t| t.join().unwrap())
238            .collect();
239        all.sort_unstable();
240        assert_eq!(all, (0..10_000).collect::<Vec<_>>());
241        unsafe { iter_destroy(h) };
242    }
243
244    #[test]
245    fn a_panicking_next_puts_the_iterator_back() {
246        let mut n = 0;
247        let h = iter_into_raw(Iter::new(std::iter::from_fn(move || {
248            n += 1;
249            assert!(n != 2, "second element");
250            Some(n)
251        })));
252        assert_eq!(next(h), Some(1));
253        assert!(std::panic::catch_unwind(move || {
254            let _ = unsafe { iter_next(h) };
255        })
256        .is_err());
257        assert_eq!(next(h), Some(3));
258        unsafe { iter_destroy(h) };
259    }
260}