devela 0.27.0

A development layer of coherence.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// devela::data::access::iter::lending::definitions
//
//! Defines [`IteratorLending`],
//! [`IteratorLendingDoubleEnded`],
//! [`IteratorLendingExactSize`],
//! [`IteratorLendingPeek`],
//! [`IteratorLendingPeekDoubleEnded`].
//

use crate::is;

#[doc = crate::_tags!(iterator lifetime)]
/// A lending iterator using a generic associated lifetime.
#[doc = crate::_doc_location!("data/access/iter")]
///
/// A lending iterator yields items borrowed from its own internal state.
/// Each call to [`next`][Self::next] creates a temporary borrow of `self`
/// and returns an item tied to that borrow. This enables iteration over
/// memory-backed structures without copying or owning the underlying data.
///
/// This is the borrowing analogue of [`Iterator`][crate::Iterator].
///
/// See also:
/// - [`IteratorLendingDoubleEnded`]
/// - [`IteratorLendingExactSize`]
/// - [`IteratorLendingPeek`]
/// - [`IteratorLendingPeekDoubleEnded`]
#[rustfmt::skip]
pub trait IteratorLending {
    /// The item yielded by this iterator.
    ///
    /// The lifetime `'a` corresponds to the borrow of `self` required to produce the item.
    type Item<'a> where Self: 'a;

    /// Advances the iterator and returns the next item.
    ///
    /// The lifetime of the returned reference is scoped to the borrow
    /// of `self` established during this call.
    fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;

    /* non-required methods */

    /// Returns a size hint for the remaining items.
    ///
    /// The default implementation returns `(0, None)`, which is correct but
    /// conservative. Implementors may override this for improved accuracy.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }

    /// Consumes the iterator, returning the number of remaining items.
    fn count(&mut self) -> usize {
        let mut n = 0;
        while self.next().is_some() { n += 1; }
        n
    }

    // ✗ last

    /// Advances the iterator by `n` steps.
    ///
    /// Returns `Ok(())` if `n` items were successfully skipped.
    /// Returns `Err(remaining)` if the iterator ended early, where
    /// `remaining` is the number of items that were *not* skipped.
    fn advance_by(&mut self, mut n: usize) -> Result<(), usize> {
        while n > 0 {
            match self.next() {
                Some(_) => n -= 1,
                None => return Err(n),
            }
        }
        Ok(())
    }

    /// Advances the iterator by `n` items and returns the next one.
    fn nth<'a>(&'a mut self, mut n: usize) -> Option<Self::Item<'a>> {
        while n > 0 {
            is![self.next().is_none(), return None];
            n -= 1;
        }
        self.next()
    }

    // ✗ step_by
    // ✗ chain
    // ✗ zip
    // ✗ intersperse
    // ✗ intersperse_with
    // ✗ map

    /// Applies `f` to each remaining item.
    fn for_each<F>(&mut self, mut f: F)
    where F: FnMut(Self::Item<'_>) {
        while let Some(item) = self.next() { f(item); }
    }

    // ✗ filter
    // ✗ filter_map
    // ✗ enumerate
    // ✗ peekable
    // ✗ skip_while
    // ✗ take_while
    // ✗ map_while
    // ✓ skip
    // ✓ take
    // ✗ scan
    // ✗ flatmap
    // ✗ flatten
    // ✗ map_windows
    // ✗ fuse

    /// Calls `f` for each item before yielding it.
    ///
    /// This is useful for debugging or side effects. The iterator
    /// behavior is otherwise unchanged.
    fn inspect<F>(&mut self, mut f: F)
    where
        F: FnMut(&Self::Item<'_>),
    {
        while let Some(item) = self.next() {
            f(&item);
        }
    }

    // ✓ by_ref
    // ✗ collect
    // ✗ try_collect
    // ✗ collect_into
    // ✗ partition
    // ✗ partition_in_place

    /// Returns `true` if the iterator is partitioned according to `pred`.
    ///
    /// All items for which `pred` returns `true` must come before all
    /// items for which it returns `false`. Once the predicate becomes
    /// `false`, it must remain `false` for all subsequent items.
    fn is_partitioned<P>(&mut self, mut pred: P) -> bool
    where
        P: FnMut(&Self::Item<'_>) -> bool,
    {
        let mut seen_false = false;
        while let Some(item) = self.next() {
            if pred(&item) {
                if seen_false { return false; }
            } else {
                seen_false = true;
            }
        }
        true
    }

    /// Applies `f` to each item, accumulating results in `acc`.
    ///
    /// Iteration stops on the first `Err`. Returns `Ok(acc)` when all
    /// applications succeed.
    ///
    /// This mirrors `Iterator::try_fold` but works with borrowed items.
    fn try_fold<B, E, F>(&mut self, mut acc: B, mut f: F) -> Result<B, E>
    where
        F: FnMut(B, Self::Item<'_>) -> Result<B, E>,
    {
        while let Some(item) = self.next() {
            acc = f(acc, item)?;
        }
        Ok(acc)
    }

    /// Applies `f` to each remaining item until an error occurs.
    fn try_for_each<F, E>(&mut self, mut f: F) -> Result<(), E>
    where F: FnMut(Self::Item<'_>) -> Result<(), E> {
        while let Some(item) = self.next() { f(item)?; }
        Ok(())
    }

    // ✗ fold
    // ✓ reduce
    // ✓ try_reduce

    /// Returns `true` if all items satisfy the predicate.
    fn all<P>(&mut self, mut pred: P) -> bool
    where
        P: FnMut(&Self::Item<'_>) -> bool,
    {
        while let Some(item) = self.next() { is![!pred(&item), return false]; }
        true
    }
    /// Returns `true` if any item satisfies the predicate.
    fn any<P>(&mut self, mut pred: P) -> bool
    where
        P: FnMut(&Self::Item<'_>) -> bool,
    {
        while let Some(item) = self.next() { is![pred(&item), return true]; }
        false
    }

    // ✓ find
    // ✓ find_map
    // ✓ try_find

    /// Returns the index of the first item for which `pred` returns `true`,
    /// or `None` if no matching item is found.
    fn position<P>(&mut self, mut pred: P) -> Option<usize>
    where
        P: FnMut(&Self::Item<'_>) -> bool,
    {
        let mut index = 0;
        while let Some(item) = self.next() {
            is![pred(&item), return Some(index)];
            index += 1;
        }
        None
    }

    // ✓ rposition
    // ✓ max
    // ✓ min
    // ✓ max_by_key
    // ✓ max_by
    // ✓ min_by_key
    // ✓ min_by
    // ✓ rev (in double-ended)
    // ✗ unzip
    // ✗ copied
    // ✗ cloned
    // ✗ cycle
    // ✗ array_chunks

    // ~ sum
    // ~ product
    // ✓ cmp
    // ✓ cmp_by
    // ✓ partial_cmp
    // ✓ partial_cmp_by
    // ✓ eq
    // ✓ eq_by
    // ✓ ne
    // ✓ lt
    // ✓ le
    // ✓ gt
    // ✓ ge
    // ✓ is_sorted
    // ✓ is_sorted_by
    // ✓ is_sorted_by_key
}

#[doc = crate::_tags!(iterator lifetime)]
/// A lending iterator that can yield items from the back.
#[doc = crate::_doc_location!("data/access/iter")]
///
/// This is the borrowing analogue of : [`IteratorDoubleEnded`][crate::IteratorDoubleEnded].
pub trait IteratorLendingDoubleEnded: IteratorLending {
    /// Returns the next item from the back of the iterator.
    fn next_back<'a>(&'a mut self) -> Option<Self::Item<'a>>;

    /* non-required methods*/

    /// Skips `n` items from the back and returns the next one.
    ///
    /// Repeatedly calls [`next_back`][Self::next_back] `n + 1` times.
    /// Returns the final yielded item, or `None` if the iterator ends before advancing `n` steps.
    ///
    /// This is the reverse analogue of [`IteratorLending::nth`].
    fn nth_back<'a>(&'a mut self, mut n: usize) -> Option<Self::Item<'a>> {
        while n > 0 {
            is![self.next_back().is_none(), return None];
            n -= 1;
        }
        self.next_back()
    }

    // ✓ rposition

    /// Reverse-direction equivalent of [`IteratorLending::try_fold`].
    ///
    /// Applies `f` starting from the back of the iterator, folding
    /// items in reverse order. Stops on first `Err`.
    fn try_rfold<B, E, F>(&mut self, mut acc: B, mut f: F) -> Result<B, E>
    where
        F: FnMut(B, Self::Item<'_>) -> Result<B, E>,
    {
        while let Some(item) = self.next_back() {
            acc = f(acc, item)?;
        }
        Ok(acc)
    }
}

#[doc = crate::_tags!(iterator lifetime)]
/// A lending iterator with a known remaining length.
#[doc = crate::_doc_location!("data/access/iter")]
///
/// This is the borrowing analogue of [`IteratorExactSize`][crate::IteratorExactSize].
///
/// # Contract
/// Implementors must return a [`size_hint`][IteratorLending::size_hint] where:
/// - the lower bound equals the upper bound, and
/// - both equal the exact number of items remaining.
///
/// In other words, `size_hint()` must return `(len, Some(len))` at all times.
pub trait IteratorLendingExactSize: IteratorLending {
    /* non-required methods */

    /// Returns the exact number of items remaining.
    ///
    /// The default implementation derives this from
    /// [`size_hint`][IteratorLending::size_hint], matching the standard library.
    ///
    /// # Panics
    /// In debug builds, panics if the upper bound returned by `size_hint` is not `Some(lower)`.
    fn len(&self) -> usize {
        let (lower, upper) = self.size_hint();
        debug_assert!(upper == Some(lower));
        lower
    }

    /// Returns `true` when no more items can be produced.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[doc = crate::_tags!(iterator lifetime)]
/// A lending iterator that can inspect the next item without advancing.
#[doc = crate::_doc_location!("data/access/iter")]
///
/// The returned reference is tied to the temporary mutable borrow of `self`
/// created by this call. Implementations must not advance the iteration state
/// (i.e., the next call to [`IteratorLending::next`] yields the same item, if any).
///
/// Implementations may internally buffer the next item to support peeking,
/// but the externally observable iteration order must be unchanged.
pub trait IteratorLendingPeek: IteratorLending {
    /// Returns the next item without advancing the iterator.
    ///
    /// Borrows `self` mutably so that both shared and exclusive lending
    /// iterators can expose a peek. The reference remains valid until
    /// `self` is borrowed again.
    fn peek<'a>(&'a mut self) -> Option<Self::Item<'a>>;

    /* non-required */

    /// Returns the next item if it matches the predicate.
    ///
    /// The iterator is advanced only when `pred` returns `true` for the
    /// next item. Otherwise, the iterator remains unchanged.
    fn next_if<F>(&mut self, pred: F) -> Option<Self::Item<'_>>
    where
        for<'a> F: FnOnce(&Self::Item<'a>) -> bool,
    {
        is![self.peek().is_some_and(|i| pred(&i)), self.next(), None]
    }

    /// Returns the next item if it is equal to `expected`.
    ///
    /// This is a convenience wrapper around [`next_if`][Self::next_if] using `PartialEq`.
    fn next_if_eq<Q>(&mut self, expected: &Q) -> Option<Self::Item<'_>>
    where
        for<'a> Self::Item<'a>: PartialEq<Q>,
        Q: ?Sized,
    {
        self.next_if(|item| item == expected)
    }

    /// Applies `f` to the next item without advancing the iterator unless `f` returns `Ok`.
    ///
    /// If `f` returns:
    /// - `Ok(r)` — the iterator is advanced and `Ok(Some(r))` is returned.
    /// - `Err(e)` — the iterator is left unchanged and `Err(e)` is returned.
    /// If the iterator is exhausted, `Ok(None)` is returned.
    ///
    /// `f` receives a temporary borrow of the next item.
    /// The borrow ends before this method calls [`IteratorLending::next`],
    /// so advancing the iterator is always sound.
    fn next_if_map<R, E, F>(&mut self, f: F) -> Result<Option<R>, E>
    where
        F: FnOnce(&Self::Item<'_>) -> Result<R, E>,
    {
        match self.peek().map(|item| f(&item)) {
            None => Ok(None),
            Some(Ok(r)) => {
                self.next();
                Ok(Some(r))
            }
            Some(Err(e)) => Err(e),
        }
    }
}

#[doc = crate::_tags!(iterator lifetime)]
/// A lending iterator that can inspect the next item from the back, without advancing.
#[doc = crate::_doc_location!("data/access/iter")]
///
/// The returned reference is tied to the temporary mutable borrow of `self`
/// created by this call. Implementations must not modify the iteration state
/// (i.e., the next call to [`IteratorLendingDoubleEnded::next_back`]
/// will yield the same item as it would have without peeking).
///
/// Implementations may internally buffer the back item to support peeking,
/// but the externally observable iteration order must be unchanged.
pub trait IteratorLendingPeekDoubleEnded: IteratorLendingPeek + IteratorLendingDoubleEnded {
    /// Returns the next item from the back, without advancing the iterator.
    ///
    /// Borrows `self` mutably so that both shared and exclusive lending
    /// iterators can expose a peek. The reference remains valid until
    /// `self` is borrowed again.
    fn peek_back<'a>(&'a mut self) -> Option<Self::Item<'a>>;

    /* non-required */

    /// Returns the next item from the back if it matches the predicate.
    ///
    /// The iterator is advanced only when `pred` returns `true` for the
    /// next item. Otherwise, the iterator remains unchanged.
    fn next_back_if<F>(&mut self, pred: F) -> Option<Self::Item<'_>>
    where
        for<'a> F: FnOnce(&Self::Item<'a>) -> bool,
    {
        is![self.peek_back().is_some_and(|i| pred(&i)), self.next_back(), None]
    }

    /// Returns the next item from the back if it is equal to `expected`.
    ///
    /// This is a convenience wrapper around [`next_back_if`][Self::next_back_if] using `PartialEq`.
    fn next_back_if_eq<Q>(&mut self, expected: &Q) -> Option<Self::Item<'_>>
    where
        for<'a> Self::Item<'a>: PartialEq<Q>,
        Q: ?Sized,
    {
        self.next_back_if(|item| item == expected)
    }

    /// Applies `f` to the next item from the back
    /// without advancing the iterator unless `f` returns `Ok`.
    ///
    /// If `f` returns:
    /// - `Ok(r)` — the iterator is advanced and `Ok(Some(r))` is returned.
    /// - `Err(e)` — the iterator is left unchanged and `Err(e)` is returned.
    /// If the iterator is exhausted, `Ok(None)` is returned.
    ///
    /// `f` receives a temporary borrow of the next item from the back.
    /// The borrow ends before this method calls [`IteratorLendingDoubleEnded::next_back`],
    /// so advancing the iterator is always sound.
    fn next_back_if_map<R, E, F>(&mut self, f: F) -> Result<Option<R>, E>
    where
        F: FnOnce(&Self::Item<'_>) -> Result<R, E>,
    {
        match self.peek_back().map(|item| f(&item)) {
            None => Ok(None),
            Some(Ok(r)) => {
                self.next_back();
                Ok(Some(r))
            }
            Some(Err(e)) => Err(e),
        }
    }
}