Skip to main content

larust_support/
loop_iter.rs

1//! Laravel Blade's automatic `$loop` variable (`$loop->first`, `->last`,
2//! `->index`, `->iteration`, `->count`) - as an explicit iterator adapter
3//! a template opts into, not implicit per-`@foreach` magic. Laravel
4//! injects `$loop` into *every* `@foreach` body automatically; Larust's
5//! own `@foreach` (`larust-view`/`larust-macros`) doesn't special-case
6//! anything at all for this - `@foreach((item, loop_) in
7//! items.iter().with_loop())` is ordinary tuple-binding codegen (already
8//! built for keyed iteration, see `larust_view::ast::Node::Foreach`'s doc
9//! comment) paired with an ordinary iterator combinator, so no framework
10//! change was needed to add this at all, only this module plus
11//! `larust-convert`'s own wiring (`blade::scan::body_references_loop_variable`).
12//!
13//! Named `loop_`, not `loop` - `loop` is a reserved Rust keyword, so no
14//! template can bind a variable literally called `loop`.
15//!
16//! Deliberately a narrower field set than Laravel's real `$loop`:
17//! `remaining`, `even`/`odd`, `depth`, and `parent` (nested-loop access)
18//! aren't included - add them if a real conversion ever needs them,
19//! rather than guessing at a full port nobody's asked for yet.
20
21/// One iteration's position, alongside the item itself - see [`WithLoop`].
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Loop {
24    /// 0-based position - Rust's own `Iterator::enumerate()` convention.
25    pub index: usize,
26    /// 1-based position - Laravel's own `$loop->iteration`.
27    pub iteration: usize,
28    /// Total number of items this loop will produce.
29    pub count: usize,
30    pub first: bool,
31    pub last: bool,
32}
33
34/// `.with_loop()` - wraps any iterator whose length is known up front
35/// (`ExactSizeIterator`, satisfied by `.iter()` on a `Vec`/slice/
36/// `HashMap`, `.iter().enumerate()` over one of those, and more) into one
37/// yielding `(item, Loop)` pairs.
38pub trait WithLoop: ExactSizeIterator + Sized {
39    fn with_loop(self) -> LoopIter<Self> {
40        LoopIter {
41            count: self.len(),
42            index: 0,
43            inner: self,
44        }
45    }
46}
47
48impl<I: ExactSizeIterator> WithLoop for I {}
49
50pub struct LoopIter<I> {
51    inner: I,
52    index: usize,
53    count: usize,
54}
55
56impl<I: ExactSizeIterator> Iterator for LoopIter<I> {
57    type Item = (I::Item, Loop);
58
59    fn next(&mut self) -> Option<Self::Item> {
60        let item = self.inner.next()?;
61        let index = self.index;
62        self.index += 1;
63        Some((
64            item,
65            Loop {
66                index,
67                iteration: index + 1,
68                count: self.count,
69                first: index == 0,
70                last: index + 1 == self.count,
71            },
72        ))
73    }
74
75    fn size_hint(&self) -> (usize, Option<usize>) {
76        self.inner.size_hint()
77    }
78}
79
80impl<I: ExactSizeIterator> ExactSizeIterator for LoopIter<I> {}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn marks_the_first_and_last_item_and_counts_correctly() {
88        let items = ["a", "b", "c"];
89        let collected: Vec<_> = items.iter().with_loop().collect();
90        assert_eq!(collected.len(), 3);
91
92        let (_, first_loop) = collected[0];
93        assert_eq!(first_loop.index, 0);
94        assert_eq!(first_loop.iteration, 1);
95        assert_eq!(first_loop.count, 3);
96        assert!(first_loop.first);
97        assert!(!first_loop.last);
98
99        let (_, last_loop) = collected[2];
100        assert_eq!(last_loop.index, 2);
101        assert_eq!(last_loop.iteration, 3);
102        assert!(!last_loop.first);
103        assert!(last_loop.last);
104    }
105
106    #[test]
107    fn a_single_item_is_both_first_and_last() {
108        let items = ["only"];
109        let collected: Vec<_> = items.iter().with_loop().collect();
110        assert_eq!(collected.len(), 1);
111        let (_, meta) = collected[0];
112        assert!(meta.first);
113        assert!(meta.last);
114    }
115
116    #[test]
117    fn composes_with_an_already_enumerated_iterator() {
118        // The exact real shape a keyed `@foreach` translates to:
119        // `.iter().enumerate().with_loop()`.
120        let items = ["a", "b"];
121        let collected: Vec<_> = items.iter().enumerate().with_loop().collect();
122        assert_eq!(collected.len(), 2);
123        let ((index, _value), meta) = collected[1];
124        assert_eq!(index, 1);
125        assert!(meta.last);
126    }
127}