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