Skip to main content

rune/modules/
iter.rs

1//! Iterators.
2
3use crate as rune;
4use crate::alloc;
5use crate::alloc::prelude::*;
6use crate::modules::collections::{HashMap, HashSet, VecDeque};
7use crate::runtime::budget;
8use crate::runtime::hint_capacity;
9use crate::runtime::range::RangeIter;
10use crate::runtime::{
11    Address, Dismantle, FromValue, Function, Handover, Inline, Object, Output, OwnedTuple,
12    Protocol, Repr, TypeHash, Value, Vec, VmError, VmErrorKind,
13};
14use crate::shared::Caller;
15use crate::{docstring, Any, ContextError, Module, Params};
16
17/// Rune support for iterators.
18///
19/// This module contains types and methods for working with iterators in Rune.
20#[rune::module(::std::iter)]
21pub fn module() -> Result<Module, ContextError> {
22    let mut m = Module::from_meta(self::module__meta)?;
23
24    m.ty::<Rev>()?;
25    m.function_meta(Rev::next__meta)?;
26    m.function_meta(Rev::next_back__meta)?;
27    m.function_meta(Rev::size_hint__meta)?;
28    m.function_meta(Rev::len__meta)?;
29    m.implement_trait::<Rev>(rune::item!(::std::iter::Iterator))?;
30    m.implement_trait::<Rev>(rune::item!(::std::iter::DoubleEndedIterator))?;
31    m.implement_trait::<Rev>(rune::item!(::std::iter::ExactSizeIterator))?;
32
33    m.ty::<Chain>()?;
34    m.function_meta(Chain::next__meta)?;
35    m.function_meta(Chain::next_back__meta)?;
36    m.function_meta(Chain::size_hint__meta)?;
37    m.function_meta(Chain::len__meta)?;
38    m.implement_trait::<Chain>(rune::item!(::std::iter::Iterator))?;
39    m.implement_trait::<Chain>(rune::item!(::std::iter::DoubleEndedIterator))?;
40    m.implement_trait::<Chain>(rune::item!(::std::iter::ExactSizeIterator))?;
41
42    m.ty::<Enumerate>()?;
43    m.function_meta(Enumerate::next__meta)?;
44    m.function_meta(Enumerate::next_back__meta)?;
45    m.function_meta(Enumerate::size_hint__meta)?;
46    m.function_meta(Enumerate::len__meta)?;
47    m.implement_trait::<Enumerate>(rune::item!(::std::iter::Iterator))?;
48    m.implement_trait::<Enumerate>(rune::item!(::std::iter::DoubleEndedIterator))?;
49    m.implement_trait::<Enumerate>(rune::item!(::std::iter::ExactSizeIterator))?;
50
51    m.ty::<Filter>()?;
52    m.function_meta(Filter::next__meta)?;
53    m.function_meta(Filter::next_back__meta)?;
54    m.function_meta(Filter::size_hint__meta)?;
55    m.implement_trait::<Filter>(rune::item!(::std::iter::Iterator))?;
56    m.implement_trait::<Filter>(rune::item!(::std::iter::DoubleEndedIterator))?;
57
58    m.ty::<Map>()?;
59    m.function_meta(Map::next__meta)?;
60    m.function_meta(Map::next_back__meta)?;
61    m.function_meta(Map::size_hint__meta)?;
62    m.function_meta(Map::len__meta)?;
63    m.implement_trait::<Map>(rune::item!(::std::iter::Iterator))?;
64    m.implement_trait::<Map>(rune::item!(::std::iter::DoubleEndedIterator))?;
65    m.implement_trait::<Map>(rune::item!(::std::iter::ExactSizeIterator))?;
66
67    m.ty::<FilterMap>()?;
68    m.function_meta(FilterMap::next__meta)?;
69    m.function_meta(FilterMap::next_back__meta)?;
70    m.implement_trait::<FilterMap>(rune::item!(::std::iter::Iterator))?;
71    m.implement_trait::<FilterMap>(rune::item!(::std::iter::DoubleEndedIterator))?;
72
73    m.ty::<FlatMap>()?;
74    m.function_meta(FlatMap::next__meta)?;
75    m.function_meta(FlatMap::next_back__meta)?;
76    m.function_meta(FlatMap::size_hint__meta)?;
77    m.implement_trait::<FlatMap>(rune::item!(::std::iter::Iterator))?;
78    m.implement_trait::<FlatMap>(rune::item!(::std::iter::DoubleEndedIterator))?;
79
80    m.ty::<Peekable>()?;
81    m.function_meta(Peekable::next__meta)?;
82    m.function_meta(Peekable::next_back__meta)?;
83    m.function_meta(Peekable::size_hint__meta)?;
84    m.function_meta(Peekable::len__meta)?;
85    m.implement_trait::<Peekable>(rune::item!(::std::iter::Iterator))?;
86    m.implement_trait::<Peekable>(rune::item!(::std::iter::DoubleEndedIterator))?;
87    m.implement_trait::<Peekable>(rune::item!(::std::iter::ExactSizeIterator))?;
88    m.function_meta(Peekable::peek__meta)?;
89
90    m.ty::<Skip>()?;
91    m.function_meta(Skip::next__meta)?;
92    m.function_meta(Skip::next_back__meta)?;
93    m.function_meta(Skip::size_hint__meta)?;
94    m.function_meta(Skip::len__meta)?;
95    m.implement_trait::<Skip>(rune::item!(::std::iter::Iterator))?;
96    m.implement_trait::<Skip>(rune::item!(::std::iter::DoubleEndedIterator))?;
97    m.implement_trait::<Skip>(rune::item!(::std::iter::ExactSizeIterator))?;
98
99    m.ty::<Take>()?;
100    m.function_meta(Take::next__meta)?;
101    m.function_meta(Take::next_back__meta)?;
102    m.function_meta(Take::size_hint__meta)?;
103    m.function_meta(Take::len__meta)?;
104    m.implement_trait::<Take>(rune::item!(::std::iter::Iterator))?;
105    m.implement_trait::<Take>(rune::item!(::std::iter::DoubleEndedIterator))?;
106    m.implement_trait::<Take>(rune::item!(::std::iter::ExactSizeIterator))?;
107
108    {
109        let mut t = m.define_trait(["ExactSizeIterator"])?;
110
111        t.docs(docstring! {
112            /// An iterator that knows its exact length.
113            ///
114            /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
115            /// If an iterator knows how many times it can iterate, providing access to
116            /// that information can be useful. For example, if you want to iterate
117            /// backwards, a good start is to know where the end is.
118            ///
119            /// When implementing an `ExactSizeIterator`, you must also implement
120            /// [`Iterator`]. When doing so, the implementation of [`Iterator::size_hint`]
121            /// *must* return the exact size of the iterator.
122            ///
123            /// The [`len`] method has a default implementation, so you usually shouldn't
124            /// implement it. However, you may be able to provide a more performant
125            /// implementation than the default, so overriding it in this case makes sense.
126            ///
127            /// Note that this trait is a safe trait and as such does *not* and *cannot*
128            /// guarantee that the returned length is correct. This means that `unsafe`
129            /// code **must not** rely on the correctness of [`Iterator::size_hint`]. The
130            /// unstable and unsafe [`TrustedLen`](super::marker::TrustedLen) trait gives
131            /// this additional guarantee.
132            ///
133            /// [`len`]: ExactSizeIterator::len
134            ///
135            /// # When *shouldn't* an adapter be `ExactSizeIterator`?
136            ///
137            /// If an adapter makes an iterator *longer*, then it's usually incorrect for
138            /// that adapter to implement `ExactSizeIterator`.  The inner exact-sized
139            /// iterator might already be `usize::MAX`-long, and thus the length of the
140            /// longer adapted iterator would no longer be exactly representable in `usize`.
141            ///
142            /// This is why [`Chain<A, B>`](crate::iter::Chain) isn't `ExactSizeIterator`,
143            /// even when `A` and `B` are both `ExactSizeIterator`.
144            ///
145            /// # Examples
146            ///
147            /// Basic usage:
148            ///
149            /// ```
150            /// // a finite range knows exactly how many times it will iterate
151            /// let five = (0..5).iter();
152            ///
153            /// assert_eq!(five.len(), 5);
154            /// ```
155        })?;
156
157        t.handler(|cx| {
158            _ = cx.find(&Protocol::LEN)?;
159            Ok(())
160        })?;
161
162        t.function("len")?
163            .argument_types::<(Value,)>()?
164            .return_type::<usize>()?
165            .docs(docstring! {
166                /// Returns the exact remaining length of the iterator.
167                ///
168                /// The implementation ensures that the iterator will return
169                /// exactly `len()` more times a [`Some(T)`] value, before
170                /// returning [`None`]. This method has a default
171                /// implementation, so you usually should not implement it
172                /// directly. However, if you can provide a more efficient
173                /// implementation, you can do so. See the [trait-level] docs
174                /// for an example.
175                ///
176                /// This function has the same safety guarantees as the
177                /// [`Iterator::size_hint`] function.
178                ///
179                /// [trait-level]: ExactSizeIterator
180                /// [`Some(T)`]: Some
181                ///
182                /// # Examples
183                ///
184                /// Basic usage:
185                ///
186                /// ```
187                /// // a finite range knows exactly how many times it will iterate
188                /// let range = (0..5).iter();
189                ///
190                /// assert_eq!(range.len(), 5);
191                /// let _ = range.next();
192                /// assert_eq!(range.len(), 4);
193                /// ```
194            })?;
195    }
196
197    {
198        let mut t = m.define_trait(["Iterator"])?;
199
200        t.docs(docstring! {
201            /// A trait for dealing with iterators.
202        })?;
203
204        t.handler(|cx| {
205            let next = cx.find(&Protocol::NEXT)?;
206            let next = Caller::<(Value,), 1, Option<Value>>::new(next);
207
208            let size_hint =
209                cx.find_or_define(&Protocol::SIZE_HINT, |_: Value| (0usize, None::<usize>))?;
210
211            let size_hint = Caller::<(&Value,), 1, (usize, Option<usize>)>::new(size_hint);
212
213            cx.find_or_define(&Protocol::NTH, {
214                let next = next.clone();
215
216                move |iter: Value, mut n: usize| loop {
217                    budget::permit()?;
218
219                    let Some(value) = next.call((iter.clone(),))? else {
220                        break Ok(None);
221                    };
222
223                    if n == 0 {
224                        break Ok::<_, VmError>(Some(value));
225                    }
226
227                    n -= 1;
228                }
229            })?;
230
231            cx.function(&Protocol::INTO_ITER, |value: Value| value)?;
232
233            cx.function("into_iter", |value: Value| value)?;
234
235            {
236                let next = next.clone();
237
238                cx.function("count", move |iter: Value| {
239                    let mut n = 0usize;
240
241                    loop {
242                        budget::permit()?;
243
244                        if next.call((iter.clone(),))?.is_none() {
245                            break Ok::<_, VmError>(n);
246                        };
247
248                        n += 1;
249                    }
250                })?;
251            }
252
253            {
254                let next = next.clone();
255
256                cx.function("fold", move |iter: Value, mut acc: Value, f: Function| {
257                    loop {
258                        budget::permit()?;
259
260                        let Some(value) = next.call((iter.clone(),))? else {
261                            break Ok::<_, VmError>(acc);
262                        };
263
264                        acc = f.call((acc, value))?;
265                    }
266                })?;
267            }
268
269            {
270                let next = next.clone();
271
272                cx.function("reduce", move |iter: Value, f: Function| {
273                    let Some(mut acc) = next.call((iter.clone(),))? else {
274                        return Ok::<_, VmError>(None);
275                    };
276
277                    while let Some(value) = next.call((iter.clone(),))? {
278                        budget::permit()?;
279
280                        acc = f.call((acc, value))?;
281                    }
282
283                    Ok(Some(acc))
284                })?;
285            }
286
287            {
288                let next = next.clone();
289
290                cx.function(
291                    "find",
292                    move |iter: Value, f: Function| -> Result<Option<Value>, VmError> {
293                        loop {
294                            budget::permit()?;
295
296                            let Some(value) = next.call((iter.clone(),))? else {
297                                break Ok(None);
298                            };
299
300                            if f.call::<bool>((value.clone(),))? {
301                                break Ok(Some(value));
302                            }
303                        }
304                    },
305                )?;
306            }
307
308            {
309                let next = next.clone();
310
311                cx.function(
312                    "any",
313                    move |iter: Value, f: Function| -> Result<bool, VmError> {
314                        loop {
315                            budget::permit()?;
316
317                            let Some(value) = next.call((iter.clone(),))? else {
318                                break Ok(false);
319                            };
320
321                            if f.call::<bool>((value.clone(),))? {
322                                break Ok(true);
323                            }
324                        }
325                    },
326                )?;
327            }
328
329            {
330                let next = next.clone();
331
332                cx.function(
333                    "all",
334                    move |iter: Value, f: Function| -> Result<bool, VmError> {
335                        loop {
336                            budget::permit()?;
337
338                            let Some(value) = next.call((iter.clone(),))? else {
339                                break Ok(true);
340                            };
341
342                            if !f.call::<bool>((value.clone(),))? {
343                                break Ok(false);
344                            }
345                        }
346                    },
347                )?;
348            }
349
350            {
351                cx.function("chain", |a: Value, b: Value| -> Result<Chain, VmError> {
352                    let b = b.protocol_into_iter()?;
353
354                    Ok(Chain {
355                        a: Some(a.clone()),
356                        b: Some(b.clone()),
357                    })
358                })?;
359                cx.function("enumerate", move |iter: Value| Enumerate { iter, count: 0 })?;
360                cx.function("filter", move |iter: Value, f: Function| Filter { iter, f })?;
361                cx.function("map", move |iter: Value, f: Function| Map {
362                    iter: Some(iter),
363                    f,
364                })?;
365                cx.function("filter_map", move |iter: Value, f: Function| FilterMap {
366                    iter: Some(iter),
367                    f,
368                })?;
369                cx.function("flat_map", move |iter: Value, f: Function| FlatMap {
370                    map: Map {
371                        iter: Some(iter),
372                        f,
373                    },
374                    frontiter: None,
375                    backiter: None,
376                })?;
377                cx.function("peekable", move |iter: Value| Peekable {
378                    iter,
379                    peeked: None,
380                })?;
381                cx.function("skip", move |iter: Value, n: usize| Skip { iter, n })?;
382                cx.function("take", move |iter: Value, n: usize| Take { iter, n })?;
383            }
384
385            {
386                let next = next.clone();
387                let size_hint = size_hint.clone();
388
389                cx.function(
390                    Params::new("collect", [Vec::HASH]),
391                    move |iter: Value| -> Result<Vec, VmError> {
392                        let (cap, _) = size_hint.call((&iter,))?;
393                        let cap = hint_capacity(cap);
394                        let mut vec = Vec::with_capacity(cap)?;
395
396                        while let Some(value) = next.call((iter.clone(),))? {
397                            budget::permit()?;
398                            vec.push(value)?;
399                        }
400
401                        Ok(vec)
402                    },
403                )?;
404            }
405
406            {
407                let next = next.clone();
408                let size_hint = size_hint.clone();
409
410                cx.function(
411                    Params::new("collect", [VecDeque::HASH]),
412                    move |iter: Value| -> Result<VecDeque, VmError> {
413                        let (cap, _) = size_hint.call((&iter,))?;
414                        let cap = hint_capacity(cap);
415                        let mut vec = Vec::with_capacity(cap)?;
416
417                        while let Some(value) = next.call((iter.clone(),))? {
418                            budget::permit()?;
419                            vec.push(value)?;
420                        }
421
422                        Ok(VecDeque::from(vec))
423                    },
424                )?;
425            }
426
427            {
428                let next = next.clone();
429                let size_hint = size_hint.clone();
430
431                cx.function(
432                    Params::new("collect", [HashSet::HASH]),
433                    move |iter: Value| -> Result<HashSet, VmError> {
434                        let (cap, _) = size_hint.call((&iter,))?;
435                        let cap = hint_capacity(cap);
436                        let mut set = HashSet::with_capacity(cap)?;
437
438                        while let Some(value) = next.call((iter.clone(),))? {
439                            budget::permit()?;
440                            set.insert(value)?;
441                        }
442
443                        Ok(set)
444                    },
445                )?;
446            }
447
448            {
449                let next = next.with_return::<Option<(Value, Value)>>();
450                let size_hint = size_hint.clone();
451
452                cx.function(
453                    Params::new("collect", [HashMap::HASH]),
454                    move |iter: Value| -> Result<HashMap, VmError> {
455                        let (cap, _) = size_hint.call((&iter,))?;
456                        let cap = hint_capacity(cap);
457                        let mut map = HashMap::with_capacity(cap)?;
458
459                        while let Some((key, value)) = next.call((iter.clone(),))? {
460                            budget::permit()?;
461                            map.insert(key, value)?;
462                        }
463
464                        Ok(map)
465                    },
466                )?;
467            }
468
469            {
470                let next = next.with_return::<Option<(String, Value)>>();
471                let size_hint = size_hint.clone();
472
473                cx.function(
474                    Params::new("collect", [Object::HASH]),
475                    move |iter: Value| -> Result<Object, VmError> {
476                        let (cap, _) = size_hint.call((&iter,))?;
477                        let cap = hint_capacity(cap);
478                        let mut map = Object::with_capacity(cap)?;
479
480                        while let Some((key, value)) = next.call((iter.clone(),))? {
481                            budget::permit()?;
482                            map.insert(key, value)?;
483                        }
484
485                        Ok(map)
486                    },
487                )?;
488            }
489
490            {
491                let next = next.clone();
492                let size_hint = size_hint.clone();
493
494                cx.function(
495                    Params::new("collect", [OwnedTuple::HASH]),
496                    move |iter: Value| -> Result<OwnedTuple, VmError> {
497                        let (cap, _) = size_hint.call((&iter,))?;
498                        let cap = hint_capacity(cap);
499                        let mut vec = alloc::Vec::try_with_capacity(cap)?;
500
501                        while let Some(value) = next.call((iter.clone(),))? {
502                            budget::permit()?;
503                            vec.try_push(value)?;
504                        }
505
506                        Ok(OwnedTuple::try_from(vec)?)
507                    },
508                )?;
509            }
510
511            {
512                let next = next.clone();
513
514                cx.function(
515                    Params::new("collect", [String::HASH]),
516                    move |iter: Value| {
517                        let mut string = String::new();
518
519                        while let Some(value) = next.call((iter.clone(),))? {
520                            budget::permit()?;
521
522                            match value.as_ref() {
523                                Repr::Inline(Inline::Char(c)) => {
524                                    string.try_push(*c)?;
525                                }
526                                Repr::Inline(value) => {
527                                    return Err(VmError::expected::<String>(value.type_info()));
528                                }
529                                Repr::Dynamic(value) => {
530                                    return Err(VmError::expected::<String>(value.type_info()));
531                                }
532                                Repr::Any(value) => match value.type_hash() {
533                                    String::HASH => {
534                                        let s = value.borrow_ref::<String>()?;
535                                        string.try_push_str(&s)?;
536                                    }
537                                    _ => {
538                                        return Err(VmError::expected::<String>(value.type_info()));
539                                    }
540                                },
541                            }
542                        }
543
544                        Ok(string)
545                    },
546                )?;
547            }
548
549            macro_rules! ops {
550                ($ty:ty) => {{
551                    cx.function(Params::new("product", [<$ty>::HASH]), |iter: Value| {
552                        let mut product = match iter.protocol_next()? {
553                            Some(init) => <$ty>::from_value(init)?,
554                            None => <$ty>::ONE,
555                        };
556
557                        while let Some(v) = iter.protocol_next()? {
558                            let v = <$ty>::from_value(v)?;
559
560                            let Some(out) = product.checked_mul(v) else {
561                                return Err(VmError::new(VmErrorKind::Overflow));
562                            };
563
564                            product = out;
565                        }
566
567                        Ok(product)
568                    })?;
569                }
570
571                {
572                    cx.function(
573                        Params::new("sum", [<$ty>::HASH]),
574                        |iter: Value| -> Result<$ty, VmError> {
575                            let mut sum = match iter.protocol_next()? {
576                                Some(init) => <$ty>::from_value(init)?,
577                                None => <$ty>::ZERO,
578                            };
579
580                            while let Some(v) = iter.protocol_next()? {
581                                let v = <$ty>::from_value(v)?;
582
583                                let Some(out) = sum.checked_add(v) else {
584                                    return Err(VmError::new(VmErrorKind::Overflow));
585                                };
586
587                                sum = out;
588                            }
589
590                            Ok(sum)
591                        },
592                    )?;
593                }};
594            }
595
596            ops!(u64);
597            ops!(i64);
598            ops!(f64);
599            Ok(())
600        })?;
601
602        t.function("next")?
603            .argument_types::<(Value,)>()?
604            .argument_names(["self"])?
605            .return_type::<Option<Value>>()?
606            .docs(docstring! {
607                /// Advances the iterator and returns the next value.
608                ///
609                /// Returns [`None`] when iteration is finished. Individual iterator
610                /// implementations may choose to resume iteration, and so calling `next()`
611                /// again may or may not eventually start returning [`Some(Item)`] again at some
612                /// point.
613                ///
614                /// [`Some(Item)`]: Some
615                ///
616                /// # Examples
617                ///
618                /// Basic usage:
619                ///
620                /// ```rune
621                /// let a = [1, 2, 3];
622                ///
623                /// let iter = a.iter();
624                ///
625                /// // A call to next() returns the next value...
626                /// assert_eq!(Some(1), iter.next());
627                /// assert_eq!(Some(2), iter.next());
628                /// assert_eq!(Some(3), iter.next());
629                ///
630                /// // ... and then None once it's over.
631                /// assert_eq!(None, iter.next());
632                ///
633                /// // More calls may or may not return `None`. Here, they always will.
634                /// assert_eq!(None, iter.next());
635                /// assert_eq!(None, iter.next());
636                /// ```
637            })?;
638
639        t.function("nth")?
640            .argument_types::<(Value, usize)>()?
641            .argument_names(["self", "n"])?
642            .return_type::<Option<Value>>()?
643            .docs(docstring! {
644                /// Returns the `n`th element of the iterator.
645                ///
646                /// Like most indexing operations, the count starts from zero, so `nth(0)`
647                /// returns the first value, `nth(1)` the second, and so on.
648                ///
649                /// Note that all preceding elements, as well as the returned element, will be
650                /// consumed from the iterator. That means that the preceding elements will be
651                /// discarded, and also that calling `nth(0)` multiple times on the same iterator
652                /// will return different elements.
653                ///
654                /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
655                /// iterator.
656                ///
657                /// # Examples
658                ///
659                /// Basic usage:
660                ///
661                /// ```rune
662                /// let a = [1, 2, 3];
663                /// assert_eq!(a.iter().nth(1), Some(2));
664                /// ```
665                ///
666                /// Calling `nth()` multiple times doesn't rewind the iterator:
667                ///
668                /// ```rune
669                /// let a = [1, 2, 3];
670                ///
671                /// let iter = a.iter();
672                ///
673                /// assert_eq!(iter.nth(1), Some(2));
674                /// assert_eq!(iter.nth(1), None);
675                /// ```
676                ///
677                /// Returning `None` if there are less than `n + 1` elements:
678                ///
679                /// ```
680                /// let a = [1, 2, 3];
681                /// assert_eq!(a.iter().nth(10), None);
682                /// ```
683            })?;
684
685        t.function("size_hint")?
686            .argument_types::<(Value,)>()?
687            .argument_names(["self"])?
688            .return_type::<(usize, Option<usize>)>()?
689            .docs(docstring! {
690                /// Returns the bounds on the remaining length of the iterator.
691                ///
692                /// Specifically, `size_hint()` returns a tuple where the first element
693                /// is the lower bound, and the second element is the upper bound.
694                ///
695                /// The second half of the tuple that is returned is an
696                /// <code>[Option]<[i64]></code>. A [`None`] here means that either there is no
697                /// known upper bound, or the upper bound is larger than [`i64`].
698                ///
699                /// # Implementation notes
700                ///
701                /// It is not enforced that an iterator implementation yields the declared
702                /// number of elements. A buggy iterator may yield less than the lower bound or
703                /// more than the upper bound of elements.
704                ///
705                /// `size_hint()` is primarily intended to be used for optimizations such as
706                /// reserving space for the elements of the iterator, but must not be trusted to
707                /// e.g., omit bounds checks in unsafe code. An incorrect implementation of
708                /// `size_hint()` should not lead to memory safety violations.
709                ///
710                /// That said, the implementation should provide a correct estimation, because
711                /// otherwise it would be a violation of the trait's protocol.
712                ///
713                /// The default implementation returns <code>(0, [None])</code> which is correct
714                /// for any iterator.
715                ///
716                /// # Examples
717                ///
718                /// Basic usage:
719                ///
720                /// ```rune
721                /// let a = [1, 2, 3];
722                /// let iter = a.iter();
723                ///
724                /// assert_eq!(iter.size_hint(), (3u64, Some(3)));
725                /// let _ = iter.next();
726                /// assert_eq!(iter.size_hint(), (2u64, Some(2)));
727                /// ```
728                ///
729                /// A more complex example:
730                ///
731                /// ```rune
732                /// // The even numbers in the range of zero to nine.
733                /// let iter = (0..10).iter().filter(|x| x % 2 == 0);
734                ///
735                /// // We might iterate from zero to ten times. Knowing that it's five
736                /// // exactly wouldn't be possible without executing filter().
737                /// assert_eq!(iter.size_hint(), (0, Some(10)));
738                ///
739                /// // Let's add five more numbers with chain()
740                /// let iter = (0..10).iter().filter(|x| x % 2 == 0).chain(15..20);
741                ///
742                /// // now both bounds are increased by five
743                /// assert_eq!(iter.size_hint(), (5, Some(15)));
744                /// ```
745                ///
746                /// Returning `None` for an upper bound:
747                ///
748                /// ```rune
749                /// // an infinite iterator has no upper bound
750                /// // and the maximum possible lower bound
751                /// let iter = (0..).iter();
752                ///
753                /// assert_eq!(iter.size_hint(), (u64::MAX, None));
754                /// ```
755            })?;
756
757        t.function("count")?
758            .argument_types::<(Value,)>()?
759            .argument_names(["self"])?
760            .return_type::<usize>()?
761            .docs(docstring! {
762                /// Consumes the iterator, counting the number of iterations and returning it.
763                ///
764                /// This method will call [`next`] repeatedly until [`None`] is encountered,
765                /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
766                /// called at least once even if the iterator does not have any elements.
767                ///
768                /// [`next`]: Iterator::next
769                ///
770                /// # Overflow Behavior
771                ///
772                /// The method does no guarding against overflows, so counting elements of an
773                /// iterator with more than [`i64::MAX`] elements panics.
774                ///
775                /// # Panics
776                ///
777                /// This function might panic if the iterator has more than [`i64::MAX`]
778                /// elements.
779                ///
780                /// # Examples
781                ///
782                /// Basic usage:
783                ///
784                /// ```rune
785                /// let a = [1, 2, 3];
786                /// assert_eq!(a.iter().count(), 3);
787                ///
788                /// let a = [1, 2, 3, 4, 5];
789                /// assert_eq!(a.iter().count(), 5);
790                /// ```
791            })?;
792
793        t.function("fold")?
794            .argument_types::<(Value, Value, Function)>()?
795            .argument_names(["self", "init", "f"])?
796            .return_type::<Value>()?
797            .docs(docstring! {
798                /// Folds every element into an accumulator by applying an operation, returning
799                /// the final result.
800                ///
801                /// `fold()` takes two arguments: an initial value, and a closure with two
802                /// arguments: an 'accumulator', and an element. The closure returns the value
803                /// that the accumulator should have for the next iteration.
804                ///
805                /// The initial value is the value the accumulator will have on the first call.
806                ///
807                /// After applying this closure to every element of the iterator, `fold()`
808                /// returns the accumulator.
809                ///
810                /// This operation is sometimes called 'reduce' or 'inject'.
811                ///
812                /// Folding is useful whenever you have a collection of something, and want to
813                /// produce a single value from it.
814                ///
815                /// Note: `fold()`, and similar methods that traverse the entire iterator, might
816                /// not terminate for infinite iterators, even on traits for which a result is
817                /// determinable in finite time.
818                ///
819                /// Note: [`reduce()`] can be used to use the first element as the initial
820                /// value, if the accumulator type and item type is the same.
821                ///
822                /// Note: `fold()` combines elements in a *left-associative* fashion. For
823                /// associative operators like `+`, the order the elements are combined in is
824                /// not important, but for non-associative operators like `-` the order will
825                /// affect the final result. For a *right-associative* version of `fold()`, see
826                /// [`DoubleEndedIterator::rfold()`].
827                ///
828                /// # Note to Implementors
829                ///
830                /// Several of the other (forward) methods have default implementations in
831                /// terms of this one, so try to implement this explicitly if it can
832                /// do something better than the default `for` loop implementation.
833                ///
834                /// In particular, try to have this call `fold()` on the internal parts
835                /// from which this iterator is composed.
836                ///
837                /// # Examples
838                ///
839                /// Basic usage:
840                ///
841                /// ```rune
842                /// let a = [1, 2, 3];
843                ///
844                /// // the sum of all of the elements of the array
845                /// let sum = a.iter().fold(0, |acc, x| acc + x);
846                ///
847                /// assert_eq!(sum, 6);
848                /// ```
849                ///
850                /// Let's walk through each step of the iteration here:
851                ///
852                /// | element | acc | x | result |
853                /// |---------|-----|---|--------|
854                /// |         | 0   |   |        |
855                /// | 1       | 0   | 1 | 1      |
856                /// | 2       | 1   | 2 | 3      |
857                /// | 3       | 3   | 3 | 6      |
858                ///
859                /// And so, our final result, `6`.
860                ///
861                /// This example demonstrates the left-associative nature of `fold()`:
862                /// it builds a string, starting with an initial value
863                /// and continuing with each element from the front until the back:
864                ///
865                /// ```rune
866                /// let numbers = [1, 2, 3, 4, 5];
867                ///
868                /// let zero = "0";
869                ///
870                /// let result = numbers.iter().fold(zero, |acc, x| {
871                ///     format!("({} + {})", acc, x)
872                /// });
873                ///
874                /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
875                /// ```
876                ///
877                /// It's common for people who haven't used iterators a lot to
878                /// use a `for` loop with a list of things to build up a result. Those
879                /// can be turned into `fold()`s:
880                ///
881                /// ```rune
882                /// let numbers = [1, 2, 3, 4, 5];
883                ///
884                /// let result = 0;
885                ///
886                /// // for loop:
887                /// for i in numbers {
888                ///     result = result + i;
889                /// }
890                ///
891                /// // fold:
892                /// let result2 = numbers.iter().fold(0, |acc, x| acc + x);
893                ///
894                /// // they're the same
895                /// assert_eq!(result, result2);
896                /// ```
897                ///
898                /// [`reduce()`]: Iterator::reduce
899            })?;
900
901        t.function("reduce")?
902            .argument_types::<(Value, Function)>()?
903            .argument_names(["self", "f"])?
904            .return_type::<Option<Value>>()?
905            .docs(docstring! {
906                /// Reduces the elements to a single one, by repeatedly applying a reducing
907                /// operation.
908                ///
909                /// If the iterator is empty, returns [`None`]; otherwise, returns the result of
910                /// the reduction.
911                ///
912                /// The reducing function is a closure with two arguments: an 'accumulator', and
913                /// an element. For iterators with at least one element, this is the same as
914                /// [`fold()`] with the first element of the iterator as the initial accumulator
915                /// value, folding every subsequent element into it.
916                ///
917                /// [`fold()`]: Iterator::fold
918                ///
919                /// # Example
920                ///
921                /// ```rune
922                /// let reduced = (1..10).iter().reduce(|acc, e| acc + e).unwrap();
923                /// assert_eq!(reduced, 45);
924                ///
925                /// // Which is equivalent to doing it with `fold`:
926                /// let folded = (1..10).iter().fold(0, |acc, e| acc + e);
927                /// assert_eq!(reduced, folded);
928                /// ```
929            })?;
930
931        t.function("find")?
932            .argument_types::<(Value, Function)>()?
933            .argument_names(["self", "predicate"])?
934            .return_type::<Option<Value>>()?
935            .docs(docstring! {
936                /// Searches for an element of an iterator that satisfies a predicate.
937                ///
938                /// `find()` takes a closure that returns `true` or `false`. It applies this
939                /// closure to each element of the iterator, and if any of them return `true`,
940                /// then `find()` returns [`Some(element)`]. If they all return `false`, it
941                /// returns [`None`].
942                ///
943                /// `find()` is short-circuiting; in other words, it will stop processing as
944                /// soon as the closure returns `true`.
945                ///
946                /// If you need the index of the element, see [`position()`].
947                ///
948                /// [`Some(element)`]: Some
949                /// [`position()`]: Iterator::position
950                ///
951                /// # Examples
952                ///
953                /// Basic usage:
954                ///
955                /// ```rune
956                /// let a = [1, 2, 3];
957                ///
958                /// assert_eq!(a.iter().find(|x| x == 2), Some(2));
959                ///
960                /// assert_eq!(a.iter().find(|x| x == 5), None);
961                /// ```
962                ///
963                /// Stopping at the first `true`:
964                ///
965                /// ```rune
966                /// let a = [1, 2, 3];
967                ///
968                /// let iter = a.iter();
969                ///
970                /// assert_eq!(iter.find(|x| x == 2), Some(2));
971                ///
972                /// // we can still use `iter`, as there are more elements.
973                /// assert_eq!(iter.next(), Some(3));
974                /// ```
975                ///
976                /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
977            })?;
978
979        t.function("any")?
980            .argument_types::<(Value, Function)>()?
981            .argument_names(["self", "f"])?
982            .return_type::<bool>()?
983            .docs(docstring! {
984                /// Tests if any element of the iterator matches a predicate.
985                ///
986                /// `any()` takes a closure that returns `true` or `false`. It applies this
987                /// closure to each element of the iterator, and if any of them return `true`,
988                /// then so does `any()`. If they all return `false`, it returns `false`.
989                ///
990                /// `any()` is short-circuiting; in other words, it will stop processing as soon
991                /// as it finds a `true`, given that no matter what else happens, the result
992                /// will also be `true`.
993                ///
994                /// An empty iterator returns `false`.
995                ///
996                /// # Examples
997                ///
998                /// Basic usage:
999                ///
1000                /// ```rune
1001                /// let a = [1, 2, 3];
1002                ///
1003                /// assert!(a.iter().any(|x| x > 0));
1004                ///
1005                /// assert!(!a.iter().any(|x| x > 5));
1006                /// ```
1007                ///
1008                /// Stopping at the first `true`:
1009                ///
1010                /// ```rune
1011                /// let a = [1, 2, 3];
1012                ///
1013                /// let iter = a.iter();
1014                ///
1015                /// assert!(iter.any(|x| x != 2));
1016                ///
1017                /// // we can still use `iter`, as there are more elements.
1018                /// assert_eq!(iter.next(), Some(2));
1019                /// ```
1020            })?;
1021
1022        t.function("all")?
1023            .argument_types::<(Value, Function)>()?
1024            .argument_names(["self", "f"])?
1025            .return_type::<bool>()?
1026            .docs(docstring! {
1027                /// Tests if every element of the iterator matches a predicate.
1028                ///
1029                /// `all()` takes a closure that returns `true` or `false`. It applies this
1030                /// closure to each element of the iterator, and if they all return `true`, then
1031                /// so does `all()`. If any of them return `false`, it returns `false`.
1032                ///
1033                /// `all()` is short-circuiting; in other words, it will stop processing as soon
1034                /// as it finds a `false`, given that no matter what else happens, the result
1035                /// will also be `false`.
1036                ///
1037                /// An empty iterator returns `true`.
1038                ///
1039                /// # Examples
1040                ///
1041                /// Basic usage:
1042                ///
1043                /// ```rune
1044                /// let a = [1, 2, 3];
1045                ///
1046                /// assert!(a.iter().all(|x| x > 0));
1047                ///
1048                /// assert!(!a.iter().all(|x| x > 2));
1049                /// ```
1050                ///
1051                /// Stopping at the first `false`:
1052                ///
1053                /// ```rune
1054                /// let a = [1, 2, 3];
1055                ///
1056                /// let iter = a.iter();
1057                ///
1058                /// assert!(!iter.all(|x| x != 2));
1059                ///
1060                /// // we can still use `iter`, as there are more elements.
1061                /// assert_eq!(iter.next(), Some(3));
1062                /// ```
1063            })?;
1064
1065        t.function("chain")?
1066            .argument_types::<(Value, Value)>()?
1067            .argument_names(["self", "other"])?
1068            .return_type::<Chain>()?
1069            .docs(docstring! {
1070                /// Takes two iterators and creates a new iterator over both in sequence.
1071                ///
1072                /// `chain()` will return a new iterator which will first iterate over
1073                /// values from the first iterator and then over values from the second
1074                /// iterator.
1075                ///
1076                /// In other words, it links two iterators together, in a chain. 🔗
1077                ///
1078                /// [`once`] is commonly used to adapt a single value into a chain of other
1079                /// kinds of iteration.
1080                ///
1081                /// # Examples
1082                ///
1083                /// Basic usage:
1084                ///
1085                /// ```rune
1086                /// let a1 = [1, 2, 3];
1087                /// let a2 = [4, 5, 6];
1088                ///
1089                /// let iter = a1.iter().chain(a2.iter());
1090                ///
1091                /// assert_eq!(iter.next(), Some(1));
1092                /// assert_eq!(iter.next(), Some(2));
1093                /// assert_eq!(iter.next(), Some(3));
1094                /// assert_eq!(iter.next(), Some(4));
1095                /// assert_eq!(iter.next(), Some(5));
1096                /// assert_eq!(iter.next(), Some(6));
1097                /// assert_eq!(iter.next(), None);
1098                /// ```
1099                ///
1100                /// Since the argument to `chain()` uses [`INTO_ITER`], we can pass anything
1101                /// that can be converted into an [`Iterator`], not just an [`Iterator`] itself.
1102                /// For example, slices (`[T]`) implement [`INTO_ITER`], and so can be passed to
1103                /// `chain()` directly:
1104                ///
1105                /// ```rune
1106                /// let s1 = [1, 2, 3];
1107                /// let s2 = [4, 5, 6];
1108                ///
1109                /// let iter = s1.iter().chain(s2);
1110                ///
1111                /// assert_eq!(iter.next(), Some(1));
1112                /// assert_eq!(iter.next(), Some(2));
1113                /// assert_eq!(iter.next(), Some(3));
1114                /// assert_eq!(iter.next(), Some(4));
1115                /// assert_eq!(iter.next(), Some(5));
1116                /// assert_eq!(iter.next(), Some(6));
1117                /// assert_eq!(iter.next(), None);
1118                /// ```
1119                ///
1120                /// [`INTO_ITER`]: protocol@INTO_ITER
1121            })?;
1122
1123        t.function("enumerate")?
1124            .argument_types::<(Value,)>()?
1125            .argument_names(["self"])?
1126            .return_type::<Enumerate>()?
1127            .docs(docstring! {
1128                /// Creates an iterator which gives the current iteration count as well as
1129                /// the next value.
1130                ///
1131                /// The iterator returned yields pairs `(i, val)`, where `i` is the current
1132                /// index of iteration and `val` is the value returned by the iterator.
1133                ///
1134                /// `enumerate()` keeps its count as a usize. If you want to count by a
1135                /// different sized integer, the zip function provides similar
1136                /// functionality.
1137                ///
1138                /// # Examples
1139                ///
1140                /// ```rune
1141                /// let a = ['a', 'b', 'c'];
1142                ///
1143                /// let iter = a.iter().enumerate();
1144                ///
1145                /// assert_eq!(iter.next(), Some((0u64, 'a')));
1146                /// assert_eq!(iter.next(), Some((1u64, 'b')));
1147                /// assert_eq!(iter.next(), Some((2u64, 'c')));
1148                /// assert_eq!(iter.next(), None);
1149                /// ```
1150            })?;
1151
1152        t.function("filter")?
1153            .argument_types::<(Value, Function)>()?
1154            .argument_names(["self", "filter"])?
1155            .return_type::<Filter>()?
1156            .docs(docstring! {
1157                /// Creates an iterator which uses a closure to determine if an element
1158                /// should be yielded.
1159                ///
1160                /// Given an element the closure must return `true` or `false`. The returned
1161                /// iterator will yield only the elements for which the closure returns
1162                /// `true`.
1163                ///
1164                /// ```rune
1165                /// let a = [0, 1, 2];
1166                ///
1167                /// let iter = a.iter().filter(|x| x.is_positive());
1168                ///
1169                /// assert_eq!(iter.next(), Some(1));
1170                /// assert_eq!(iter.next(), Some(2));
1171                /// assert_eq!(iter.next(), None);
1172                /// ```
1173            })?;
1174
1175        t.function("map")?
1176            .argument_types::<(Value, Function)>()?
1177            .argument_names(["self", "f"])?
1178            .return_type::<Map>()?
1179            .docs(docstring! {
1180                /// Takes a closure and creates an iterator which calls that closure on each
1181                /// element.
1182                ///
1183                /// `map()` transforms one iterator into another. It produces a new iterator
1184                /// which calls this closure on each element of the original iterator.
1185                ///
1186                /// If you are good at thinking in types, you can think of `map()` like
1187                /// this: If you have an iterator that gives you elements of some type `A`,
1188                /// and you want an iterator of some other type `B`, you can use `map()`,
1189                /// passing a closure that takes an `A` and returns a `B`.
1190                ///
1191                /// `map()` is conceptually similar to a `for` loop. However, as `map()` is
1192                /// lazy, it is best used when you're already working with other iterators.
1193                /// If you're doing some sort of looping for a side effect, it's considered
1194                /// more idiomatic to use `for` than `map()`.
1195                ///
1196                /// # Examples
1197                ///
1198                /// Basic usage:
1199                ///
1200                /// ```rune
1201                /// let a = [1, 2, 3];
1202                ///
1203                /// let iter = a.iter().map(|x| 2 * x);
1204                ///
1205                /// assert_eq!(iter.next(), Some(2));
1206                /// assert_eq!(iter.next(), Some(4));
1207                /// assert_eq!(iter.next(), Some(6));
1208                /// assert_eq!(iter.next(), None);
1209                /// ```
1210                ///
1211                /// If you're doing some sort of side effect, prefer `for` to `map()`:
1212                ///
1213                /// ```rune
1214                /// // don't do this:
1215                /// (0..5).iter().map(|x| println!("{}", x));
1216                ///
1217                /// // it won't even execute, as it is lazy. Rust will warn you about this.
1218                ///
1219                /// // Instead, use for:
1220                /// for x in 0..5 {
1221                ///     println!("{}", x);
1222                /// }
1223                /// ```
1224            })?;
1225
1226        t.function("filter_map")?
1227            .argument_types::<(Value, Function)>()?
1228            .argument_names(["self", "f"])?
1229            .return_type::<FilterMap>()?
1230            .docs(docstring! {
1231                /// Creates an iterator that both filters and maps.
1232                ///
1233                /// The returned iterator yields only the `value`s for which the supplied
1234                /// closure returns `Some(value)`.
1235                ///
1236                /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
1237                /// concise. The example below shows how a `map().filter().map()` can be
1238                /// shortened to a single call to `filter_map`.
1239                ///
1240                /// [`filter`]: Iterator::filter
1241                /// [`map`]: Iterator::map
1242                ///
1243                /// # Examples
1244                ///
1245                /// Basic usage:
1246                ///
1247                /// ```rune
1248                /// let a = ["1", "two", "NaN", "four", "5"];
1249                ///
1250                /// let iter = a.iter().filter_map(|s| s.parse::<i64>().ok());
1251                ///
1252                /// assert_eq!(iter.next(), Some(1));
1253                /// assert_eq!(iter.next(), Some(5));
1254                /// assert_eq!(iter.next(), None);
1255                /// ```
1256                ///
1257                /// Here's the same example, but with [`filter`] and [`map`]:
1258                ///
1259                /// ```rune
1260                /// let a = ["1", "two", "NaN", "four", "5"];
1261                /// let iter = a.iter().map(|s| s.parse::<i64>()).filter(|s| s.is_ok()).map(|s| s.unwrap());
1262                /// assert_eq!(iter.next(), Some(1));
1263                /// assert_eq!(iter.next(), Some(5));
1264                /// assert_eq!(iter.next(), None);
1265                /// ```
1266            })?;
1267
1268        t.function("flat_map")?
1269            .argument_types::<(Value, Function)>()?
1270            .argument_names(["self", "f"])?
1271            .return_type::<FlatMap>()?
1272            .docs(docstring! {
1273                /// Creates an iterator that works like map, but flattens nested
1274                /// structure.
1275                ///
1276                /// The [`map`] adapter is very useful, but only when the
1277                /// closure argument produces values. If it produces an iterator
1278                /// instead, there's an extra layer of indirection. `flat_map()`
1279                /// will remove this extra layer on its own.
1280                ///
1281                /// You can think of `flat_map(f)` as the semantic equivalent of
1282                /// [`map`]ping, and then [`flatten`]ing as in
1283                /// `map(f).flatten()`.
1284                ///
1285                /// Another way of thinking about `flat_map()`: [`map`]'s
1286                /// closure returns one item for each element, and
1287                /// `flat_map()`'s closure returns an iterator for each element.
1288                ///
1289                /// [`map`]: Iterator::map
1290                /// [`flatten`]: Iterator::flatten
1291                ///
1292                /// # Examples
1293                ///
1294                /// Basic usage:
1295                ///
1296                /// ```rune
1297                /// let words = ["alpha", "beta", "gamma"];
1298                ///
1299                /// // chars() returns an iterator
1300                /// let merged = words.iter().flat_map(|s| s.chars()).collect::<String>();
1301                /// assert_eq!(merged, "alphabetagamma");
1302                /// ```
1303            })?;
1304
1305        t.function("peekable")?
1306            .argument_types::<(Value,)>()?
1307            .argument_names(["self"])?
1308            .return_type::<Peekable>()?
1309            .docs(docstring! {
1310                /// Creates an iterator which can use the [`peek`] method to
1311                /// look at the next element of the iterator without consuming
1312                /// it. See their documentation for more information.
1313                ///
1314                /// Note that the underlying iterator is still advanced when
1315                /// [`peek`] are called for the first time: In order to retrieve
1316                /// the next element, [`next`] is called on the underlying
1317                /// iterator, hence any side effects (i.e. anything other than
1318                /// fetching the next value) of the [`next`] method will occur.
1319                ///
1320                /// # Examples
1321                ///
1322                /// Basic usage:
1323                ///
1324                /// ```rune
1325                /// let xs = [1, 2, 3];
1326                ///
1327                /// let iter = xs.iter().peekable();
1328                ///
1329                /// // peek() lets us see into the future
1330                /// assert_eq!(iter.peek(), Some(1));
1331                /// assert_eq!(iter.next(), Some(1));
1332                ///
1333                /// assert_eq!(iter.next(), Some(2));
1334                ///
1335                /// // we can peek() multiple times, the iterator won't advance
1336                /// assert_eq!(iter.peek(), Some(3));
1337                /// assert_eq!(iter.peek(), Some(3));
1338                ///
1339                /// assert_eq!(iter.next(), Some(3));
1340                ///
1341                /// // after the iterator is finished, so is peek()
1342                /// assert_eq!(iter.peek(), None);
1343                /// assert_eq!(iter.next(), None);
1344                /// ```
1345                ///
1346                /// [`peek`]: Peekable::peek
1347                /// [`next`]: Iterator::next
1348            })?;
1349
1350        t.function("skip")?
1351            .argument_types::<(Value, usize)>()?
1352            .argument_names(["self", "n"])?
1353            .return_type::<Skip>()?
1354            .docs(docstring! {
1355                /// Creates an iterator that skips the first `n` elements.
1356                ///
1357                /// `skip(n)` skips elements until `n` elements are skipped or
1358                /// the end of the iterator is reached (whichever happens
1359                /// first). After that, all the remaining elements are yielded.
1360                /// In particular, if the original iterator is too short, then
1361                /// the returned iterator is empty.
1362                ///
1363                /// # Examples
1364                ///
1365                /// Basic usage:
1366                ///
1367                /// ```rune
1368                /// let a = [1, 2, 3];
1369                ///
1370                /// let iter = a.iter().skip(2);
1371                ///
1372                /// assert_eq!(iter.next(), Some(3));
1373                /// assert_eq!(iter.next(), None);
1374                /// ```
1375            })?;
1376
1377        t.function("take")?
1378            .argument_types::<(Value, usize)>()?
1379            .argument_names(["self", "n"])?
1380            .return_type::<Take>()?
1381            .docs(docstring! {
1382                /// Creates an iterator that yields the first `n` elements, or
1383                /// fewer if the underlying iterator ends sooner.
1384                ///
1385                /// `take(n)` yields elements until `n` elements are yielded or
1386                /// the end of the iterator is reached (whichever happens
1387                /// first). The returned iterator is a prefix of length `n` if
1388                /// the original iterator contains at least `n` elements,
1389                /// otherwise it contains all of the (fewer than `n`) elements
1390                /// of the original iterator.
1391                ///
1392                /// # Examples
1393                ///
1394                /// Basic usage:
1395                ///
1396                /// ```rune
1397                /// let a = [1, 2, 3];
1398                ///
1399                /// let iter = a.iter().take(2);
1400                ///
1401                /// assert_eq!(iter.next(), Some(1));
1402                /// assert_eq!(iter.next(), Some(2));
1403                /// assert_eq!(iter.next(), None);
1404                /// ```
1405                ///
1406                /// `take()` is often used with an infinite iterator, to make it
1407                /// finite:
1408                ///
1409                /// ```rune
1410                /// let iter = (0..).iter().take(3);
1411                ///
1412                /// assert_eq!(iter.next(), Some(0));
1413                /// assert_eq!(iter.next(), Some(1));
1414                /// assert_eq!(iter.next(), Some(2));
1415                /// assert_eq!(iter.next(), None);
1416                /// ```
1417                ///
1418                /// If less than `n` elements are available, `take` will limit
1419                /// itself to the size of the underlying iterator:
1420                ///
1421                /// ```rune
1422                /// let v = [1, 2];
1423                /// let iter = v.iter().take(5);
1424                /// assert_eq!(iter.next(), Some(1));
1425                /// assert_eq!(iter.next(), Some(2));
1426                /// assert_eq!(iter.next(), None);
1427                /// ```
1428            })?;
1429
1430        macro_rules! sum_ops {
1431            ($ty:ty) => {
1432                t.function(Params::new("sum", [<$ty>::HASH]))?
1433                    .argument_types::<(Value,)>()?
1434                    .argument_names(["self"])?
1435                    .return_type::<$ty>()?
1436                    .docs(docstring! {
1437                        /// Sums the elements of an iterator.
1438                        ///
1439                        /// Takes each element, adds them together, and returns
1440                        /// the result.
1441                        ///
1442                        /// An empty iterator returns the zero value of the
1443                        /// type.
1444                        ///
1445                        /// `sum()` can be used to sum numerical built-in types,
1446                        /// such as `i64`, `float` and `u64`. The first element
1447                        /// returned by the iterator determines the type being
1448                        /// summed.
1449                        ///
1450                        /// # Panics
1451                        ///
1452                        /// When calling `sum()` and a primitive integer type is
1453                        /// being returned, this method will panic if the
1454                        /// computation overflows.
1455                        ///
1456                        /// # Examples
1457                        ///
1458                        /// Basic usage:
1459                        ///
1460                        /// ```rune
1461                        #[doc = concat!(" let a = [1", stringify!($ty), ", 2", stringify!($ty), ", 3", stringify!($ty), "];")]
1462                        #[doc = concat!(" let sum = a.iter().sum::<", stringify!($ty), ">();")]
1463                        ///
1464                        #[doc = concat!(" assert_eq!(sum, 6", stringify!($ty), ");")]
1465                        /// ```
1466                    })?;
1467            };
1468        }
1469
1470        sum_ops!(u64);
1471        sum_ops!(i64);
1472        sum_ops!(f64);
1473
1474        macro_rules! integer_product_ops {
1475            ($ty:ty) => {
1476                t.function(Params::new("product", [<$ty>::HASH]))?
1477                    .argument_types::<(Value,)>()?
1478                    .argument_names(["self"])?
1479                    .return_type::<$ty>()?
1480                    .docs(docstring! {
1481                        /// Iterates over the entire iterator, multiplying all
1482                        /// the elements
1483                        ///
1484                        /// An empty iterator returns the one value of the type.
1485                        ///
1486                        /// `sum()` can be used to sum numerical built-in types,
1487                        /// such as `i64`, `f64` and `u64`. The first element
1488                        /// returned by the iterator determines the type being
1489                        /// multiplied.
1490                        ///
1491                        /// # Panics
1492                        ///
1493                        /// When calling `product()` and a primitive integer
1494                        /// type is being returned, method will panic if the
1495                        /// computation overflows.
1496                        ///
1497                        /// # Examples
1498                        ///
1499                        /// ```rune
1500                        /// fn factorial(n) {
1501                        #[doc = concat!("     (1", stringify!($ty), "..=n).iter().product::<", stringify!($ty), ">()")]
1502                        /// }
1503                        ///
1504                        #[doc = concat!(" assert_eq!(factorial(0", stringify!($ty), "), 1", stringify!($ty), ");")]
1505                        #[doc = concat!(" assert_eq!(factorial(1", stringify!($ty), "), 1", stringify!($ty), ");")]
1506                        #[doc = concat!(" assert_eq!(factorial(5", stringify!($ty), "), 120", stringify!($ty), ");")]
1507                        /// ```
1508                    })?;
1509            };
1510        }
1511
1512        t.function(Params::new("collect", [Vec::HASH]))?
1513            .argument_types::<(Value,)>()?
1514            .argument_names(["self"])?
1515            .return_type::<Vec>()?
1516            .docs(docstring! {
1517                /// Collect the iterator as a [`Vec`].
1518                ///
1519                /// # Examples
1520                ///
1521                /// ```rune
1522                /// use std::iter::range;
1523                ///
1524                /// assert_eq!((0..3).iter().collect::<Vec>(), [0, 1, 2]);
1525                /// ```
1526            })?;
1527
1528        t.function(Params::new("collect", [VecDeque::HASH]))?
1529            .argument_types::<(Value,)>()?
1530            .argument_names(["self"])?
1531            .return_type::<VecDeque>()?
1532            .docs(docstring! {
1533                /// Collect the iterator as a [`VecDeque`].
1534                ///
1535                /// # Examples
1536                ///
1537                /// ```rune
1538                /// use std::collections::VecDeque;
1539                ///
1540                /// assert_eq!((0..3).iter().collect::<VecDeque>(), VecDeque::from::<Vec>([0, 1, 2]));
1541                /// ```
1542            })?;
1543
1544        t.function(Params::new("collect", [HashSet::HASH]))?
1545            .argument_types::<(Value,)>()?
1546            .argument_names(["self"])?
1547            .return_type::<HashSet>()?
1548            .docs(docstring! {
1549                /// Collect the iterator as a [`HashSet`].
1550                ///
1551                /// # Examples
1552                ///
1553                /// ```rune
1554                /// use std::collections::HashSet;
1555                ///
1556                /// let a = (0..3).iter().collect::<HashSet>();
1557                /// let b = HashSet::from_iter([0, 1, 2]);
1558                ///
1559                /// assert_eq!(a, b);
1560                /// ```
1561            })?;
1562
1563        t.function(Params::new("collect", [HashMap::HASH]))?
1564            .argument_types::<(Value,)>()?
1565            .argument_names(["self"])?
1566            .return_type::<HashMap>()?
1567            .docs(docstring! {
1568                /// Collect the iterator as a [`HashMap`].
1569                ///
1570                /// # Examples
1571                ///
1572                /// ```rune
1573                /// use std::collections::HashMap;
1574                ///
1575                /// let actual = (0..3).iter().map(|n| (n, n.to_string())).collect::<HashMap>();
1576                ///
1577                /// let expected = HashMap::from_iter([
1578                ///     (0, "0"),
1579                ///     (1, "1"),
1580                ///     (2, "2"),
1581                /// ]);
1582                ///
1583                /// assert_eq!(actual, expected);
1584                /// ```
1585            })?;
1586
1587        t.function(Params::new("collect", [Object::HASH]))?
1588            .argument_types::<(Value,)>()?
1589            .argument_names(["self"])?
1590            .return_type::<HashMap>()?
1591            .docs(docstring! {
1592                /// Collect the iterator as an [`Object`].
1593                ///
1594                /// # Examples
1595                ///
1596                /// ```rune
1597                /// assert_eq!([("first", 1), ("second", 2)].iter().collect::<Object>(), #{first: 1, second: 2});
1598                /// ```
1599            })?;
1600
1601        t.function(Params::new("collect", [OwnedTuple::HASH]))?
1602            .argument_types::<(Value,)>()?
1603            .argument_names(["self"])?
1604            .return_type::<OwnedTuple>()?
1605            .docs(docstring! {
1606                /// Collect the iterator as a [`Tuple`].
1607                ///
1608                /// # Examples
1609                ///
1610                /// ```rune
1611                /// assert_eq!((0..3).iter().collect::<Tuple>(), (0, 1, 2));
1612                /// ```
1613            })?;
1614
1615        t.function(Params::new("collect", [String::HASH]))?
1616            .argument_types::<(Value,)>()?
1617            .argument_names(["self"])?
1618            .return_type::<String>()?
1619            .docs(docstring! {
1620                /// Collect the iterator as a [`String`].
1621                ///
1622                /// # Examples
1623                ///
1624                /// ```rune
1625                /// assert_eq!(["first", "second"].iter().collect::<String>(), "firstsecond");
1626                /// ```
1627            })?;
1628
1629        macro_rules! float_product_ops {
1630            ($ty:ty) => {
1631                t.function(Params::new("product", [<$ty>::HASH]))?
1632                    .argument_types::<(Value,)>()?
1633                    .argument_names(["self"])?
1634                    .return_type::<$ty>()?
1635                    .docs(docstring! {
1636                        /// Iterates over the entire iterator, multiplying all
1637                        /// the elements
1638                        ///
1639                        /// An empty iterator returns the one value of the type.
1640                        ///
1641                        /// `sum()` can be used to sum numerical built-in types,
1642                        /// such as `i64`, `f64` and `u64`. The first element
1643                        /// returned by the iterator determines the type being
1644                        /// multiplied.
1645                        ///
1646                        /// # Panics
1647                        ///
1648                        /// When calling `product()` and a primitive integer
1649                        /// type is being returned, method will panic if the
1650                        /// computation overflows.
1651                        ///
1652                        /// # Examples
1653                        ///
1654                        /// ```rune
1655                        /// fn factorial(n) {
1656                        #[doc = concat!("     (1..=n).iter().map(|n| n as ", stringify!($ty), ").product::<", stringify!($ty), ">()")]
1657                        /// }
1658                        ///
1659                        #[doc = concat!(" assert_eq!(factorial(0), 1", stringify!($ty), ");")]
1660                        #[doc = concat!(" assert_eq!(factorial(1), 1", stringify!($ty), ");")]
1661                        #[doc = concat!(" assert_eq!(factorial(5), 120", stringify!($ty), ");")]
1662                        /// ```
1663                    })?;
1664            };
1665        }
1666
1667        integer_product_ops!(u64);
1668        integer_product_ops!(i64);
1669        float_product_ops!(f64);
1670    }
1671
1672    {
1673        let mut t = m.define_trait(["DoubleEndedIterator"])?;
1674
1675        t.docs(docstring! {
1676            /// An iterator able to yield elements from both ends.
1677            ///
1678            /// Something that implements `DoubleEndedIterator` has one extra
1679            /// capability over something that implements [`Iterator`]: the
1680            /// ability to also take `Item`s from the back, as well as the
1681            /// front.
1682            ///
1683            /// It is important to note that both back and forth work on the
1684            /// same range, and do not cross: iteration is over when they meet
1685            /// in the middle.
1686            ///
1687            /// In a similar fashion to the [`Iterator`] protocol, once a
1688            /// `DoubleEndedIterator` returns [`None`] from a [`next_back()`],
1689            /// calling it again may or may not ever return [`Some`] again.
1690            /// [`next()`] and [`next_back()`] are interchangeable for this
1691            /// purpose.
1692            ///
1693            /// [`next_back()`]: DoubleEndedIterator::next_back
1694            /// [`next()`]: Iterator::next
1695            ///
1696            /// # Examples
1697            ///
1698            /// Basic usage:
1699            ///
1700            /// ```
1701            /// let numbers = [1, 2, 3, 4, 5, 6];
1702            ///
1703            /// let iter = numbers.iter();
1704            ///
1705            /// assert_eq!(Some(1), iter.next());
1706            /// assert_eq!(Some(6), iter.next_back());
1707            /// assert_eq!(Some(5), iter.next_back());
1708            /// assert_eq!(Some(2), iter.next());
1709            /// assert_eq!(Some(3), iter.next());
1710            /// assert_eq!(Some(4), iter.next());
1711            /// assert_eq!(None, iter.next());
1712            /// assert_eq!(None, iter.next_back());
1713            /// ```
1714        })?;
1715
1716        t.handler(|cx| {
1717            let next_back = cx.find(&Protocol::NEXT_BACK)?;
1718
1719            cx.find_or_define(&Protocol::NTH_BACK, {
1720                let next_back = next_back.clone();
1721
1722                move |iterator: Value, mut n: usize| -> Result<Option<Value>, VmError> {
1723                    loop {
1724                        budget::permit()?;
1725
1726                        let mut memory = [iterator.clone()];
1727                        next_back.call(&mut memory, Address::ZERO, 1, Output::keep(0))?;
1728                        let [value] = memory;
1729
1730                        let Some(value) = Option::<Value>::from_value(value)? else {
1731                            break Ok(None);
1732                        };
1733
1734                        if n == 0 {
1735                            break Ok(Some(value));
1736                        }
1737
1738                        n -= 1;
1739                    }
1740                }
1741            })?;
1742
1743            cx.raw_function("rev", |stack, addr, len, out| {
1744                let [value] = stack.slice_at(addr, len)? else {
1745                    return Err(VmError::new(VmErrorKind::BadArgumentCount {
1746                        actual: len,
1747                        expected: 1,
1748                    }));
1749                };
1750
1751                let rev = Rev {
1752                    value: value.clone(),
1753                };
1754
1755                stack.store(out, || rune::to_value(rev))?;
1756                Ok(())
1757            })?;
1758
1759            Ok(())
1760        })?;
1761
1762        t.function("next_back")?
1763            .argument_types::<(Value,)>()?
1764            .argument_names(["self"])?
1765            .return_type::<Option<Value>>()?
1766            .docs(docstring! {
1767                /// Removes and returns an element from the end of the iterator.
1768                ///
1769                /// Returns `None` when there are no more elements.
1770                ///
1771                /// # Examples
1772                ///
1773                /// Basic usage:
1774                ///
1775                /// ```rune
1776                /// let numbers = [1, 2, 3, 4, 5, 6];
1777                ///
1778                /// let iter = numbers.iter();
1779                ///
1780                /// assert_eq!(Some(1), iter.next());
1781                /// assert_eq!(Some(6), iter.next_back());
1782                /// assert_eq!(Some(5), iter.next_back());
1783                /// assert_eq!(Some(2), iter.next());
1784                /// assert_eq!(Some(3), iter.next());
1785                /// assert_eq!(Some(4), iter.next());
1786                /// assert_eq!(None, iter.next());
1787                /// assert_eq!(None, iter.next_back());
1788                /// ```
1789            })?;
1790
1791        t.function("nth_back")?
1792            .argument_types::<(Value, usize)>()?
1793            .argument_names(["self", "n"])?
1794            .return_type::<Option<Value>>()?
1795            .docs(docstring! {
1796                /// Returns the `n`th element from the end of the iterator.
1797                ///
1798                /// This is essentially the reversed version of
1799                /// [`Iterator::nth()`]. Although like most indexing operations,
1800                /// the count starts from zero, so `nth_back(0)` returns the
1801                /// first value from the end, `nth_back(1)` the second, and so
1802                /// on.
1803                ///
1804                /// Note that all elements between the end and the returned
1805                /// element will be consumed, including the returned element.
1806                /// This also means that calling `nth_back(0)` multiple times on
1807                /// the same iterator will return different elements.
1808                ///
1809                /// `nth_back()` will return [`None`] if `n` is greater than or
1810                /// equal to the length of the iterator.
1811                ///
1812                /// # Examples
1813                ///
1814                /// Basic usage:
1815                ///
1816                /// ```rune
1817                /// let a = [1, 2, 3];
1818                /// assert_eq!(a.iter().nth_back(2), Some(1));
1819                /// ```
1820                ///
1821                /// Calling `nth_back()` multiple times doesn't rewind the
1822                /// iterator:
1823                ///
1824                /// ```rune
1825                /// let a = [1, 2, 3];
1826                ///
1827                /// let iter = a.iter();
1828                ///
1829                /// assert_eq!(iter.nth_back(1), Some(2));
1830                /// assert_eq!(iter.nth_back(1), None);
1831                /// ```
1832                ///
1833                /// Returning `None` if there are less than `n + 1` elements:
1834                ///
1835                /// ```rune
1836                /// let a = [1, 2, 3];
1837                /// assert_eq!(a.iter().nth_back(10), None);
1838                /// ```
1839            })?;
1840
1841        t.function("rev")?
1842            .argument_types::<(Value,)>()?
1843            .argument_names(["self"])?
1844            .return_type::<Rev>()?
1845            .docs(docstring! {
1846                /// Reverses an iterator's direction.
1847                ///
1848                /// Usually, iterators iterate from left to right. After using `rev()`, an
1849                /// iterator will instead iterate from right to left.
1850                ///
1851                /// This is only possible if the iterator has an end, so `rev()` only works on
1852                /// double-ended iterators.
1853                ///
1854                /// # Examples
1855                ///
1856                /// ```rune
1857                /// let a = [1, 2, 3];
1858                ///
1859                /// let iter = a.iter().rev();
1860                ///
1861                /// assert_eq!(iter.next(), Some(3));
1862                /// assert_eq!(iter.next(), Some(2));
1863                /// assert_eq!(iter.next(), Some(1));
1864                ///
1865                /// assert_eq!(iter.next(), None);
1866                /// ```
1867            })?;
1868    }
1869
1870    m.function_meta(range)?;
1871
1872    m.ty::<Empty>()?;
1873    m.function_meta(Empty::next__meta)?;
1874    m.function_meta(Empty::next_back__meta)?;
1875    m.function_meta(Empty::size_hint__meta)?;
1876    m.implement_trait::<Empty>(rune::item!(::std::iter::Iterator))?;
1877    m.implement_trait::<Empty>(rune::item!(::std::iter::DoubleEndedIterator))?;
1878    m.function_meta(empty)?;
1879
1880    m.ty::<Once>()?;
1881    m.function_meta(Once::next__meta)?;
1882    m.function_meta(Once::next_back__meta)?;
1883    m.function_meta(Once::size_hint__meta)?;
1884    m.implement_trait::<Once>(rune::item!(::std::iter::Iterator))?;
1885    m.implement_trait::<Once>(rune::item!(::std::iter::DoubleEndedIterator))?;
1886    m.function_meta(once)?;
1887    Ok(m)
1888}
1889
1890/// Construct an iterator which produces no values.
1891///
1892/// # Examples
1893///
1894/// ```rune
1895/// use std::iter::empty;
1896///
1897/// assert!(empty().next().is_none());
1898/// assert_eq!(empty().collect::<Vec>(), []);
1899/// ```
1900#[rune::function]
1901fn empty() -> Empty {
1902    Empty
1903}
1904
1905#[derive(Any)]
1906#[rune(item = ::std::iter)]
1907struct Empty;
1908
1909impl Empty {
1910    #[rune::function(keep, protocol = NEXT)]
1911    fn next(&mut self) -> Option<Value> {
1912        None
1913    }
1914
1915    #[rune::function(keep, protocol = NEXT_BACK)]
1916    fn next_back(&mut self) -> Option<Value> {
1917        None
1918    }
1919
1920    #[rune::function(keep, protocol = SIZE_HINT)]
1921    fn size_hint(&self) -> (usize, Option<usize>) {
1922        (0, Some(0))
1923    }
1924}
1925
1926/// Construct an iterator which produces a single `value` once.
1927///
1928/// # Examples
1929///
1930/// ```rune
1931/// use std::iter::once;
1932///
1933/// assert!(once(42).next().is_some());
1934/// assert_eq!(once(42).collect::<Vec>(), [42]);
1935/// ```
1936#[rune::function]
1937fn once(value: Value) -> Once {
1938    Once { value: Some(value) }
1939}
1940
1941#[derive(Any)]
1942#[rune(item = ::std::iter)]
1943pub(crate) struct Once {
1944    #[rune(dismantle)]
1945    value: Option<Value>,
1946}
1947
1948impl Once {
1949    #[rune::function(keep, protocol = NEXT)]
1950    fn next(&mut self) -> Option<Value> {
1951        self.value.take()
1952    }
1953
1954    #[rune::function(keep, protocol = NEXT_BACK)]
1955    fn next_back(&mut self) -> Option<Value> {
1956        self.value.take()
1957    }
1958
1959    #[rune::function(keep, protocol = SIZE_HINT)]
1960    fn size_hint(&self) -> (usize, Option<usize>) {
1961        let len = usize::from(self.value.is_some());
1962        (len, Some(len))
1963    }
1964}
1965
1966/// Produce an iterator which starts at the range `start` and ends at the value
1967/// `end` (exclusive).
1968///
1969/// # Examples
1970///
1971/// ```rune
1972/// use std::iter::range;
1973///
1974/// assert!(range(0, 3).next().is_some());
1975/// assert_eq!(range(0, 3).collect::<Vec>(), [0, 1, 2]);
1976/// ```
1977#[rune::function(deprecated = "Use the `<from>..<to>` operator instead")]
1978fn range(start: i64, end: i64) -> RangeIter<i64> {
1979    RangeIter::new(start..end)
1980}
1981
1982/// Fuse the iterator if the expression is `None`.
1983macro_rules! fuse {
1984    ($self:ident . $iter:ident . $($call:tt)+) => {
1985        match $self.$iter {
1986            Some(ref mut iter) => match iter.$($call)+? {
1987                None => {
1988                    $self.$iter = None;
1989                    None
1990                }
1991                item => item,
1992            },
1993            None => None,
1994        }
1995    };
1996}
1997
1998/// Try an iterator method without fusing,
1999/// like an inline `.as_mut().and_then(...)`
2000macro_rules! maybe {
2001    ($self:ident . $iter:ident . $($call:tt)+) => {
2002        match $self.$iter {
2003            Some(ref mut iter) => iter.$($call)+?,
2004            None => None,
2005        }
2006    };
2007}
2008
2009#[derive(Any, Debug)]
2010#[rune(item = ::std::iter)]
2011pub(crate) struct Chain {
2012    #[rune(dismantle)]
2013    a: Option<Value>,
2014    #[rune(dismantle)]
2015    b: Option<Value>,
2016}
2017
2018impl Chain {
2019    #[rune::function(keep, protocol = NEXT)]
2020    #[inline]
2021    fn next(&mut self) -> Result<Option<Value>, VmError> {
2022        Ok(match fuse!(self.a.protocol_next()) {
2023            None => maybe!(self.b.protocol_next()),
2024            item => item,
2025        })
2026    }
2027
2028    #[rune::function(keep, protocol = NEXT_BACK)]
2029    #[inline]
2030    fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2031        Ok(match fuse!(self.b.protocol_next_back()) {
2032            None => maybe!(self.a.protocol_next_back()),
2033            item => item,
2034        })
2035    }
2036
2037    #[rune::function(keep, protocol = SIZE_HINT)]
2038    #[inline]
2039    fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2040        match self {
2041            Self {
2042                a: Some(a),
2043                b: Some(b),
2044            } => {
2045                let (a_lower, a_upper) = a.protocol_size_hint()?;
2046                let (b_lower, b_upper) = b.protocol_size_hint()?;
2047
2048                let lower = a_lower.saturating_add(b_lower);
2049
2050                let upper = match (a_upper, b_upper) {
2051                    (Some(x), Some(y)) => x.checked_add(y),
2052                    _ => None,
2053                };
2054
2055                Ok((lower, upper))
2056            }
2057            Self {
2058                a: Some(a),
2059                b: None,
2060            } => a.protocol_size_hint(),
2061            Self {
2062                a: None,
2063                b: Some(b),
2064            } => b.protocol_size_hint(),
2065            Self { a: None, b: None } => Ok((0, Some(0))),
2066        }
2067    }
2068
2069    #[rune::function(keep, protocol = LEN)]
2070    #[inline]
2071    fn len(&self) -> Result<usize, VmError> {
2072        match self {
2073            Self {
2074                a: Some(a),
2075                b: Some(b),
2076            } => {
2077                let a_len = a.protocol_len()?;
2078                let b_len = b.protocol_len()?;
2079                Ok(a_len.saturating_add(b_len))
2080            }
2081            Self {
2082                a: Some(a),
2083                b: None,
2084            } => a.protocol_len(),
2085            Self {
2086                a: None,
2087                b: Some(b),
2088            } => b.protocol_len(),
2089            Self { a: None, b: None } => Ok(0),
2090        }
2091    }
2092}
2093
2094#[derive(Any, Debug)]
2095#[rune(item = ::std::iter)]
2096pub(crate) struct Enumerate {
2097    #[rune(dismantle)]
2098    iter: Value,
2099    count: usize,
2100}
2101
2102impl Enumerate {
2103    #[rune::function(keep, protocol = NEXT)]
2104    #[inline]
2105    fn next(&mut self) -> Result<Option<(usize, Value)>, VmError> {
2106        if let Some(value) = self.iter.protocol_next()? {
2107            let i = self.count;
2108            self.count += 1;
2109            return Ok(Some((i, value)));
2110        }
2111
2112        Ok(None)
2113    }
2114
2115    #[rune::function(keep, protocol = NEXT_BACK)]
2116    #[inline]
2117    fn next_back(&mut self) -> Result<Option<(usize, Value)>, VmError> {
2118        if let Some(value) = self.iter.protocol_next_back()? {
2119            let len = self.iter.protocol_len()?;
2120            return Ok(Some((self.count + len, value)));
2121        }
2122
2123        Ok(None)
2124    }
2125
2126    #[rune::function(keep, protocol = SIZE_HINT)]
2127    #[inline]
2128    fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2129        self.iter.protocol_size_hint()
2130    }
2131
2132    #[rune::function(keep, protocol = LEN)]
2133    #[inline]
2134    fn len(&self) -> Result<usize, VmError> {
2135        self.iter.protocol_len()
2136    }
2137}
2138
2139#[derive(Any, Debug)]
2140#[rune(item = ::std::iter)]
2141pub(crate) struct Filter {
2142    #[rune(dismantle)]
2143    iter: Value,
2144    #[rune(dismantle)]
2145    f: Function,
2146}
2147
2148impl Filter {
2149    #[rune::function(keep, protocol = NEXT)]
2150    #[inline]
2151    fn next(&mut self) -> Result<Option<Value>, VmError> {
2152        while let Some(value) = self.iter.protocol_next()? {
2153            if self.f.call::<bool>((value.clone(),))? {
2154                return Ok(Some(value));
2155            }
2156        }
2157
2158        Ok(None)
2159    }
2160
2161    #[rune::function(keep, protocol = NEXT_BACK)]
2162    #[inline]
2163    fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2164        while let Some(value) = self.iter.protocol_next_back()? {
2165            if self.f.call::<bool>((value.clone(),))? {
2166                return Ok(Some(value));
2167            }
2168        }
2169
2170        Ok(None)
2171    }
2172
2173    #[rune::function(keep, protocol = SIZE_HINT)]
2174    #[inline]
2175    fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2176        let (_, hi) = self.iter.protocol_size_hint()?;
2177        Ok((0, hi))
2178    }
2179}
2180
2181#[derive(Any, Debug)]
2182#[rune(item = ::std::iter)]
2183pub(crate) struct Map {
2184    #[rune(dismantle)]
2185    iter: Option<Value>,
2186    #[rune(dismantle)]
2187    f: Function,
2188}
2189
2190impl Map {
2191    #[rune::function(keep, protocol = NEXT)]
2192    #[inline]
2193    fn next(&mut self) -> Result<Option<Value>, VmError> {
2194        if let Some(value) = fuse!(self.iter.protocol_next()) {
2195            return Ok(Some(self.f.call::<Value>((value.clone(),))?));
2196        }
2197
2198        Ok(None)
2199    }
2200
2201    #[rune::function(keep, protocol = NEXT_BACK)]
2202    #[inline]
2203    fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2204        if let Some(value) = fuse!(self.iter.protocol_next_back()) {
2205            return Ok(Some(self.f.call::<Value>((value.clone(),))?));
2206        }
2207
2208        Ok(None)
2209    }
2210
2211    #[rune::function(keep, protocol = SIZE_HINT)]
2212    #[inline]
2213    fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2214        let Some(iter) = &self.iter else {
2215            return Ok((0, Some(0)));
2216        };
2217
2218        iter.protocol_size_hint()
2219    }
2220
2221    #[rune::function(keep, protocol = LEN)]
2222    #[inline]
2223    fn len(&self) -> Result<usize, VmError> {
2224        let Some(iter) = &self.iter else {
2225            return Ok(0);
2226        };
2227
2228        iter.protocol_len()
2229    }
2230}
2231
2232#[derive(Any, Debug)]
2233#[rune(item = ::std::iter)]
2234pub(crate) struct FilterMap {
2235    #[rune(dismantle)]
2236    iter: Option<Value>,
2237    #[rune(dismantle)]
2238    f: Function,
2239}
2240
2241impl FilterMap {
2242    #[rune::function(keep, protocol = NEXT)]
2243    #[inline]
2244    fn next(&mut self) -> Result<Option<Value>, VmError> {
2245        while let Some(value) = fuse!(self.iter.protocol_next()) {
2246            if let Some(value) = self.f.call::<Option<Value>>((value.clone(),))? {
2247                return Ok(Some(value));
2248            }
2249        }
2250
2251        Ok(None)
2252    }
2253
2254    #[rune::function(keep, protocol = NEXT_BACK)]
2255    #[inline]
2256    fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2257        while let Some(value) = fuse!(self.iter.protocol_next_back()) {
2258            if let Some(value) = self.f.call::<Option<Value>>((value.clone(),))? {
2259                return Ok(Some(value));
2260            }
2261        }
2262
2263        Ok(None)
2264    }
2265}
2266
2267#[derive(Any, Debug)]
2268#[rune(item = ::std::iter)]
2269pub(crate) struct FlatMap {
2270    #[rune(dismantle)]
2271    map: Map,
2272    #[rune(dismantle)]
2273    frontiter: Option<Value>,
2274    #[rune(dismantle)]
2275    backiter: Option<Value>,
2276}
2277
2278impl FlatMap {
2279    #[rune::function(keep, protocol = NEXT)]
2280    #[inline]
2281    fn next(&mut self) -> Result<Option<Value>, VmError> {
2282        loop {
2283            if let Some(iter) = &mut self.frontiter {
2284                match iter.protocol_next()? {
2285                    None => self.frontiter = None,
2286                    item @ Some(_) => return Ok(item),
2287                }
2288            }
2289
2290            let Some(value) = self.map.next()? else {
2291                return Ok(match &mut self.backiter {
2292                    Some(backiter) => backiter.protocol_next()?,
2293                    None => None,
2294                });
2295            };
2296
2297            self.frontiter = Some(value.protocol_into_iter()?)
2298        }
2299    }
2300
2301    #[rune::function(keep, protocol = NEXT_BACK)]
2302    #[inline]
2303    fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2304        loop {
2305            if let Some(ref mut iter) = self.backiter {
2306                match iter.protocol_next_back()? {
2307                    None => self.backiter = None,
2308                    item @ Some(_) => return Ok(item),
2309                }
2310            }
2311
2312            let Some(value) = self.map.next_back()? else {
2313                return Ok(match &mut self.frontiter {
2314                    Some(frontiter) => frontiter.protocol_next_back()?,
2315                    None => None,
2316                });
2317            };
2318
2319            self.backiter = Some(value.protocol_into_iter()?);
2320        }
2321    }
2322
2323    #[rune::function(keep, protocol = SIZE_HINT)]
2324    #[inline]
2325    fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2326        let (flo, fhi) = match &self.frontiter {
2327            Some(iter) => iter.protocol_size_hint()?,
2328            None => (0, Some(0)),
2329        };
2330
2331        let (blo, bhi) = match &self.backiter {
2332            Some(iter) => iter.protocol_size_hint()?,
2333            None => (0, Some(0)),
2334        };
2335
2336        let lo = flo.saturating_add(blo);
2337
2338        Ok(match (self.map.size_hint()?, fhi, bhi) {
2339            ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
2340            _ => (lo, None),
2341        })
2342    }
2343}
2344
2345#[derive(Any, Debug)]
2346#[rune(item = ::std::iter, dismantle)]
2347pub(crate) struct Peekable {
2348    iter: Value,
2349    peeked: Option<Option<Value>>,
2350}
2351
2352impl Peekable {
2353    #[rune::function(keep, protocol = NEXT)]
2354    #[inline]
2355    fn next(&mut self) -> Result<Option<Value>, VmError> {
2356        Ok(match self.peeked.take() {
2357            Some(v) => v,
2358            None => self.iter.protocol_next()?,
2359        })
2360    }
2361
2362    #[rune::function(keep, protocol = NEXT_BACK)]
2363    #[inline]
2364    fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2365        Ok(match self.peeked.as_mut() {
2366            Some(v @ Some(_)) => self.iter.protocol_next_back()?.or_else(|| v.take()),
2367            Some(None) => None,
2368            None => self.iter.protocol_next_back()?,
2369        })
2370    }
2371
2372    #[rune::function(keep, protocol = SIZE_HINT)]
2373    #[inline]
2374    fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2375        let peek_len = match &self.peeked {
2376            Some(None) => return Ok((0, Some(0))),
2377            Some(Some(_)) => 1,
2378            None => 0,
2379        };
2380
2381        let (lo, hi) = self.iter.protocol_size_hint()?;
2382        let lo = lo.saturating_add(peek_len);
2383
2384        let hi = match hi {
2385            Some(x) => x.checked_add(peek_len),
2386            None => None,
2387        };
2388
2389        Ok((lo, hi))
2390    }
2391
2392    #[rune::function(keep, protocol = LEN)]
2393    #[inline]
2394    fn len(&self) -> Result<usize, VmError> {
2395        let peek_len = match &self.peeked {
2396            Some(None) => return Ok(0),
2397            Some(Some(_)) => 1,
2398            None => 0,
2399        };
2400
2401        let len = self.iter.protocol_len()?;
2402        Ok(len.saturating_add(peek_len))
2403    }
2404
2405    /// Returns a reference to the `next()` value without advancing the iterator.
2406    ///
2407    /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`. But if the
2408    /// iteration is over, `None` is returned.
2409    ///
2410    /// [`next`]: Iterator::next
2411    ///
2412    /// Because `peek()` returns a reference, and many iterators iterate over
2413    /// references, there can be a possibly confusing situation where the return
2414    /// value is a double reference. You can see this effect in the examples below.
2415    ///
2416    /// # Examples
2417    ///
2418    /// Basic usage:
2419    ///
2420    /// ```rune
2421    /// let xs = [1, 2, 3];
2422    ///
2423    /// let iter = xs.iter().peekable();
2424    ///
2425    /// // peek() lets us see into the future
2426    /// assert_eq!(iter.peek(), Some(1));
2427    /// assert_eq!(iter.next(), Some(1));
2428    ///
2429    /// assert_eq!(iter.next(), Some(2));
2430    ///
2431    /// // The iterator does not advance even if we `peek` multiple times
2432    /// assert_eq!(iter.peek(), Some(3));
2433    /// assert_eq!(iter.peek(), Some(3));
2434    ///
2435    /// assert_eq!(iter.next(), Some(3));
2436    ///
2437    /// // After the iterator is finished, so is `peek()`
2438    /// assert_eq!(iter.peek(), None);
2439    /// assert_eq!(iter.next(), None);
2440    /// ```
2441    #[rune::function(keep)]
2442    #[inline]
2443    fn peek(&mut self) -> Result<Option<Value>, VmError> {
2444        if let Some(v) = &self.peeked {
2445            return Ok(v.clone());
2446        }
2447
2448        let value = self.iter.protocol_next()?;
2449        self.peeked = Some(value.clone());
2450        Ok(value)
2451    }
2452}
2453
2454#[derive(Any, Debug)]
2455#[rune(item = ::std::iter)]
2456pub(crate) struct Skip {
2457    #[rune(dismantle)]
2458    iter: Value,
2459    n: usize,
2460}
2461
2462impl Skip {
2463    #[rune::function(keep, protocol = NEXT)]
2464    #[inline]
2465    fn next(&mut self) -> Result<Option<Value>, VmError> {
2466        if self.n > 0 {
2467            let old_n = self.n;
2468            self.n = 0;
2469
2470            for _ in 0..old_n {
2471                match self.iter.protocol_next()? {
2472                    Some(..) => (),
2473                    None => return Ok(None),
2474                }
2475            }
2476        }
2477
2478        self.iter.protocol_next()
2479    }
2480
2481    #[rune::function(keep, protocol = NEXT_BACK)]
2482    #[inline]
2483    fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2484        Ok(if self.len()? > 0 {
2485            self.iter.protocol_next_back()?
2486        } else {
2487            None
2488        })
2489    }
2490
2491    #[rune::function(keep, protocol = SIZE_HINT)]
2492    #[inline]
2493    fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2494        let (lower, upper) = self.iter.protocol_size_hint()?;
2495        let lower = lower.saturating_sub(self.n);
2496        let upper = upper.map(|x| x.saturating_sub(self.n));
2497        Ok((lower, upper))
2498    }
2499
2500    #[rune::function(keep, protocol = LEN)]
2501    #[inline]
2502    fn len(&self) -> Result<usize, VmError> {
2503        let len = self.iter.protocol_len()?;
2504        Ok(len.saturating_sub(self.n))
2505    }
2506}
2507
2508#[derive(Any, Debug)]
2509#[rune(item = ::std::iter)]
2510pub(crate) struct Take {
2511    #[rune(dismantle)]
2512    iter: Value,
2513    n: usize,
2514}
2515
2516impl Take {
2517    #[rune::function(keep, protocol = NEXT)]
2518    #[inline]
2519    fn next(&mut self) -> Result<Option<Value>, VmError> {
2520        if self.n == 0 {
2521            return Ok(None);
2522        }
2523
2524        self.n -= 1;
2525        self.iter.protocol_next()
2526    }
2527
2528    #[rune::function(keep, protocol = NEXT_BACK)]
2529    #[inline]
2530    fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2531        if self.n == 0 {
2532            Ok(None)
2533        } else {
2534            let n = self.n;
2535            self.n -= 1;
2536            let len = self.iter.protocol_len()?;
2537            self.iter.protocol_nth_back(len.saturating_sub(n))
2538        }
2539    }
2540
2541    #[rune::function(keep, protocol = SIZE_HINT)]
2542    #[inline]
2543    fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2544        if self.n == 0 {
2545            return Ok((0, Some(0)));
2546        }
2547
2548        let (lower, upper) = self.iter.protocol_size_hint()?;
2549
2550        let lower = lower.min(self.n);
2551
2552        let upper = match upper {
2553            Some(x) if x < self.n => Some(x),
2554            _ => Some(self.n),
2555        };
2556
2557        Ok((lower, upper))
2558    }
2559
2560    #[rune::function(keep, protocol = LEN)]
2561    #[inline]
2562    fn len(&self) -> Result<usize, VmError> {
2563        if self.n == 0 {
2564            return Ok(0);
2565        }
2566
2567        let len = self.iter.protocol_len()?;
2568        Ok(len.min(self.n))
2569    }
2570}
2571
2572#[derive(Any, Debug)]
2573#[rune(item = ::std::iter)]
2574pub(crate) struct Rev {
2575    #[rune(dismantle)]
2576    value: Value,
2577}
2578
2579impl Rev {
2580    #[rune::function(keep, protocol = NEXT)]
2581    #[inline]
2582    fn next(&mut self) -> Result<Option<Value>, VmError> {
2583        self.value.protocol_next_back()
2584    }
2585
2586    #[rune::function(keep, protocol = NEXT_BACK)]
2587    #[inline]
2588    fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2589        self.value.protocol_next()
2590    }
2591
2592    #[rune::function(keep, protocol = SIZE_HINT)]
2593    #[inline]
2594    fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2595        self.value.protocol_size_hint()
2596    }
2597
2598    #[rune::function(keep, protocol = LEN)]
2599    #[inline]
2600    fn len(&self) -> Result<usize, VmError> {
2601        self.value.protocol_len()
2602    }
2603}
2604
2605pub(crate) trait CheckedOps: Sized {
2606    const ONE: Self;
2607    const ZERO: Self;
2608
2609    fn checked_add(self, value: Self) -> Option<Self>;
2610    fn checked_mul(self, value: Self) -> Option<Self>;
2611}
2612
2613impl CheckedOps for i64 {
2614    const ONE: Self = 1;
2615    const ZERO: Self = 0;
2616
2617    #[inline]
2618    fn checked_add(self, value: Self) -> Option<Self> {
2619        i64::checked_add(self, value)
2620    }
2621
2622    #[inline]
2623    fn checked_mul(self, value: Self) -> Option<Self> {
2624        i64::checked_mul(self, value)
2625    }
2626}
2627
2628impl CheckedOps for u64 {
2629    const ONE: Self = 1;
2630    const ZERO: Self = 0;
2631
2632    #[inline]
2633    fn checked_add(self, value: Self) -> Option<Self> {
2634        u64::checked_add(self, value)
2635    }
2636
2637    #[inline]
2638    fn checked_mul(self, value: Self) -> Option<Self> {
2639        u64::checked_mul(self, value)
2640    }
2641}
2642
2643impl CheckedOps for f64 {
2644    const ONE: Self = 1.0;
2645    const ZERO: Self = 0.0;
2646
2647    #[inline]
2648    fn checked_add(self, value: Self) -> Option<Self> {
2649        Some(self + value)
2650    }
2651
2652    #[inline]
2653    fn checked_mul(self, value: Self) -> Option<Self> {
2654        Some(self * value)
2655    }
2656}
2657
2658/// A peeked value is held one level deeper than the derive can reach, so this
2659/// one hands over what it holds by hand while the rest of the adapters mark the
2660/// fields which hold values.
2661impl Dismantle for Peekable {
2662    fn dismantle(&mut self, out: &mut Handover<'_>) {
2663        out.consume(&mut self.iter);
2664        out.consume_all(self.peeked.iter_mut().flatten());
2665    }
2666}