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