rune/modules/option.rs
1//! The [`Option`] type.
2
3use core::cmp::Ordering;
4use core::hash::Hasher as _;
5
6use crate as rune;
7use crate::alloc::fmt::TryWrite;
8use crate::alloc::String;
9use crate::runtime::{
10 ControlFlow, EnvProtocolCaller, Formatter, Function, Hasher, Panic, Protocol, Value, VmError,
11};
12use crate::Any;
13use crate::{hash_in, ContextError, Hash, Module};
14
15/// The [`Option`] type.
16///
17/// This module deals with the fundamental [`Option`] type in rune.
18#[rune::module(::std::option)]
19pub fn module() -> Result<Module, ContextError> {
20 let mut m = Module::from_meta(self::module__meta)?;
21 let mut option = m.ty::<Option<Value>>()?.make_enum(&["Some", "None"])?;
22
23 option
24 .variant_mut(0)?
25 .make_unnamed(1)?
26 .constructor(Option::Some)?
27 .static_docs(&["Some value."])?;
28
29 option
30 .variant_mut(1)?
31 .make_empty()?
32 .constructor(|| Option::None)?
33 .static_docs(&["No value."])?;
34
35 m.function_meta(is_variant__meta)?;
36
37 m.index_function(&Protocol::GET, 0, |this: &Option<Value>| match this {
38 Option::Some(value) => Ok(value.clone()),
39 _ => Err(crate::__priv::e::unsupported_tuple_index_get(
40 <Option<Value> as Any>::ANY_TYPE_INFO,
41 0,
42 )),
43 })?;
44
45 m.function_meta(expect)?;
46 m.function_meta(is_some)?;
47 m.function_meta(is_none)?;
48 m.function_meta(iter)?;
49 m.function_meta(into_iter)?;
50 m.function_meta(and_then)?;
51 m.function_meta(map)?;
52 m.function_meta(take)?;
53 m.function_meta(transpose)?;
54 m.function_meta(unwrap)?;
55 m.function_meta(unwrap_or)?;
56 m.function_meta(unwrap_or_else)?;
57 m.function_meta(ok_or)?;
58 m.function_meta(ok_or_else)?;
59
60 m.function_meta(clone__meta)?;
61 m.implement_trait::<Option<Value>>(rune::item!(::std::clone::Clone))?;
62
63 m.function_meta(partial_eq__meta)?;
64 m.implement_trait::<Option<Value>>(rune::item!(::std::cmp::PartialEq))?;
65
66 m.function_meta(eq__meta)?;
67 m.implement_trait::<Option<Value>>(rune::item!(::std::cmp::Eq))?;
68
69 m.function_meta(partial_cmp__meta)?;
70 m.implement_trait::<Option<Value>>(rune::item!(::std::cmp::PartialOrd))?;
71
72 m.function_meta(cmp__meta)?;
73 m.implement_trait::<Option<Value>>(rune::item!(::std::cmp::Ord))?;
74
75 m.function_meta(hash__meta)?;
76 m.function_meta(debug_fmt__meta)?;
77
78 m.function_meta(option_try__meta)?;
79
80 m.ty::<Iter>()?;
81 m.function_meta(Iter::next__meta)?;
82 m.function_meta(Iter::next_back__meta)?;
83 m.function_meta(Iter::size_hint__meta)?;
84 m.implement_trait::<Iter>(rune::item!(::std::iter::Iterator))?;
85 m.implement_trait::<Iter>(rune::item!(::std::iter::DoubleEndedIterator))?;
86 m.function_meta(Iter::clone__meta)?;
87 m.implement_trait::<Iter>(rune::item!(::std::clone::Clone))?;
88
89 Ok(m)
90}
91
92#[rune::function(instance, keep, protocol = IS_VARIANT)]
93#[inline]
94pub(crate) fn is_variant(this: &Option<Value>, variant_hash: Hash) -> bool {
95 match (this, variant_hash) {
96 (Option::Some(_), hash_in!(crate, ::std::option::Option::Some)) => true,
97 (Option::None, hash_in!(crate, ::std::option::Option::None)) => true,
98 _ => false,
99 }
100}
101
102/// Returns the contained [`Some`] value, consuming the `self` value.
103///
104/// # Panics
105///
106/// Panics if the value is a [`None`] with a custom panic message provided by
107/// `msg`.
108///
109/// # Examples
110///
111/// ```rune
112/// let x = Some("value");
113/// assert_eq!(x.expect("fruits are healthy"), "value");
114/// ```
115///
116/// ```rune,should_panic
117/// let x = None;
118/// x.expect("fruits are healthy"); // panics with `fruits are healthy`
119/// ```
120///
121/// # Recommended Message Style
122///
123/// We recommend that `expect` messages are used to describe the reason you
124/// _expect_ the [`Option`] should be [`Some`].
125///
126/// ```rune,should_panic
127/// # let slice = [];
128/// let item = slice.get(0).expect("slice should not be empty");
129/// ```
130///
131/// **Hint**: If you're having trouble remembering how to phrase expect error
132/// messages remember to focus on the word "should" as in "env variable should
133/// be set by blah" or "the given binary should be available and executable by
134/// the current user".
135///
136/// For more detail on expect message styles and the reasoning behind our
137/// recommendation please refer to the section on ["Common Message
138/// Styles"](https://doc.rust-lang.org/std/error/index.html#common-message-styles) in the
139/// [`std::error`](https://doc.rust-lang.org/std/error/index.html) module docs.
140#[rune::function(instance)]
141fn expect(option: &Option<Value>, message: Value) -> Result<Value, VmError> {
142 match option {
143 Some(some) => Ok(some.clone()),
144 None => {
145 let mut s = String::new();
146 Formatter::format_with(&mut s, |f| message.display_fmt(f))?;
147 Err(VmError::from(Panic::custom(s)))
148 }
149 }
150}
151
152/// Returns `true` if the option is a [`Some`] value.
153///
154/// # Examples
155///
156/// ```rune
157/// let x = Some(2);
158/// assert_eq!(x.is_some(), true);
159///
160/// let x = None;
161/// assert_eq!(x.is_some(), false);
162/// ```
163#[rune::function(instance)]
164fn is_some(this: &Option<Value>) -> bool {
165 this.is_some()
166}
167
168/// Returns `true` if the option is a [`None`] value.
169///
170/// # Examples
171///
172/// ```rune
173/// let x = Some(2);
174/// assert_eq!(x.is_none(), false);
175///
176/// let x = None;
177/// assert_eq!(x.is_none(), true);
178/// ```
179#[rune::function(instance)]
180fn is_none(this: &Option<Value>) -> bool {
181 this.is_none()
182}
183
184/// Construct an iterator over an optional value.
185///
186/// # Examples
187///
188/// ```rune
189/// let value = Some(1);
190/// let it = value.iter();
191///
192/// assert_eq!(Some(1), it.next());
193/// assert_eq!(None, it.next());
194///
195/// let value = None;
196/// let it = value.iter();
197///
198/// assert_eq!(None, it.next());
199/// ```
200#[rune::function(instance)]
201fn iter(value: &Option<Value>) -> Iter {
202 Iter::new(value.clone())
203}
204
205/// Construct an iterator over an optional value.
206///
207/// # Examples
208///
209/// ```rune
210/// let value = Some(1);
211///
212/// let out = [];
213///
214/// for v in value {
215/// out.push(v);
216/// }
217///
218/// assert_eq!(out, [1]);
219/// ```
220#[rune::function(instance, protocol = INTO_ITER)]
221fn into_iter(this: &Option<Value>) -> Iter {
222 Iter::new(this.clone())
223}
224
225/// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
226/// wrapped value and returns the result.
227///
228/// Some languages call this operation flatmap.
229///
230/// # Examples
231///
232/// ```rune
233/// fn sq_then_to_string(x) {
234/// x.checked_mul(x).map(|sq| sq.to_string())
235/// }
236///
237/// assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
238/// assert_eq!(Some(1_000_000_000_000_000_000).and_then(sq_then_to_string), None); // overflowed!
239/// assert_eq!(None.and_then(sq_then_to_string), None);
240/// ```
241///
242/// Often used to chain fallible operations that may return [`None`].
243///
244/// ```rune
245/// let arr_2d = [["A0", "A1"], ["B0", "B1"]];
246///
247/// let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
248/// assert_eq!(item_0_1, Some("A1"));
249///
250/// let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
251/// assert_eq!(item_2_0, None);
252/// ```
253#[rune::function(instance)]
254fn and_then(option: &Option<Value>, then: Function) -> Result<Option<Value>, VmError> {
255 match option {
256 // no need to clone v, passing the same reference forward
257 Some(v) => Ok(then.call((v.clone(),))?),
258 None => Ok(None),
259 }
260}
261
262/// Maps an `Option<T>` to `Option<U>` by applying a function to a contained
263/// value (if [`Some`]) or returns [`None`] (if [`None`]).
264///
265/// # Examples
266///
267/// Calculates the length of an `Option<[String]>` as an
268/// `Option<[usize]>`, consuming the original:
269///
270/// [String]: ../../std/string/struct.String.html "String"
271///
272/// ```rune
273/// let maybe_some_string = Some(String::from("Hello, World!"));
274/// // `Option::map` takes self *by value*, consuming `maybe_some_string`
275/// let maybe_some_len = maybe_some_string.map(|s| s.len());
276/// assert_eq!(maybe_some_len, Some(13));
277///
278/// let x = None;
279/// assert_eq!(x.map(|s| s.len()), None);
280/// ```
281#[rune::function(instance)]
282fn map(option: &Option<Value>, then: Function) -> Result<Option<Value>, VmError> {
283 match option {
284 // no need to clone v, passing the same reference forward
285 Some(v) => Ok(Some(then.call((v.clone(),))?)),
286 None => Ok(None),
287 }
288}
289
290/// Takes the value out of the option, leaving a [`None`] in its place.
291///
292/// # Examples
293///
294/// ```rune
295/// let x = Some(2);
296/// let y = x.take();
297/// assert_eq!(x, None);
298/// assert_eq!(y, Some(2));
299///
300/// let x = None;
301/// let y = x.take();
302/// assert_eq!(x, None);
303/// assert_eq!(y, None);
304/// ```
305#[rune::function(instance)]
306fn take(option: &mut Option<Value>) -> Option<Value> {
307 option.take()
308}
309
310/// Transposes an [`Option`] of a [`Result`] into a [`Result`] of an [`Option`].
311///
312/// [`None`] will be mapped to `[Ok]\([None])`. `[Some]\([Ok]\(\_))` and
313/// `[Some]\([Err]\(\_))` will be mapped to `[Ok]\([Some]\(\_))` and
314/// `[Err]\(\_)`.
315///
316/// # Examples
317///
318/// ```rune
319/// let x = Ok(Some(5));
320/// let y = Some(Ok(5));
321/// assert_eq!(x, y.transpose());
322/// ```
323#[rune::function(instance)]
324fn transpose(this: &Option<Value>) -> Result<Value, VmError> {
325 let value = match this {
326 Some(value) => value,
327 None => {
328 let none = Value::try_from(Option::<Value>::None)?;
329 let result = Value::try_from(Result::<Value, Value>::Ok(none))?;
330 return Ok(result);
331 }
332 };
333
334 match &*value.borrow_ref::<Result<Value, Value>>()? {
335 Ok(ok) => {
336 let some = Value::try_from(Some(ok.clone()))?;
337 let result = Value::try_from(Ok(some))?;
338 Ok(result)
339 }
340 Err(err) => {
341 let result = Value::try_from(Err(err.clone()))?;
342 Ok(result)
343 }
344 }
345}
346
347/// Returns the contained [`Some`] value, consuming the `self` value.
348///
349/// Because this function may panic, its use is generally discouraged. Instead,
350/// prefer to use pattern matching and handle the [`None`] case explicitly, or
351/// call [`unwrap_or`], [`unwrap_or_else`], or `unwrap_or_default`.
352///
353/// [`unwrap_or`]: Option::unwrap_or
354/// [`unwrap_or_else`]: Option::unwrap_or_else
355///
356/// # Panics
357///
358/// Panics if the self value equals [`None`].
359///
360/// # Examples
361///
362/// ```rune
363/// let x = Some("air");
364/// assert_eq!(x.unwrap(), "air");
365/// ```
366///
367/// ```rune,should_panic
368/// let x = None;
369/// assert_eq!(x.unwrap(), "air"); // fails
370/// ```
371#[rune::function(instance)]
372fn unwrap(option: &Option<Value>) -> Result<Value, VmError> {
373 match option {
374 Some(some) => Ok(some.clone()),
375 None => Err(VmError::from(Panic::custom(
376 "Called `Option::unwrap()` on a `None` value",
377 ))),
378 }
379}
380
381/// Returns the contained [`Some`] value or a provided `default`.
382///
383/// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
384/// the result of a function call, it is recommended to use [`unwrap_or_else`],
385/// which is lazily evaluated.
386///
387/// [`unwrap_or_else`]: Option::unwrap_or_else
388///
389/// # Examples
390///
391/// ```rune
392/// assert_eq!(Some("car").unwrap_or("bike"), "car");
393/// assert_eq!(None.unwrap_or("bike"), "bike");
394/// ```
395#[rune::function(instance)]
396fn unwrap_or(this: &Option<Value>, default: Value) -> Value {
397 match this {
398 Some(value) => value.clone(),
399 None => default,
400 }
401}
402
403/// Returns the contained [`Some`] value or computes it from a closure.
404///
405/// # Examples
406///
407/// ```rune
408/// let k = 10;
409/// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
410/// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
411/// ```
412#[rune::function(instance)]
413fn unwrap_or_else(this: &Option<Value>, default: Function) -> Result<Value, VmError> {
414 match this {
415 Some(value) => Ok(value.clone()),
416 None => default.call(()),
417 }
418}
419
420/// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
421/// [`Ok(v)`] and [`None`] to [`Err(err)`].
422///
423/// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
424/// result of a function call, it is recommended to use [`ok_or_else`], which is
425/// lazily evaluated.
426///
427/// [`Ok(v)`]: Ok
428/// [`Err(err)`]: Err
429/// [`Some(v)`]: Some
430/// [`ok_or_else`]: Option::ok_or_else
431///
432/// # Examples
433///
434/// ```rune
435/// let x = Some("foo");
436/// assert_eq!(x.ok_or(0), Ok("foo"));
437///
438/// let x = None;
439/// assert_eq!(x.ok_or(0), Err(0));
440/// ```
441#[rune::function(instance)]
442fn ok_or(this: &Option<Value>, err: Value) -> Result<Value, Value> {
443 match this {
444 Some(value) => Ok(value.clone()),
445 None => Err(err),
446 }
447}
448
449/// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
450/// [`Ok(v)`] and [`None`] to [`Err(err())`].
451///
452/// [`Ok(v)`]: Ok
453/// [`Err(err())`]: Err
454/// [`Some(v)`]: Some
455///
456/// # Examples
457///
458/// ```rune
459/// let x = Some("foo");
460/// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
461///
462/// let x = None;
463/// assert_eq!(x.ok_or_else(|| 0), Err(0));
464/// ```
465#[rune::function(instance)]
466fn ok_or_else(this: &Option<Value>, err: Function) -> Result<Result<Value, Value>, VmError> {
467 match this {
468 Some(value) => Ok(Ok(value.clone())),
469 None => Ok(Err(err.call(())?)),
470 }
471}
472
473/// Clone the option.
474///
475/// # Examples
476///
477/// ```rune
478/// let a = Some(b"hello world");
479/// let b = a.clone();
480///
481/// a?.extend(b"!");
482///
483/// assert_eq!(a, Some(b"hello world!"));
484/// assert_eq!(b, Some(b"hello world"));
485/// ```
486#[rune::function(keep, instance, protocol = CLONE)]
487fn clone(this: &Option<Value>) -> Result<Option<Value>, VmError> {
488 Ok(match this {
489 Some(value) => Some(value.clone_with(&mut EnvProtocolCaller)?),
490 None => None,
491 })
492}
493
494/// Test two options for partial equality.
495///
496/// # Examples
497///
498/// ```rune
499/// assert!(None == None);
500/// assert!(Some(b"a") == Some(b"a"));
501/// assert!(Some(b"a") != Some(b"ab"));
502/// assert!(Some(b"ab") != Some(b"a"));
503/// ```
504///
505/// Using explicit functions:
506///
507/// ```rune
508/// use std::ops::partial_eq;
509///
510/// assert_eq!(partial_eq(None, None), true);
511/// assert_eq!(partial_eq(Some(b"a"), Some(b"a")), true);
512/// assert_eq!(partial_eq(Some(b"a"), Some(b"ab")), false);
513/// assert_eq!(partial_eq(Some(b"ab"), Some(b"a")), false);
514/// ```
515#[rune::function(keep, instance, protocol = PARTIAL_EQ)]
516#[inline]
517fn partial_eq(this: &Option<Value>, rhs: &Option<Value>) -> Result<bool, VmError> {
518 match (this, rhs) {
519 (Some(a), Some(b)) => Ok(Value::partial_eq(a, b)?),
520 (None, None) => Ok(true),
521 _ => Ok(false),
522 }
523}
524
525/// Test two options for total equality.
526///
527/// # Examples
528///
529/// ```rune
530/// use std::ops::eq;
531///
532/// assert_eq!(eq(None, None), true);
533/// assert_eq!(eq(Some(b"a"), Some(b"a")), true);
534/// assert_eq!(eq(Some(b"a"), Some(b"ab")), false);
535/// assert_eq!(eq(Some(b"ab"), Some(b"a")), false);
536/// ```
537#[rune::function(keep, instance, protocol = EQ)]
538#[inline]
539fn eq(this: &Option<Value>, rhs: &Option<Value>) -> Result<bool, VmError> {
540 match (this, rhs) {
541 (Some(a), Some(b)) => Ok(Value::eq(a, b)?),
542 (None, None) => Ok(true),
543 _ => Ok(false),
544 }
545}
546
547/// Perform a partial ordered comparison between two options.
548///
549/// # Examples
550///
551/// ```rune
552/// assert!(Some(b"a") < Some(b"ab"));
553/// assert!(Some(b"ab") > Some(b"a"));
554/// assert!(Some(b"a") == Some(b"a"));
555/// ```
556///
557/// Using explicit functions:
558///
559/// ```rune
560/// use std::cmp::Ordering;
561/// use std::ops::partial_cmp;
562///
563/// assert_eq!(partial_cmp(Some(b"a"), Some(b"ab")), Some(Ordering::Less));
564/// assert_eq!(partial_cmp(Some(b"ab"), Some(b"a")), Some(Ordering::Greater));
565/// assert_eq!(partial_cmp(Some(b"a"), Some(b"a")), Some(Ordering::Equal));
566/// ```
567#[rune::function(keep, instance, protocol = PARTIAL_CMP)]
568#[inline]
569fn partial_cmp(this: &Option<Value>, rhs: &Option<Value>) -> Result<Option<Ordering>, VmError> {
570 match (this, rhs) {
571 (Some(a), Some(b)) => Ok(Value::partial_cmp(a, b)?),
572 (None, None) => Ok(Some(Ordering::Equal)),
573 (Some(..), None) => Ok(Some(Ordering::Greater)),
574 (None, Some(..)) => Ok(Some(Ordering::Less)),
575 }
576}
577
578/// Perform a totally ordered comparison between two options.
579///
580/// # Examples
581///
582/// ```rune
583/// use std::cmp::Ordering;
584/// use std::ops::cmp;
585///
586/// assert_eq!(cmp(Some(b"a"), Some(b"ab")), Ordering::Less);
587/// assert_eq!(cmp(Some(b"ab"), Some(b"a")), Ordering::Greater);
588/// assert_eq!(cmp(Some(b"a"), Some(b"a")), Ordering::Equal);
589/// ```
590#[rune::function(keep, instance, protocol = CMP)]
591#[inline]
592fn cmp(this: &Option<Value>, rhs: &Option<Value>) -> Result<Ordering, VmError> {
593 match (this, rhs) {
594 (Some(a), Some(b)) => Ok(Value::cmp(a, b)?),
595 (None, None) => Ok(Ordering::Equal),
596 (Some(..), None) => Ok(Ordering::Greater),
597 (None, Some(..)) => Ok(Ordering::Less),
598 }
599}
600
601/// Hash the result.
602///
603/// # Examples
604///
605/// ```rune
606/// use std::ops::hash;
607///
608/// let a = Ok("hello");
609/// let b = Ok("hello");
610///
611/// assert_eq!(hash(a), hash(b));
612/// ```
613#[rune::function(keep, instance, protocol = HASH)]
614fn hash(this: &Option<Value>, hasher: &mut Hasher) -> Result<(), VmError> {
615 match this {
616 Some(value) => {
617 hasher.write_u64(0);
618 value.hash(hasher)?;
619 }
620 None => {
621 hasher.write_u64(1);
622 }
623 }
624
625 Ok(())
626}
627
628/// Write a debug representation of a result.
629///
630/// # Examples
631///
632/// ```rune
633/// println!("{:?}", Some("Hello"));
634/// println!("{:?}", None);
635/// ```
636#[rune::function(keep, instance, protocol = DEBUG_FMT)]
637#[inline]
638fn debug_fmt(this: &Option<Value>, f: &mut Formatter) -> Result<(), VmError> {
639 match this {
640 Some(value) => {
641 f.try_write_str("Some(")?;
642 value.debug_fmt(f)?;
643 f.try_write_str(")")?;
644 }
645 None => {
646 f.try_write_str("None")?;
647 }
648 }
649
650 Ok(())
651}
652
653/// Using [`Option`] with the try protocol.
654///
655/// # Examples
656///
657/// ```rune
658/// fn maybe_add_one(value) {
659/// Some(value? + 1)
660/// }
661///
662/// assert_eq!(maybe_add_one(Some(4)), Some(5));
663/// assert_eq!(maybe_add_one(None), None);
664/// ```
665#[rune::function(keep, instance, protocol = TRY)]
666pub(crate) fn option_try(this: &Option<Value>) -> Result<ControlFlow, VmError> {
667 Ok(match this {
668 Some(value) => ControlFlow::Continue(value.clone()),
669 None => ControlFlow::Break(Value::try_from(None)?),
670 })
671}
672
673/// The iterator holds the value it hands out, and a script can nest one inside
674/// another - `a = Some(a).iter()` in a loop - so it hands it over rather than
675/// being dropped in place.
676#[derive(Any, Clone)]
677#[rune(item = ::std::option)]
678pub(crate) struct Iter {
679 #[rune(dismantle)]
680 value: Option<Value>,
681}
682
683impl Iter {
684 /// Construct a new iterator.
685 fn new(value: Option<Value>) -> Self {
686 Self { value }
687 }
688
689 /// Get the next value in the iterator.
690 ///
691 /// # Examples
692 ///
693 /// ```rune
694 /// let a = Some(1).iter();
695 ///
696 /// assert_eq!(a.next(), Some(1));
697 /// assert_eq!(a.next(), None);
698 /// ```
699 #[rune::function(keep, protocol = NEXT)]
700 fn next(&mut self) -> Option<Value> {
701 self.value.take()
702 }
703
704 /// Get the next back value in the iterator.
705 ///
706 /// # Examples
707 ///
708 /// ```rune
709 /// let a = Some(1).iter();
710 ///
711 /// assert_eq!(a.next_back(), Some(1));
712 /// assert_eq!(a.next_back(), None);
713 /// ```
714 #[rune::function(keep, protocol = NEXT_BACK)]
715 fn next_back(&mut self) -> Option<Value> {
716 self.value.take()
717 }
718
719 /// Get a size hint of the option iterator.
720 ///
721 /// # Examples
722 ///
723 /// ```rune
724 /// let a = Some(1).iter();
725 ///
726 /// assert_eq!(a.size_hint(), (1, Some(1)));
727 /// ```
728 #[rune::function(keep, protocol = SIZE_HINT)]
729 fn size_hint(&self) -> (usize, Option<usize>) {
730 let len = usize::from(self.value.is_some());
731 (len, Some(len))
732 }
733
734 /// Convert into an iterator.
735 ///
736 /// # Examples
737 ///
738 /// ```rune
739 /// let a = Some(42);
740 ///
741 /// let v = 0;
742 ///
743 /// for i in a {
744 /// v = 42;
745 /// }
746 ///
747 /// assert_eq!(v, 1);
748 /// ```
749 #[rune::function(keep, protocol = INTO_ITER)]
750 fn into_iter(self) -> Self {
751 self
752 }
753
754 /// Clone the option iterator.
755 ///
756 /// # Examples
757 ///
758 /// ```rune
759 /// let a = Some(1);
760 /// let it = a.iter();
761 ///
762 /// assert_eq!(it.clone().next(), Some(1));
763 /// assert_eq!(it.next(), Some(1));
764 /// assert_eq!(it.next(), None);
765 /// ```
766 #[rune::function(keep, protocol = CLONE)]
767 #[inline]
768 fn clone(&self) -> Self {
769 Clone::clone(self)
770 }
771}