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