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` 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 ///
950 /// # Examples
951 ///
952 /// Basic usage:
953 ///
954 /// ```rune
955 /// let a = [1, 2, 3];
956 ///
957 /// assert_eq!(a.iter().find(|x| x == 2), Some(2));
958 ///
959 /// assert_eq!(a.iter().find(|x| x == 5), None);
960 /// ```
961 ///
962 /// Stopping at the first `true`:
963 ///
964 /// ```rune
965 /// let a = [1, 2, 3];
966 ///
967 /// let iter = a.iter();
968 ///
969 /// assert_eq!(iter.find(|x| x == 2), Some(2));
970 ///
971 /// // we can still use `iter`, as there are more elements.
972 /// assert_eq!(iter.next(), Some(3));
973 /// ```
974 ///
975 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
976 })?;
977
978 t.function("any")?
979 .argument_types::<(Value, Function)>()?
980 .argument_names(["self", "f"])?
981 .return_type::<bool>()?
982 .docs(docstring! {
983 /// Tests if any element of the iterator matches a predicate.
984 ///
985 /// `any()` takes a closure that returns `true` or `false`. It applies this
986 /// closure to each element of the iterator, and if any of them return `true`,
987 /// then so does `any()`. If they all return `false`, it returns `false`.
988 ///
989 /// `any()` is short-circuiting; in other words, it will stop processing as soon
990 /// as it finds a `true`, given that no matter what else happens, the result
991 /// will also be `true`.
992 ///
993 /// An empty iterator returns `false`.
994 ///
995 /// # Examples
996 ///
997 /// Basic usage:
998 ///
999 /// ```rune
1000 /// let a = [1, 2, 3];
1001 ///
1002 /// assert!(a.iter().any(|x| x > 0));
1003 ///
1004 /// assert!(!a.iter().any(|x| x > 5));
1005 /// ```
1006 ///
1007 /// Stopping at the first `true`:
1008 ///
1009 /// ```rune
1010 /// let a = [1, 2, 3];
1011 ///
1012 /// let iter = a.iter();
1013 ///
1014 /// assert!(iter.any(|x| x != 2));
1015 ///
1016 /// // we can still use `iter`, as there are more elements.
1017 /// assert_eq!(iter.next(), Some(2));
1018 /// ```
1019 })?;
1020
1021 t.function("all")?
1022 .argument_types::<(Value, Function)>()?
1023 .argument_names(["self", "f"])?
1024 .return_type::<bool>()?
1025 .docs(docstring! {
1026 /// Tests if every element of the iterator matches a predicate.
1027 ///
1028 /// `all()` takes a closure that returns `true` or `false`. It applies this
1029 /// closure to each element of the iterator, and if they all return `true`, then
1030 /// so does `all()`. If any of them return `false`, it returns `false`.
1031 ///
1032 /// `all()` is short-circuiting; in other words, it will stop processing as soon
1033 /// as it finds a `false`, given that no matter what else happens, the result
1034 /// will also be `false`.
1035 ///
1036 /// An empty iterator returns `true`.
1037 ///
1038 /// # Examples
1039 ///
1040 /// Basic usage:
1041 ///
1042 /// ```rune
1043 /// let a = [1, 2, 3];
1044 ///
1045 /// assert!(a.iter().all(|x| x > 0));
1046 ///
1047 /// assert!(!a.iter().all(|x| x > 2));
1048 /// ```
1049 ///
1050 /// Stopping at the first `false`:
1051 ///
1052 /// ```rune
1053 /// let a = [1, 2, 3];
1054 ///
1055 /// let iter = a.iter();
1056 ///
1057 /// assert!(!iter.all(|x| x != 2));
1058 ///
1059 /// // we can still use `iter`, as there are more elements.
1060 /// assert_eq!(iter.next(), Some(3));
1061 /// ```
1062 })?;
1063
1064 t.function("chain")?
1065 .argument_types::<(Value, Value)>()?
1066 .argument_names(["self", "other"])?
1067 .return_type::<Chain>()?
1068 .docs(docstring! {
1069 /// Takes two iterators and creates a new iterator over both in sequence.
1070 ///
1071 /// `chain()` will return a new iterator which will first iterate over
1072 /// values from the first iterator and then over values from the second
1073 /// iterator.
1074 ///
1075 /// In other words, it links two iterators together, in a chain. 🔗
1076 ///
1077 /// [`once`] is commonly used to adapt a single value into a chain of other
1078 /// kinds of iteration.
1079 ///
1080 /// # Examples
1081 ///
1082 /// Basic usage:
1083 ///
1084 /// ```rune
1085 /// let a1 = [1, 2, 3];
1086 /// let a2 = [4, 5, 6];
1087 ///
1088 /// let iter = a1.iter().chain(a2.iter());
1089 ///
1090 /// assert_eq!(iter.next(), Some(1));
1091 /// assert_eq!(iter.next(), Some(2));
1092 /// assert_eq!(iter.next(), Some(3));
1093 /// assert_eq!(iter.next(), Some(4));
1094 /// assert_eq!(iter.next(), Some(5));
1095 /// assert_eq!(iter.next(), Some(6));
1096 /// assert_eq!(iter.next(), None);
1097 /// ```
1098 ///
1099 /// Since the argument to `chain()` uses `INTO_ITER`, we can pass anything
1100 /// that can be converted into an [`Iterator`], not just an [`Iterator`] itself.
1101 /// For example, slices (`[T]`) implement `INTO_ITER`, and so can be passed to
1102 /// `chain()` directly:
1103 ///
1104 /// ```rune
1105 /// let s1 = [1, 2, 3];
1106 /// let s2 = [4, 5, 6];
1107 ///
1108 /// let iter = s1.iter().chain(s2);
1109 ///
1110 /// assert_eq!(iter.next(), Some(1));
1111 /// assert_eq!(iter.next(), Some(2));
1112 /// assert_eq!(iter.next(), Some(3));
1113 /// assert_eq!(iter.next(), Some(4));
1114 /// assert_eq!(iter.next(), Some(5));
1115 /// assert_eq!(iter.next(), Some(6));
1116 /// assert_eq!(iter.next(), None);
1117 /// ```
1118 })?;
1119
1120 t.function("enumerate")?
1121 .argument_types::<(Value,)>()?
1122 .argument_names(["self"])?
1123 .return_type::<Enumerate>()?
1124 .docs(docstring! {
1125 /// Creates an iterator which gives the current iteration count as well as
1126 /// the next value.
1127 ///
1128 /// The iterator returned yields pairs `(i, val)`, where `i` is the current
1129 /// index of iteration and `val` is the value returned by the iterator.
1130 ///
1131 /// `enumerate()` keeps its count as a usize. If you want to count by a
1132 /// different sized integer, the zip function provides similar
1133 /// functionality.
1134 ///
1135 /// # Examples
1136 ///
1137 /// ```rune
1138 /// let a = ['a', 'b', 'c'];
1139 ///
1140 /// let iter = a.iter().enumerate();
1141 ///
1142 /// assert_eq!(iter.next(), Some((0u64, 'a')));
1143 /// assert_eq!(iter.next(), Some((1u64, 'b')));
1144 /// assert_eq!(iter.next(), Some((2u64, 'c')));
1145 /// assert_eq!(iter.next(), None);
1146 /// ```
1147 })?;
1148
1149 t.function("filter")?
1150 .argument_types::<(Value, Function)>()?
1151 .argument_names(["self", "filter"])?
1152 .return_type::<Filter>()?
1153 .docs(docstring! {
1154 /// Creates an iterator which uses a closure to determine if an element
1155 /// should be yielded.
1156 ///
1157 /// Given an element the closure must return `true` or `false`. The returned
1158 /// iterator will yield only the elements for which the closure returns
1159 /// `true`.
1160 ///
1161 /// ```rune
1162 /// let a = [0, 1, 2];
1163 ///
1164 /// let iter = a.iter().filter(|x| x.is_positive());
1165 ///
1166 /// assert_eq!(iter.next(), Some(1));
1167 /// assert_eq!(iter.next(), Some(2));
1168 /// assert_eq!(iter.next(), None);
1169 /// ```
1170 })?;
1171
1172 t.function("map")?
1173 .argument_types::<(Value, Function)>()?
1174 .argument_names(["self", "f"])?
1175 .return_type::<Map>()?
1176 .docs(docstring! {
1177 /// Takes a closure and creates an iterator which calls that closure on each
1178 /// element.
1179 ///
1180 /// `map()` transforms one iterator into another. It produces a new iterator
1181 /// which calls this closure on each element of the original iterator.
1182 ///
1183 /// If you are good at thinking in types, you can think of `map()` like
1184 /// this: If you have an iterator that gives you elements of some type `A`,
1185 /// and you want an iterator of some other type `B`, you can use `map()`,
1186 /// passing a closure that takes an `A` and returns a `B`.
1187 ///
1188 /// `map()` is conceptually similar to a `for` loop. However, as `map()` is
1189 /// lazy, it is best used when you're already working with other iterators.
1190 /// If you're doing some sort of looping for a side effect, it's considered
1191 /// more idiomatic to use `for` than `map()`.
1192 ///
1193 /// # Examples
1194 ///
1195 /// Basic usage:
1196 ///
1197 /// ```rune
1198 /// let a = [1, 2, 3];
1199 ///
1200 /// let iter = a.iter().map(|x| 2 * x);
1201 ///
1202 /// assert_eq!(iter.next(), Some(2));
1203 /// assert_eq!(iter.next(), Some(4));
1204 /// assert_eq!(iter.next(), Some(6));
1205 /// assert_eq!(iter.next(), None);
1206 /// ```
1207 ///
1208 /// If you're doing some sort of side effect, prefer `for` to `map()`:
1209 ///
1210 /// ```rune
1211 /// // don't do this:
1212 /// (0..5).iter().map(|x| println!("{}", x));
1213 ///
1214 /// // it won't even execute, as it is lazy. Rust will warn you about this.
1215 ///
1216 /// // Instead, use for:
1217 /// for x in 0..5 {
1218 /// println!("{}", x);
1219 /// }
1220 /// ```
1221 })?;
1222
1223 t.function("filter_map")?
1224 .argument_types::<(Value, Function)>()?
1225 .argument_names(["self", "f"])?
1226 .return_type::<FilterMap>()?
1227 .docs(docstring! {
1228 /// Creates an iterator that both filters and maps.
1229 ///
1230 /// The returned iterator yields only the `value`s for which the supplied
1231 /// closure returns `Some(value)`.
1232 ///
1233 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
1234 /// concise. The example below shows how a `map().filter().map()` can be
1235 /// shortened to a single call to `filter_map`.
1236 ///
1237 /// [`filter`]: Iterator::filter
1238 /// [`map`]: Iterator::map
1239 ///
1240 /// # Examples
1241 ///
1242 /// Basic usage:
1243 ///
1244 /// ```rune
1245 /// let a = ["1", "two", "NaN", "four", "5"];
1246 ///
1247 /// let iter = a.iter().filter_map(|s| s.parse::<i64>().ok());
1248 ///
1249 /// assert_eq!(iter.next(), Some(1));
1250 /// assert_eq!(iter.next(), Some(5));
1251 /// assert_eq!(iter.next(), None);
1252 /// ```
1253 ///
1254 /// Here's the same example, but with [`filter`] and [`map`]:
1255 ///
1256 /// ```rune
1257 /// let a = ["1", "two", "NaN", "four", "5"];
1258 /// let iter = a.iter().map(|s| s.parse::<i64>()).filter(|s| s.is_ok()).map(|s| s.unwrap());
1259 /// assert_eq!(iter.next(), Some(1));
1260 /// assert_eq!(iter.next(), Some(5));
1261 /// assert_eq!(iter.next(), None);
1262 /// ```
1263 })?;
1264
1265 t.function("flat_map")?
1266 .argument_types::<(Value, Function)>()?
1267 .argument_names(["self", "f"])?
1268 .return_type::<FlatMap>()?
1269 .docs(docstring! {
1270 /// Creates an iterator that works like map, but flattens nested
1271 /// structure.
1272 ///
1273 /// The [`map`] adapter is very useful, but only when the
1274 /// closure argument produces values. If it produces an iterator
1275 /// instead, there's an extra layer of indirection. `flat_map()`
1276 /// will remove this extra layer on its own.
1277 ///
1278 /// You can think of `flat_map(f)` as the semantic equivalent of
1279 /// [`map`]ping, and then `flatten`ing as in
1280 /// `map(f).flatten()`.
1281 ///
1282 /// Another way of thinking about `flat_map()`: [`map`]'s
1283 /// closure returns one item for each element, and
1284 /// `flat_map()`'s closure returns an iterator for each element.
1285 ///
1286 /// [`map`]: Iterator::map
1287 ///
1288 /// # Examples
1289 ///
1290 /// Basic usage:
1291 ///
1292 /// ```rune
1293 /// let words = ["alpha", "beta", "gamma"];
1294 ///
1295 /// // chars() returns an iterator
1296 /// let merged = words.iter().flat_map(|s| s.chars()).collect::<String>();
1297 /// assert_eq!(merged, "alphabetagamma");
1298 /// ```
1299 })?;
1300
1301 t.function("peekable")?
1302 .argument_types::<(Value,)>()?
1303 .argument_names(["self"])?
1304 .return_type::<Peekable>()?
1305 .docs(docstring! {
1306 /// Creates an iterator which can use the [`peek`] method to
1307 /// look at the next element of the iterator without consuming
1308 /// it. See their documentation for more information.
1309 ///
1310 /// Note that the underlying iterator is still advanced when
1311 /// [`peek`] are called for the first time: In order to retrieve
1312 /// the next element, [`next`] is called on the underlying
1313 /// iterator, hence any side effects (i.e. anything other than
1314 /// fetching the next value) of the [`next`] method will occur.
1315 ///
1316 /// # Examples
1317 ///
1318 /// Basic usage:
1319 ///
1320 /// ```rune
1321 /// let xs = [1, 2, 3];
1322 ///
1323 /// let iter = xs.iter().peekable();
1324 ///
1325 /// // peek() lets us see into the future
1326 /// assert_eq!(iter.peek(), Some(1));
1327 /// assert_eq!(iter.next(), Some(1));
1328 ///
1329 /// assert_eq!(iter.next(), Some(2));
1330 ///
1331 /// // we can peek() multiple times, the iterator won't advance
1332 /// assert_eq!(iter.peek(), Some(3));
1333 /// assert_eq!(iter.peek(), Some(3));
1334 ///
1335 /// assert_eq!(iter.next(), Some(3));
1336 ///
1337 /// // after the iterator is finished, so is peek()
1338 /// assert_eq!(iter.peek(), None);
1339 /// assert_eq!(iter.next(), None);
1340 /// ```
1341 ///
1342 /// [`peek`]: Peekable::peek
1343 /// [`next`]: Iterator::next
1344 })?;
1345
1346 t.function("skip")?
1347 .argument_types::<(Value, usize)>()?
1348 .argument_names(["self", "n"])?
1349 .return_type::<Skip>()?
1350 .docs(docstring! {
1351 /// Creates an iterator that skips the first `n` elements.
1352 ///
1353 /// `skip(n)` skips elements until `n` elements are skipped or
1354 /// the end of the iterator is reached (whichever happens
1355 /// first). After that, all the remaining elements are yielded.
1356 /// In particular, if the original iterator is too short, then
1357 /// the returned iterator is empty.
1358 ///
1359 /// # Examples
1360 ///
1361 /// Basic usage:
1362 ///
1363 /// ```rune
1364 /// let a = [1, 2, 3];
1365 ///
1366 /// let iter = a.iter().skip(2);
1367 ///
1368 /// assert_eq!(iter.next(), Some(3));
1369 /// assert_eq!(iter.next(), None);
1370 /// ```
1371 })?;
1372
1373 t.function("take")?
1374 .argument_types::<(Value, usize)>()?
1375 .argument_names(["self", "n"])?
1376 .return_type::<Take>()?
1377 .docs(docstring! {
1378 /// Creates an iterator that yields the first `n` elements, or
1379 /// fewer if the underlying iterator ends sooner.
1380 ///
1381 /// `take(n)` yields elements until `n` elements are yielded or
1382 /// the end of the iterator is reached (whichever happens
1383 /// first). The returned iterator is a prefix of length `n` if
1384 /// the original iterator contains at least `n` elements,
1385 /// otherwise it contains all of the (fewer than `n`) elements
1386 /// of the original iterator.
1387 ///
1388 /// # Examples
1389 ///
1390 /// Basic usage:
1391 ///
1392 /// ```rune
1393 /// let a = [1, 2, 3];
1394 ///
1395 /// let iter = a.iter().take(2);
1396 ///
1397 /// assert_eq!(iter.next(), Some(1));
1398 /// assert_eq!(iter.next(), Some(2));
1399 /// assert_eq!(iter.next(), None);
1400 /// ```
1401 ///
1402 /// `take()` is often used with an infinite iterator, to make it
1403 /// finite:
1404 ///
1405 /// ```rune
1406 /// let iter = (0..).iter().take(3);
1407 ///
1408 /// assert_eq!(iter.next(), Some(0));
1409 /// assert_eq!(iter.next(), Some(1));
1410 /// assert_eq!(iter.next(), Some(2));
1411 /// assert_eq!(iter.next(), None);
1412 /// ```
1413 ///
1414 /// If less than `n` elements are available, `take` will limit
1415 /// itself to the size of the underlying iterator:
1416 ///
1417 /// ```rune
1418 /// let v = [1, 2];
1419 /// let iter = v.iter().take(5);
1420 /// assert_eq!(iter.next(), Some(1));
1421 /// assert_eq!(iter.next(), Some(2));
1422 /// assert_eq!(iter.next(), None);
1423 /// ```
1424 })?;
1425
1426 macro_rules! sum_ops {
1427 ($ty:ty) => {
1428 t.function(Params::new("sum", [<$ty>::HASH]))?
1429 .argument_types::<(Value,)>()?
1430 .argument_names(["self"])?
1431 .return_type::<$ty>()?
1432 .docs(docstring! {
1433 /// Sums the elements of an iterator.
1434 ///
1435 /// Takes each element, adds them together, and returns
1436 /// the result.
1437 ///
1438 /// An empty iterator returns the zero value of the
1439 /// type.
1440 ///
1441 /// `sum()` can be used to sum numerical built-in types,
1442 /// such as [`i64`], `float` and [`u64`]. The first element
1443 /// returned by the iterator determines the type being
1444 /// summed.
1445 ///
1446 /// # Panics
1447 ///
1448 /// When calling `sum()` and a primitive integer type is
1449 /// being returned, this method will panic if the
1450 /// computation overflows.
1451 ///
1452 /// # Examples
1453 ///
1454 /// Basic usage:
1455 ///
1456 /// ```rune
1457 #[doc = concat!(" let a = [1", stringify!($ty), ", 2", stringify!($ty), ", 3", stringify!($ty), "];")]
1458 #[doc = concat!(" let sum = a.iter().sum::<", stringify!($ty), ">();")]
1459 ///
1460 #[doc = concat!(" assert_eq!(sum, 6", stringify!($ty), ");")]
1461 /// ```
1462 })?;
1463 };
1464 }
1465
1466 sum_ops!(u64);
1467 sum_ops!(i64);
1468 sum_ops!(f64);
1469
1470 macro_rules! integer_product_ops {
1471 ($ty:ty) => {
1472 t.function(Params::new("product", [<$ty>::HASH]))?
1473 .argument_types::<(Value,)>()?
1474 .argument_names(["self"])?
1475 .return_type::<$ty>()?
1476 .docs(docstring! {
1477 /// Iterates over the entire iterator, multiplying all
1478 /// the elements
1479 ///
1480 /// An empty iterator returns the one value of the type.
1481 ///
1482 /// `sum()` can be used to sum numerical built-in types,
1483 /// such as [`i64`], [`f64`] and [`u64`]. The first element
1484 /// returned by the iterator determines the type being
1485 /// multiplied.
1486 ///
1487 /// # Panics
1488 ///
1489 /// When calling `product()` and a primitive integer
1490 /// type is being returned, method will panic if the
1491 /// computation overflows.
1492 ///
1493 /// # Examples
1494 ///
1495 /// ```rune
1496 /// fn factorial(n) {
1497 #[doc = concat!(" (1", stringify!($ty), "..=n).iter().product::<", stringify!($ty), ">()")]
1498 /// }
1499 ///
1500 #[doc = concat!(" assert_eq!(factorial(0", stringify!($ty), "), 1", stringify!($ty), ");")]
1501 #[doc = concat!(" assert_eq!(factorial(1", stringify!($ty), "), 1", stringify!($ty), ");")]
1502 #[doc = concat!(" assert_eq!(factorial(5", stringify!($ty), "), 120", stringify!($ty), ");")]
1503 /// ```
1504 })?;
1505 };
1506 }
1507
1508 t.function(Params::new("collect", [Vec::HASH]))?
1509 .argument_types::<(Value,)>()?
1510 .argument_names(["self"])?
1511 .return_type::<Vec>()?
1512 .docs(docstring! {
1513 /// Collect the iterator as a [`Vec`].
1514 ///
1515 /// # Examples
1516 ///
1517 /// ```rune
1518 /// use std::iter::range;
1519 ///
1520 /// assert_eq!((0..3).iter().collect::<Vec>(), [0, 1, 2]);
1521 /// ```
1522 })?;
1523
1524 t.function(Params::new("collect", [VecDeque::HASH]))?
1525 .argument_types::<(Value,)>()?
1526 .argument_names(["self"])?
1527 .return_type::<VecDeque>()?
1528 .docs(docstring! {
1529 /// Collect the iterator as a [`VecDeque`][std::collections::vec_deque::VecDeque].
1530 ///
1531 /// # Examples
1532 ///
1533 /// ```rune
1534 /// use std::collections::VecDeque;
1535 ///
1536 /// assert_eq!((0..3).iter().collect::<VecDeque>(), VecDeque::from::<Vec>([0, 1, 2]));
1537 /// ```
1538 })?;
1539
1540 t.function(Params::new("collect", [HashSet::HASH]))?
1541 .argument_types::<(Value,)>()?
1542 .argument_names(["self"])?
1543 .return_type::<HashSet>()?
1544 .docs(docstring! {
1545 /// Collect the iterator as a [`HashSet`][std::collections::hash_set::HashSet].
1546 ///
1547 /// # Examples
1548 ///
1549 /// ```rune
1550 /// use std::collections::HashSet;
1551 ///
1552 /// let a = (0..3).iter().collect::<HashSet>();
1553 /// let b = HashSet::from_iter([0, 1, 2]);
1554 ///
1555 /// assert_eq!(a, b);
1556 /// ```
1557 })?;
1558
1559 t.function(Params::new("collect", [HashMap::HASH]))?
1560 .argument_types::<(Value,)>()?
1561 .argument_names(["self"])?
1562 .return_type::<HashMap>()?
1563 .docs(docstring! {
1564 /// Collect the iterator as a [`HashMap`][std::collections::hash_map::HashMap].
1565 ///
1566 /// # Examples
1567 ///
1568 /// ```rune
1569 /// use std::collections::HashMap;
1570 ///
1571 /// let actual = (0..3).iter().map(|n| (n, n.to_string())).collect::<HashMap>();
1572 ///
1573 /// let expected = HashMap::from_iter([
1574 /// (0, "0"),
1575 /// (1, "1"),
1576 /// (2, "2"),
1577 /// ]);
1578 ///
1579 /// assert_eq!(actual, expected);
1580 /// ```
1581 })?;
1582
1583 t.function(Params::new("collect", [Object::HASH]))?
1584 .argument_types::<(Value,)>()?
1585 .argument_names(["self"])?
1586 .return_type::<HashMap>()?
1587 .docs(docstring! {
1588 /// Collect the iterator as an [`Object`].
1589 ///
1590 /// # Examples
1591 ///
1592 /// ```rune
1593 /// assert_eq!([("first", 1), ("second", 2)].iter().collect::<Object>(), #{first: 1, second: 2});
1594 /// ```
1595 })?;
1596
1597 t.function(Params::new("collect", [OwnedTuple::HASH]))?
1598 .argument_types::<(Value,)>()?
1599 .argument_names(["self"])?
1600 .return_type::<OwnedTuple>()?
1601 .docs(docstring! {
1602 /// Collect the iterator as a [`Tuple`].
1603 ///
1604 /// # Examples
1605 ///
1606 /// ```rune
1607 /// assert_eq!((0..3).iter().collect::<Tuple>(), (0, 1, 2));
1608 /// ```
1609 })?;
1610
1611 t.function(Params::new("collect", [String::HASH]))?
1612 .argument_types::<(Value,)>()?
1613 .argument_names(["self"])?
1614 .return_type::<String>()?
1615 .docs(docstring! {
1616 /// Collect the iterator as a [`String`].
1617 ///
1618 /// # Examples
1619 ///
1620 /// ```rune
1621 /// assert_eq!(["first", "second"].iter().collect::<String>(), "firstsecond");
1622 /// ```
1623 })?;
1624
1625 macro_rules! float_product_ops {
1626 ($ty:ty) => {
1627 t.function(Params::new("product", [<$ty>::HASH]))?
1628 .argument_types::<(Value,)>()?
1629 .argument_names(["self"])?
1630 .return_type::<$ty>()?
1631 .docs(docstring! {
1632 /// Iterates over the entire iterator, multiplying all
1633 /// the elements
1634 ///
1635 /// An empty iterator returns the one value of the type.
1636 ///
1637 /// `sum()` can be used to sum numerical built-in types,
1638 /// such as [`i64`], [`f64`] and [`u64`]. The first element
1639 /// returned by the iterator determines the type being
1640 /// multiplied.
1641 ///
1642 /// # Panics
1643 ///
1644 /// When calling `product()` and a primitive integer
1645 /// type is being returned, method will panic if the
1646 /// computation overflows.
1647 ///
1648 /// # Examples
1649 ///
1650 /// ```rune
1651 /// fn factorial(n) {
1652 #[doc = concat!(" (1..=n).iter().map(|n| n as ", stringify!($ty), ").product::<", stringify!($ty), ">()")]
1653 /// }
1654 ///
1655 #[doc = concat!(" assert_eq!(factorial(0), 1", stringify!($ty), ");")]
1656 #[doc = concat!(" assert_eq!(factorial(1), 1", stringify!($ty), ");")]
1657 #[doc = concat!(" assert_eq!(factorial(5), 120", stringify!($ty), ");")]
1658 /// ```
1659 })?;
1660 };
1661 }
1662
1663 integer_product_ops!(u64);
1664 integer_product_ops!(i64);
1665 float_product_ops!(f64);
1666 }
1667
1668 {
1669 let mut t = m.define_trait(["DoubleEndedIterator"])?;
1670
1671 t.docs(docstring! {
1672 /// An iterator able to yield elements from both ends.
1673 ///
1674 /// Something that implements [`DoubleEndedIterator`] has one extra
1675 /// capability over something that implements [`Iterator`]: the
1676 /// ability to also take `Item`s from the back, as well as the
1677 /// front.
1678 ///
1679 /// It is important to note that both back and forth work on the
1680 /// same range, and do not cross: iteration is over when they meet
1681 /// in the middle.
1682 ///
1683 /// In a similar fashion to the [`Iterator`] protocol, once a
1684 /// [`DoubleEndedIterator`] returns [`None`] from a [`next_back()`],
1685 /// calling it again may or may not ever return [`Some`] again.
1686 /// [`next()`] and [`next_back()`] are interchangeable for this
1687 /// purpose.
1688 ///
1689 /// [`next_back()`]: DoubleEndedIterator::next_back
1690 /// [`next()`]: Iterator::next
1691 ///
1692 /// # Examples
1693 ///
1694 /// Basic usage:
1695 ///
1696 /// ```
1697 /// let numbers = [1, 2, 3, 4, 5, 6];
1698 ///
1699 /// let iter = numbers.iter();
1700 ///
1701 /// assert_eq!(Some(1), iter.next());
1702 /// assert_eq!(Some(6), iter.next_back());
1703 /// assert_eq!(Some(5), iter.next_back());
1704 /// assert_eq!(Some(2), iter.next());
1705 /// assert_eq!(Some(3), iter.next());
1706 /// assert_eq!(Some(4), iter.next());
1707 /// assert_eq!(None, iter.next());
1708 /// assert_eq!(None, iter.next_back());
1709 /// ```
1710 })?;
1711
1712 t.handler(|cx| {
1713 let next_back = cx.find(&Protocol::NEXT_BACK)?;
1714
1715 cx.find_or_define(&Protocol::NTH_BACK, {
1716 let next_back = next_back.clone();
1717
1718 move |iterator: Value, mut n: usize| -> Result<Option<Value>, VmError> {
1719 loop {
1720 budget::permit()?;
1721
1722 let mut memory = [iterator.clone()];
1723 next_back.call(&mut memory, Address::ZERO, 1, Output::keep(0))?;
1724 let [value] = memory;
1725
1726 let Some(value) = Option::<Value>::from_value(value)? else {
1727 break Ok(None);
1728 };
1729
1730 if n == 0 {
1731 break Ok(Some(value));
1732 }
1733
1734 n -= 1;
1735 }
1736 }
1737 })?;
1738
1739 cx.raw_function("rev", |stack, addr, len, out| {
1740 let [value] = stack.slice_at(addr, len)? else {
1741 return Err(VmError::new(VmErrorKind::BadArgumentCount {
1742 actual: len,
1743 expected: 1,
1744 }));
1745 };
1746
1747 let rev = Rev {
1748 value: value.clone(),
1749 };
1750
1751 stack.store(out, || rune::to_value(rev))?;
1752 Ok(())
1753 })?;
1754
1755 Ok(())
1756 })?;
1757
1758 t.function("next_back")?
1759 .argument_types::<(Value,)>()?
1760 .argument_names(["self"])?
1761 .return_type::<Option<Value>>()?
1762 .docs(docstring! {
1763 /// Removes and returns an element from the end of the iterator.
1764 ///
1765 /// Returns [`None`] when there are no more elements.
1766 ///
1767 /// # Examples
1768 ///
1769 /// Basic usage:
1770 ///
1771 /// ```rune
1772 /// let numbers = [1, 2, 3, 4, 5, 6];
1773 ///
1774 /// let iter = numbers.iter();
1775 ///
1776 /// assert_eq!(Some(1), iter.next());
1777 /// assert_eq!(Some(6), iter.next_back());
1778 /// assert_eq!(Some(5), iter.next_back());
1779 /// assert_eq!(Some(2), iter.next());
1780 /// assert_eq!(Some(3), iter.next());
1781 /// assert_eq!(Some(4), iter.next());
1782 /// assert_eq!(None, iter.next());
1783 /// assert_eq!(None, iter.next_back());
1784 /// ```
1785 })?;
1786
1787 t.function("nth_back")?
1788 .argument_types::<(Value, usize)>()?
1789 .argument_names(["self", "n"])?
1790 .return_type::<Option<Value>>()?
1791 .docs(docstring! {
1792 /// Returns the `n`th element from the end of the iterator.
1793 ///
1794 /// This is essentially the reversed version of
1795 /// [`Iterator::nth()`]. Although like most indexing operations,
1796 /// the count starts from zero, so `nth_back(0)` returns the
1797 /// first value from the end, `nth_back(1)` the second, and so
1798 /// on.
1799 ///
1800 /// Note that all elements between the end and the returned
1801 /// element will be consumed, including the returned element.
1802 /// This also means that calling `nth_back(0)` multiple times on
1803 /// the same iterator will return different elements.
1804 ///
1805 /// `nth_back()` will return [`None`] if `n` is greater than or
1806 /// equal to the length of the iterator.
1807 ///
1808 /// # Examples
1809 ///
1810 /// Basic usage:
1811 ///
1812 /// ```rune
1813 /// let a = [1, 2, 3];
1814 /// assert_eq!(a.iter().nth_back(2), Some(1));
1815 /// ```
1816 ///
1817 /// Calling `nth_back()` multiple times doesn't rewind the
1818 /// iterator:
1819 ///
1820 /// ```rune
1821 /// let a = [1, 2, 3];
1822 ///
1823 /// let iter = a.iter();
1824 ///
1825 /// assert_eq!(iter.nth_back(1), Some(2));
1826 /// assert_eq!(iter.nth_back(1), None);
1827 /// ```
1828 ///
1829 /// Returning [`None`] if there are less than `n + 1` elements:
1830 ///
1831 /// ```rune
1832 /// let a = [1, 2, 3];
1833 /// assert_eq!(a.iter().nth_back(10), None);
1834 /// ```
1835 })?;
1836
1837 t.function("rev")?
1838 .argument_types::<(Value,)>()?
1839 .argument_names(["self"])?
1840 .return_type::<Rev>()?
1841 .docs(docstring! {
1842 /// Reverses an iterator's direction.
1843 ///
1844 /// Usually, iterators iterate from left to right. After using `rev()`, an
1845 /// iterator will instead iterate from right to left.
1846 ///
1847 /// This is only possible if the iterator has an end, so `rev()` only works on
1848 /// double-ended iterators.
1849 ///
1850 /// # Examples
1851 ///
1852 /// ```rune
1853 /// let a = [1, 2, 3];
1854 ///
1855 /// let iter = a.iter().rev();
1856 ///
1857 /// assert_eq!(iter.next(), Some(3));
1858 /// assert_eq!(iter.next(), Some(2));
1859 /// assert_eq!(iter.next(), Some(1));
1860 ///
1861 /// assert_eq!(iter.next(), None);
1862 /// ```
1863 })?;
1864 }
1865
1866 m.function_meta(range)?;
1867
1868 m.ty::<Empty>()?;
1869 m.function_meta(Empty::next__meta)?;
1870 m.function_meta(Empty::next_back__meta)?;
1871 m.function_meta(Empty::size_hint__meta)?;
1872 m.implement_trait::<Empty>(rune::item!(::std::iter::Iterator))?;
1873 m.implement_trait::<Empty>(rune::item!(::std::iter::DoubleEndedIterator))?;
1874 m.function_meta(empty)?;
1875
1876 m.ty::<Once>()?;
1877 m.function_meta(Once::next__meta)?;
1878 m.function_meta(Once::next_back__meta)?;
1879 m.function_meta(Once::size_hint__meta)?;
1880 m.implement_trait::<Once>(rune::item!(::std::iter::Iterator))?;
1881 m.implement_trait::<Once>(rune::item!(::std::iter::DoubleEndedIterator))?;
1882 m.function_meta(once)?;
1883 Ok(m)
1884}
1885
1886/// Construct an iterator which produces no values.
1887///
1888/// # Examples
1889///
1890/// ```rune
1891/// use std::iter::empty;
1892///
1893/// assert!(empty().next().is_none());
1894/// assert_eq!(empty().collect::<Vec>(), []);
1895/// ```
1896#[rune::function]
1897fn empty() -> Empty {
1898 Empty
1899}
1900
1901#[derive(Any)]
1902#[rune(item = ::std::iter)]
1903struct Empty;
1904
1905impl Empty {
1906 #[rune::function(keep, protocol = NEXT)]
1907 fn next(&mut self) -> Option<Value> {
1908 None
1909 }
1910
1911 #[rune::function(keep, protocol = NEXT_BACK)]
1912 fn next_back(&mut self) -> Option<Value> {
1913 None
1914 }
1915
1916 #[rune::function(keep, protocol = SIZE_HINT)]
1917 fn size_hint(&self) -> (usize, Option<usize>) {
1918 (0, Some(0))
1919 }
1920}
1921
1922/// Construct an iterator which produces a single `value` once.
1923///
1924/// # Examples
1925///
1926/// ```rune
1927/// use std::iter::once;
1928///
1929/// assert!(once(42).next().is_some());
1930/// assert_eq!(once(42).collect::<Vec>(), [42]);
1931/// ```
1932#[rune::function]
1933fn once(value: Value) -> Once {
1934 Once { value: Some(value) }
1935}
1936
1937#[derive(Any)]
1938#[rune(item = ::std::iter)]
1939pub(crate) struct Once {
1940 #[rune(dismantle)]
1941 value: Option<Value>,
1942}
1943
1944impl Once {
1945 #[rune::function(keep, protocol = NEXT)]
1946 fn next(&mut self) -> Option<Value> {
1947 self.value.take()
1948 }
1949
1950 #[rune::function(keep, protocol = NEXT_BACK)]
1951 fn next_back(&mut self) -> Option<Value> {
1952 self.value.take()
1953 }
1954
1955 #[rune::function(keep, protocol = SIZE_HINT)]
1956 fn size_hint(&self) -> (usize, Option<usize>) {
1957 let len = usize::from(self.value.is_some());
1958 (len, Some(len))
1959 }
1960}
1961
1962/// Produce an iterator which starts at the range `start` and ends at the value
1963/// `end` (exclusive).
1964///
1965/// # Examples
1966///
1967/// ```rune
1968/// use std::iter::range;
1969///
1970/// assert!(range(0, 3).next().is_some());
1971/// assert_eq!(range(0, 3).collect::<Vec>(), [0, 1, 2]);
1972/// ```
1973#[rune::function(deprecated = "Use the `<from>..<to>` operator instead")]
1974fn range(start: i64, end: i64) -> RangeIter<i64> {
1975 RangeIter::new(start..end)
1976}
1977
1978/// Fuse the iterator if the expression is [`None`].
1979macro_rules! fuse {
1980 ($self:ident . $iter:ident . $($call:tt)+) => {
1981 match $self.$iter {
1982 Some(ref mut iter) => match iter.$($call)+? {
1983 None => {
1984 $self.$iter = None;
1985 None
1986 }
1987 item => item,
1988 },
1989 None => None,
1990 }
1991 };
1992}
1993
1994/// Try an iterator method without fusing,
1995/// like an inline `.as_mut().and_then(...)`
1996macro_rules! maybe {
1997 ($self:ident . $iter:ident . $($call:tt)+) => {
1998 match $self.$iter {
1999 Some(ref mut iter) => iter.$($call)+?,
2000 None => None,
2001 }
2002 };
2003}
2004
2005#[derive(Any, Debug)]
2006#[rune(item = ::std::iter)]
2007pub(crate) struct Chain {
2008 #[rune(dismantle)]
2009 a: Option<Value>,
2010 #[rune(dismantle)]
2011 b: Option<Value>,
2012}
2013
2014impl Chain {
2015 #[rune::function(keep, protocol = NEXT)]
2016 #[inline]
2017 fn next(&mut self) -> Result<Option<Value>, VmError> {
2018 Ok(match fuse!(self.a.protocol_next()) {
2019 None => maybe!(self.b.protocol_next()),
2020 item => item,
2021 })
2022 }
2023
2024 #[rune::function(keep, protocol = NEXT_BACK)]
2025 #[inline]
2026 fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2027 Ok(match fuse!(self.b.protocol_next_back()) {
2028 None => maybe!(self.a.protocol_next_back()),
2029 item => item,
2030 })
2031 }
2032
2033 #[rune::function(keep, protocol = SIZE_HINT)]
2034 #[inline]
2035 fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2036 match self {
2037 Self {
2038 a: Some(a),
2039 b: Some(b),
2040 } => {
2041 let (a_lower, a_upper) = a.protocol_size_hint()?;
2042 let (b_lower, b_upper) = b.protocol_size_hint()?;
2043
2044 let lower = a_lower.saturating_add(b_lower);
2045
2046 let upper = match (a_upper, b_upper) {
2047 (Some(x), Some(y)) => x.checked_add(y),
2048 _ => None,
2049 };
2050
2051 Ok((lower, upper))
2052 }
2053 Self {
2054 a: Some(a),
2055 b: None,
2056 } => a.protocol_size_hint(),
2057 Self {
2058 a: None,
2059 b: Some(b),
2060 } => b.protocol_size_hint(),
2061 Self { a: None, b: None } => Ok((0, Some(0))),
2062 }
2063 }
2064
2065 #[rune::function(keep, protocol = LEN)]
2066 #[inline]
2067 fn len(&self) -> Result<usize, VmError> {
2068 match self {
2069 Self {
2070 a: Some(a),
2071 b: Some(b),
2072 } => {
2073 let a_len = a.protocol_len()?;
2074 let b_len = b.protocol_len()?;
2075 Ok(a_len.saturating_add(b_len))
2076 }
2077 Self {
2078 a: Some(a),
2079 b: None,
2080 } => a.protocol_len(),
2081 Self {
2082 a: None,
2083 b: Some(b),
2084 } => b.protocol_len(),
2085 Self { a: None, b: None } => Ok(0),
2086 }
2087 }
2088}
2089
2090#[derive(Any, Debug)]
2091#[rune(item = ::std::iter)]
2092pub(crate) struct Enumerate {
2093 #[rune(dismantle)]
2094 iter: Value,
2095 count: usize,
2096}
2097
2098impl Enumerate {
2099 #[rune::function(keep, protocol = NEXT)]
2100 #[inline]
2101 fn next(&mut self) -> Result<Option<(usize, Value)>, VmError> {
2102 if let Some(value) = self.iter.protocol_next()? {
2103 let i = self.count;
2104 self.count += 1;
2105 return Ok(Some((i, value)));
2106 }
2107
2108 Ok(None)
2109 }
2110
2111 #[rune::function(keep, protocol = NEXT_BACK)]
2112 #[inline]
2113 fn next_back(&mut self) -> Result<Option<(usize, Value)>, VmError> {
2114 if let Some(value) = self.iter.protocol_next_back()? {
2115 let len = self.iter.protocol_len()?;
2116 return Ok(Some((self.count + len, value)));
2117 }
2118
2119 Ok(None)
2120 }
2121
2122 #[rune::function(keep, protocol = SIZE_HINT)]
2123 #[inline]
2124 fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2125 self.iter.protocol_size_hint()
2126 }
2127
2128 #[rune::function(keep, protocol = LEN)]
2129 #[inline]
2130 fn len(&self) -> Result<usize, VmError> {
2131 self.iter.protocol_len()
2132 }
2133}
2134
2135#[derive(Any, Debug)]
2136#[rune(item = ::std::iter)]
2137pub(crate) struct Filter {
2138 #[rune(dismantle)]
2139 iter: Value,
2140 #[rune(dismantle)]
2141 f: Function,
2142}
2143
2144impl Filter {
2145 #[rune::function(keep, protocol = NEXT)]
2146 #[inline]
2147 fn next(&mut self) -> Result<Option<Value>, VmError> {
2148 while let Some(value) = self.iter.protocol_next()? {
2149 if self.f.call::<bool>((value.clone(),))? {
2150 return Ok(Some(value));
2151 }
2152 }
2153
2154 Ok(None)
2155 }
2156
2157 #[rune::function(keep, protocol = NEXT_BACK)]
2158 #[inline]
2159 fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2160 while let Some(value) = self.iter.protocol_next_back()? {
2161 if self.f.call::<bool>((value.clone(),))? {
2162 return Ok(Some(value));
2163 }
2164 }
2165
2166 Ok(None)
2167 }
2168
2169 #[rune::function(keep, protocol = SIZE_HINT)]
2170 #[inline]
2171 fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2172 let (_, hi) = self.iter.protocol_size_hint()?;
2173 Ok((0, hi))
2174 }
2175}
2176
2177#[derive(Any, Debug)]
2178#[rune(item = ::std::iter)]
2179pub(crate) struct Map {
2180 #[rune(dismantle)]
2181 iter: Option<Value>,
2182 #[rune(dismantle)]
2183 f: Function,
2184}
2185
2186impl Map {
2187 #[rune::function(keep, protocol = NEXT)]
2188 #[inline]
2189 fn next(&mut self) -> Result<Option<Value>, VmError> {
2190 if let Some(value) = fuse!(self.iter.protocol_next()) {
2191 return Ok(Some(self.f.call::<Value>((value.clone(),))?));
2192 }
2193
2194 Ok(None)
2195 }
2196
2197 #[rune::function(keep, protocol = NEXT_BACK)]
2198 #[inline]
2199 fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2200 if let Some(value) = fuse!(self.iter.protocol_next_back()) {
2201 return Ok(Some(self.f.call::<Value>((value.clone(),))?));
2202 }
2203
2204 Ok(None)
2205 }
2206
2207 #[rune::function(keep, protocol = SIZE_HINT)]
2208 #[inline]
2209 fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2210 let Some(iter) = &self.iter else {
2211 return Ok((0, Some(0)));
2212 };
2213
2214 iter.protocol_size_hint()
2215 }
2216
2217 #[rune::function(keep, protocol = LEN)]
2218 #[inline]
2219 fn len(&self) -> Result<usize, VmError> {
2220 let Some(iter) = &self.iter else {
2221 return Ok(0);
2222 };
2223
2224 iter.protocol_len()
2225 }
2226}
2227
2228#[derive(Any, Debug)]
2229#[rune(item = ::std::iter)]
2230pub(crate) struct FilterMap {
2231 #[rune(dismantle)]
2232 iter: Option<Value>,
2233 #[rune(dismantle)]
2234 f: Function,
2235}
2236
2237impl FilterMap {
2238 #[rune::function(keep, protocol = NEXT)]
2239 #[inline]
2240 fn next(&mut self) -> Result<Option<Value>, VmError> {
2241 while let Some(value) = fuse!(self.iter.protocol_next()) {
2242 if let Some(value) = self.f.call::<Option<Value>>((value.clone(),))? {
2243 return Ok(Some(value));
2244 }
2245 }
2246
2247 Ok(None)
2248 }
2249
2250 #[rune::function(keep, protocol = NEXT_BACK)]
2251 #[inline]
2252 fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2253 while let Some(value) = fuse!(self.iter.protocol_next_back()) {
2254 if let Some(value) = self.f.call::<Option<Value>>((value.clone(),))? {
2255 return Ok(Some(value));
2256 }
2257 }
2258
2259 Ok(None)
2260 }
2261}
2262
2263#[derive(Any, Debug)]
2264#[rune(item = ::std::iter)]
2265pub(crate) struct FlatMap {
2266 #[rune(dismantle)]
2267 map: Map,
2268 #[rune(dismantle)]
2269 frontiter: Option<Value>,
2270 #[rune(dismantle)]
2271 backiter: Option<Value>,
2272}
2273
2274impl FlatMap {
2275 #[rune::function(keep, protocol = NEXT)]
2276 #[inline]
2277 fn next(&mut self) -> Result<Option<Value>, VmError> {
2278 loop {
2279 if let Some(iter) = &mut self.frontiter {
2280 match iter.protocol_next()? {
2281 None => self.frontiter = None,
2282 item @ Some(_) => return Ok(item),
2283 }
2284 }
2285
2286 let Some(value) = self.map.next()? else {
2287 return Ok(match &mut self.backiter {
2288 Some(backiter) => backiter.protocol_next()?,
2289 None => None,
2290 });
2291 };
2292
2293 self.frontiter = Some(value.protocol_into_iter()?)
2294 }
2295 }
2296
2297 #[rune::function(keep, protocol = NEXT_BACK)]
2298 #[inline]
2299 fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2300 loop {
2301 if let Some(ref mut iter) = self.backiter {
2302 match iter.protocol_next_back()? {
2303 None => self.backiter = None,
2304 item @ Some(_) => return Ok(item),
2305 }
2306 }
2307
2308 let Some(value) = self.map.next_back()? else {
2309 return Ok(match &mut self.frontiter {
2310 Some(frontiter) => frontiter.protocol_next_back()?,
2311 None => None,
2312 });
2313 };
2314
2315 self.backiter = Some(value.protocol_into_iter()?);
2316 }
2317 }
2318
2319 #[rune::function(keep, protocol = SIZE_HINT)]
2320 #[inline]
2321 fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2322 let (flo, fhi) = match &self.frontiter {
2323 Some(iter) => iter.protocol_size_hint()?,
2324 None => (0, Some(0)),
2325 };
2326
2327 let (blo, bhi) = match &self.backiter {
2328 Some(iter) => iter.protocol_size_hint()?,
2329 None => (0, Some(0)),
2330 };
2331
2332 let lo = flo.saturating_add(blo);
2333
2334 Ok(match (self.map.size_hint()?, fhi, bhi) {
2335 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
2336 _ => (lo, None),
2337 })
2338 }
2339}
2340
2341#[derive(Any, Debug)]
2342#[rune(item = ::std::iter, dismantle)]
2343pub(crate) struct Peekable {
2344 iter: Value,
2345 peeked: Option<Option<Value>>,
2346}
2347
2348impl Peekable {
2349 #[rune::function(keep, protocol = NEXT)]
2350 #[inline]
2351 fn next(&mut self) -> Result<Option<Value>, VmError> {
2352 Ok(match self.peeked.take() {
2353 Some(v) => v,
2354 None => self.iter.protocol_next()?,
2355 })
2356 }
2357
2358 #[rune::function(keep, protocol = NEXT_BACK)]
2359 #[inline]
2360 fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2361 Ok(match self.peeked.as_mut() {
2362 Some(v @ Some(_)) => self.iter.protocol_next_back()?.or_else(|| v.take()),
2363 Some(None) => None,
2364 None => self.iter.protocol_next_back()?,
2365 })
2366 }
2367
2368 #[rune::function(keep, protocol = SIZE_HINT)]
2369 #[inline]
2370 fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2371 let peek_len = match &self.peeked {
2372 Some(None) => return Ok((0, Some(0))),
2373 Some(Some(_)) => 1,
2374 None => 0,
2375 };
2376
2377 let (lo, hi) = self.iter.protocol_size_hint()?;
2378 let lo = lo.saturating_add(peek_len);
2379
2380 let hi = match hi {
2381 Some(x) => x.checked_add(peek_len),
2382 None => None,
2383 };
2384
2385 Ok((lo, hi))
2386 }
2387
2388 #[rune::function(keep, protocol = LEN)]
2389 #[inline]
2390 fn len(&self) -> Result<usize, VmError> {
2391 let peek_len = match &self.peeked {
2392 Some(None) => return Ok(0),
2393 Some(Some(_)) => 1,
2394 None => 0,
2395 };
2396
2397 let len = self.iter.protocol_len()?;
2398 Ok(len.saturating_add(peek_len))
2399 }
2400
2401 /// Returns a reference to the `next()` value without advancing the iterator.
2402 ///
2403 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`. But if the
2404 /// iteration is over, [`None`] is returned.
2405 ///
2406 /// [`next`]: Iterator::next
2407 ///
2408 /// Because `peek()` returns a reference, and many iterators iterate over
2409 /// references, there can be a possibly confusing situation where the return
2410 /// value is a double reference. You can see this effect in the examples below.
2411 ///
2412 /// # Examples
2413 ///
2414 /// Basic usage:
2415 ///
2416 /// ```rune
2417 /// let xs = [1, 2, 3];
2418 ///
2419 /// let iter = xs.iter().peekable();
2420 ///
2421 /// // peek() lets us see into the future
2422 /// assert_eq!(iter.peek(), Some(1));
2423 /// assert_eq!(iter.next(), Some(1));
2424 ///
2425 /// assert_eq!(iter.next(), Some(2));
2426 ///
2427 /// // The iterator does not advance even if we `peek` multiple times
2428 /// assert_eq!(iter.peek(), Some(3));
2429 /// assert_eq!(iter.peek(), Some(3));
2430 ///
2431 /// assert_eq!(iter.next(), Some(3));
2432 ///
2433 /// // After the iterator is finished, so is `peek()`
2434 /// assert_eq!(iter.peek(), None);
2435 /// assert_eq!(iter.next(), None);
2436 /// ```
2437 #[rune::function(keep)]
2438 #[inline]
2439 fn peek(&mut self) -> Result<Option<Value>, VmError> {
2440 if let Some(v) = &self.peeked {
2441 return Ok(v.clone());
2442 }
2443
2444 let value = self.iter.protocol_next()?;
2445 self.peeked = Some(value.clone());
2446 Ok(value)
2447 }
2448}
2449
2450#[derive(Any, Debug)]
2451#[rune(item = ::std::iter)]
2452pub(crate) struct Skip {
2453 #[rune(dismantle)]
2454 iter: Value,
2455 n: usize,
2456}
2457
2458impl Skip {
2459 #[rune::function(keep, protocol = NEXT)]
2460 #[inline]
2461 fn next(&mut self) -> Result<Option<Value>, VmError> {
2462 if self.n > 0 {
2463 let old_n = self.n;
2464 self.n = 0;
2465
2466 for _ in 0..old_n {
2467 match self.iter.protocol_next()? {
2468 Some(..) => (),
2469 None => return Ok(None),
2470 }
2471 }
2472 }
2473
2474 self.iter.protocol_next()
2475 }
2476
2477 #[rune::function(keep, protocol = NEXT_BACK)]
2478 #[inline]
2479 fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2480 Ok(if self.len()? > 0 {
2481 self.iter.protocol_next_back()?
2482 } else {
2483 None
2484 })
2485 }
2486
2487 #[rune::function(keep, protocol = SIZE_HINT)]
2488 #[inline]
2489 fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2490 let (lower, upper) = self.iter.protocol_size_hint()?;
2491 let lower = lower.saturating_sub(self.n);
2492 let upper = upper.map(|x| x.saturating_sub(self.n));
2493 Ok((lower, upper))
2494 }
2495
2496 #[rune::function(keep, protocol = LEN)]
2497 #[inline]
2498 fn len(&self) -> Result<usize, VmError> {
2499 let len = self.iter.protocol_len()?;
2500 Ok(len.saturating_sub(self.n))
2501 }
2502}
2503
2504#[derive(Any, Debug)]
2505#[rune(item = ::std::iter)]
2506pub(crate) struct Take {
2507 #[rune(dismantle)]
2508 iter: Value,
2509 n: usize,
2510}
2511
2512impl Take {
2513 #[rune::function(keep, protocol = NEXT)]
2514 #[inline]
2515 fn next(&mut self) -> Result<Option<Value>, VmError> {
2516 if self.n == 0 {
2517 return Ok(None);
2518 }
2519
2520 self.n -= 1;
2521 self.iter.protocol_next()
2522 }
2523
2524 #[rune::function(keep, protocol = NEXT_BACK)]
2525 #[inline]
2526 fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2527 if self.n == 0 {
2528 Ok(None)
2529 } else {
2530 let n = self.n;
2531 self.n -= 1;
2532 let len = self.iter.protocol_len()?;
2533 self.iter.protocol_nth_back(len.saturating_sub(n))
2534 }
2535 }
2536
2537 #[rune::function(keep, protocol = SIZE_HINT)]
2538 #[inline]
2539 fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2540 if self.n == 0 {
2541 return Ok((0, Some(0)));
2542 }
2543
2544 let (lower, upper) = self.iter.protocol_size_hint()?;
2545
2546 let lower = lower.min(self.n);
2547
2548 let upper = match upper {
2549 Some(x) if x < self.n => Some(x),
2550 _ => Some(self.n),
2551 };
2552
2553 Ok((lower, upper))
2554 }
2555
2556 #[rune::function(keep, protocol = LEN)]
2557 #[inline]
2558 fn len(&self) -> Result<usize, VmError> {
2559 if self.n == 0 {
2560 return Ok(0);
2561 }
2562
2563 let len = self.iter.protocol_len()?;
2564 Ok(len.min(self.n))
2565 }
2566}
2567
2568#[derive(Any, Debug)]
2569#[rune(item = ::std::iter)]
2570pub(crate) struct Rev {
2571 #[rune(dismantle)]
2572 value: Value,
2573}
2574
2575impl Rev {
2576 #[rune::function(keep, protocol = NEXT)]
2577 #[inline]
2578 fn next(&mut self) -> Result<Option<Value>, VmError> {
2579 self.value.protocol_next_back()
2580 }
2581
2582 #[rune::function(keep, protocol = NEXT_BACK)]
2583 #[inline]
2584 fn next_back(&mut self) -> Result<Option<Value>, VmError> {
2585 self.value.protocol_next()
2586 }
2587
2588 #[rune::function(keep, protocol = SIZE_HINT)]
2589 #[inline]
2590 fn size_hint(&self) -> Result<(usize, Option<usize>), VmError> {
2591 self.value.protocol_size_hint()
2592 }
2593
2594 #[rune::function(keep, protocol = LEN)]
2595 #[inline]
2596 fn len(&self) -> Result<usize, VmError> {
2597 self.value.protocol_len()
2598 }
2599}
2600
2601pub(crate) trait CheckedOps: Sized {
2602 const ONE: Self;
2603 const ZERO: Self;
2604
2605 fn checked_add(self, value: Self) -> Option<Self>;
2606 fn checked_mul(self, value: Self) -> Option<Self>;
2607}
2608
2609impl CheckedOps for i64 {
2610 const ONE: Self = 1;
2611 const ZERO: Self = 0;
2612
2613 #[inline]
2614 fn checked_add(self, value: Self) -> Option<Self> {
2615 i64::checked_add(self, value)
2616 }
2617
2618 #[inline]
2619 fn checked_mul(self, value: Self) -> Option<Self> {
2620 i64::checked_mul(self, value)
2621 }
2622}
2623
2624impl CheckedOps for u64 {
2625 const ONE: Self = 1;
2626 const ZERO: Self = 0;
2627
2628 #[inline]
2629 fn checked_add(self, value: Self) -> Option<Self> {
2630 u64::checked_add(self, value)
2631 }
2632
2633 #[inline]
2634 fn checked_mul(self, value: Self) -> Option<Self> {
2635 u64::checked_mul(self, value)
2636 }
2637}
2638
2639impl CheckedOps for f64 {
2640 const ONE: Self = 1.0;
2641 const ZERO: Self = 0.0;
2642
2643 #[inline]
2644 fn checked_add(self, value: Self) -> Option<Self> {
2645 Some(self + value)
2646 }
2647
2648 #[inline]
2649 fn checked_mul(self, value: Self) -> Option<Self> {
2650 Some(self * value)
2651 }
2652}
2653
2654/// A peeked value is held one level deeper than the derive can reach, so this
2655/// one hands over what it holds by hand while the rest of the adapters mark the
2656/// fields which hold values.
2657impl Dismantle for Peekable {
2658 fn dismantle(&mut self, out: &mut Handover<'_>) {
2659 out.consume(&mut self.iter);
2660 out.consume_all(self.peeked.iter_mut().flatten());
2661 }
2662}