]> git.lizzy.rs Git - rust.git/blob - src/libcore/option.rs
Rollup merge of #67967 - JohnTitor:fix-ice-0107, r=matthewjasper
[rust.git] / src / libcore / option.rs
1 //! Optional values.
2 //!
3 //! Type [`Option`] represents an optional value: every [`Option`]
4 //! is either [`Some`] and contains a value, or [`None`], and
5 //! does not. [`Option`] types are very common in Rust code, as
6 //! they have a number of uses:
7 //!
8 //! * Initial values
9 //! * Return values for functions that are not defined
10 //!   over their entire input range (partial functions)
11 //! * Return value for otherwise reporting simple errors, where [`None`] is
12 //!   returned on error
13 //! * Optional struct fields
14 //! * Struct fields that can be loaned or "taken"
15 //! * Optional function arguments
16 //! * Nullable pointers
17 //! * Swapping things out of difficult situations
18 //!
19 //! [`Option`]s are commonly paired with pattern matching to query the presence
20 //! of a value and take action, always accounting for the [`None`] case.
21 //!
22 //! ```
23 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
24 //!     if denominator == 0.0 {
25 //!         None
26 //!     } else {
27 //!         Some(numerator / denominator)
28 //!     }
29 //! }
30 //!
31 //! // The return value of the function is an option
32 //! let result = divide(2.0, 3.0);
33 //!
34 //! // Pattern match to retrieve the value
35 //! match result {
36 //!     // The division was valid
37 //!     Some(x) => println!("Result: {}", x),
38 //!     // The division was invalid
39 //!     None    => println!("Cannot divide by 0"),
40 //! }
41 //! ```
42 //!
43 //
44 // FIXME: Show how `Option` is used in practice, with lots of methods
45 //
46 //! # Options and pointers ("nullable" pointers)
47 //!
48 //! Rust's pointer types must always point to a valid location; there are
49 //! no "null" references. Instead, Rust has *optional* pointers, like
50 //! the optional owned box, [`Option`]`<`[`Box<T>`]`>`.
51 //!
52 //! The following example uses [`Option`] to create an optional box of
53 //! [`i32`]. Notice that in order to use the inner [`i32`] value first, the
54 //! `check_optional` function needs to use pattern matching to
55 //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
56 //! not ([`None`]).
57 //!
58 //! ```
59 //! let optional = None;
60 //! check_optional(optional);
61 //!
62 //! let optional = Some(Box::new(9000));
63 //! check_optional(optional);
64 //!
65 //! fn check_optional(optional: Option<Box<i32>>) {
66 //!     match optional {
67 //!         Some(p) => println!("has value {}", p),
68 //!         None => println!("has no value"),
69 //!     }
70 //! }
71 //! ```
72 //!
73 //! This usage of [`Option`] to create safe nullable pointers is so
74 //! common that Rust does special optimizations to make the
75 //! representation of [`Option`]`<`[`Box<T>`]`>` a single pointer. Optional pointers
76 //! in Rust are stored as efficiently as any other pointer type.
77 //!
78 //! # Examples
79 //!
80 //! Basic pattern matching on [`Option`]:
81 //!
82 //! ```
83 //! let msg = Some("howdy");
84 //!
85 //! // Take a reference to the contained string
86 //! if let Some(m) = &msg {
87 //!     println!("{}", *m);
88 //! }
89 //!
90 //! // Remove the contained string, destroying the Option
91 //! let unwrapped_msg = msg.unwrap_or("default message");
92 //! ```
93 //!
94 //! Initialize a result to [`None`] before a loop:
95 //!
96 //! ```
97 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
98 //!
99 //! // A list of data to search through.
100 //! let all_the_big_things = [
101 //!     Kingdom::Plant(250, "redwood"),
102 //!     Kingdom::Plant(230, "noble fir"),
103 //!     Kingdom::Plant(229, "sugar pine"),
104 //!     Kingdom::Animal(25, "blue whale"),
105 //!     Kingdom::Animal(19, "fin whale"),
106 //!     Kingdom::Animal(15, "north pacific right whale"),
107 //! ];
108 //!
109 //! // We're going to search for the name of the biggest animal,
110 //! // but to start with we've just got `None`.
111 //! let mut name_of_biggest_animal = None;
112 //! let mut size_of_biggest_animal = 0;
113 //! for big_thing in &all_the_big_things {
114 //!     match *big_thing {
115 //!         Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
116 //!             // Now we've found the name of some big animal
117 //!             size_of_biggest_animal = size;
118 //!             name_of_biggest_animal = Some(name);
119 //!         }
120 //!         Kingdom::Animal(..) | Kingdom::Plant(..) => ()
121 //!     }
122 //! }
123 //!
124 //! match name_of_biggest_animal {
125 //!     Some(name) => println!("the biggest animal is {}", name),
126 //!     None => println!("there are no animals :("),
127 //! }
128 //! ```
129 //!
130 //! [`Option`]: enum.Option.html
131 //! [`Some`]: enum.Option.html#variant.Some
132 //! [`None`]: enum.Option.html#variant.None
133 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
134 //! [`i32`]: ../../std/primitive.i32.html
135
136 // ignore-tidy-undocumented-unsafe
137
138 #![stable(feature = "rust1", since = "1.0.0")]
139
140 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
141 use crate::pin::Pin;
142 use crate::{
143     convert, fmt, hint, mem,
144     ops::{self, Deref, DerefMut},
145 };
146
147 // Note that this is not a lang item per se, but it has a hidden dependency on
148 // `Iterator`, which is one. The compiler assumes that the `next` method of
149 // `Iterator` is an enumeration with one type parameter and two variants,
150 // which basically means it must be `Option`.
151
152 /// The `Option` type. See [the module level documentation](index.html) for more.
153 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub enum Option<T> {
156     /// No value
157     #[stable(feature = "rust1", since = "1.0.0")]
158     None,
159     /// Some value `T`
160     #[stable(feature = "rust1", since = "1.0.0")]
161     Some(#[stable(feature = "rust1", since = "1.0.0")] T),
162 }
163
164 /////////////////////////////////////////////////////////////////////////////
165 // Type implementation
166 /////////////////////////////////////////////////////////////////////////////
167
168 impl<T> Option<T> {
169     /////////////////////////////////////////////////////////////////////////
170     // Querying the contained values
171     /////////////////////////////////////////////////////////////////////////
172
173     /// Returns `true` if the option is a [`Some`] value.
174     ///
175     /// # Examples
176     ///
177     /// ```
178     /// let x: Option<u32> = Some(2);
179     /// assert_eq!(x.is_some(), true);
180     ///
181     /// let x: Option<u32> = None;
182     /// assert_eq!(x.is_some(), false);
183     /// ```
184     ///
185     /// [`Some`]: #variant.Some
186     #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
187     #[inline]
188     #[stable(feature = "rust1", since = "1.0.0")]
189     pub fn is_some(&self) -> bool {
190         matches!(*self, Some(_))
191     }
192
193     /// Returns `true` if the option is a [`None`] value.
194     ///
195     /// # Examples
196     ///
197     /// ```
198     /// let x: Option<u32> = Some(2);
199     /// assert_eq!(x.is_none(), false);
200     ///
201     /// let x: Option<u32> = None;
202     /// assert_eq!(x.is_none(), true);
203     /// ```
204     ///
205     /// [`None`]: #variant.None
206     #[must_use = "if you intended to assert that this doesn't have a value, consider \
207                   `.and_then(|| panic!(\"`Option` had a value when expected `None`\"))` instead"]
208     #[inline]
209     #[stable(feature = "rust1", since = "1.0.0")]
210     pub fn is_none(&self) -> bool {
211         !self.is_some()
212     }
213
214     /// Returns `true` if the option is a [`Some`] value containing the given value.
215     ///
216     /// # Examples
217     ///
218     /// ```
219     /// #![feature(option_result_contains)]
220     ///
221     /// let x: Option<u32> = Some(2);
222     /// assert_eq!(x.contains(&2), true);
223     ///
224     /// let x: Option<u32> = Some(3);
225     /// assert_eq!(x.contains(&2), false);
226     ///
227     /// let x: Option<u32> = None;
228     /// assert_eq!(x.contains(&2), false);
229     /// ```
230     #[must_use]
231     #[inline]
232     #[unstable(feature = "option_result_contains", issue = "62358")]
233     pub fn contains<U>(&self, x: &U) -> bool
234     where
235         U: PartialEq<T>,
236     {
237         match self {
238             Some(y) => x == y,
239             None => false,
240         }
241     }
242
243     /////////////////////////////////////////////////////////////////////////
244     // Adapter for working with references
245     /////////////////////////////////////////////////////////////////////////
246
247     /// Converts from `&Option<T>` to `Option<&T>`.
248     ///
249     /// # Examples
250     ///
251     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
252     /// The [`map`] method takes the `self` argument by value, consuming the original,
253     /// so this technique uses `as_ref` to first take an `Option` to a reference
254     /// to the value inside the original.
255     ///
256     /// [`map`]: enum.Option.html#method.map
257     /// [`String`]: ../../std/string/struct.String.html
258     /// [`usize`]: ../../std/primitive.usize.html
259     ///
260     /// ```
261     /// let text: Option<String> = Some("Hello, world!".to_string());
262     /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
263     /// // then consume *that* with `map`, leaving `text` on the stack.
264     /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
265     /// println!("still can print text: {:?}", text);
266     /// ```
267     #[inline]
268     #[stable(feature = "rust1", since = "1.0.0")]
269     pub fn as_ref(&self) -> Option<&T> {
270         match *self {
271             Some(ref x) => Some(x),
272             None => None,
273         }
274     }
275
276     /// Converts from `&mut Option<T>` to `Option<&mut T>`.
277     ///
278     /// # Examples
279     ///
280     /// ```
281     /// let mut x = Some(2);
282     /// match x.as_mut() {
283     ///     Some(v) => *v = 42,
284     ///     None => {},
285     /// }
286     /// assert_eq!(x, Some(42));
287     /// ```
288     #[inline]
289     #[stable(feature = "rust1", since = "1.0.0")]
290     pub fn as_mut(&mut self) -> Option<&mut T> {
291         match *self {
292             Some(ref mut x) => Some(x),
293             None => None,
294         }
295     }
296
297     /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
298     ///
299     /// [`Pin`]: ../pin/struct.Pin.html
300     #[inline]
301     #[stable(feature = "pin", since = "1.33.0")]
302     pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
303         unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
304     }
305
306     /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
307     ///
308     /// [`Pin`]: ../pin/struct.Pin.html
309     #[inline]
310     #[stable(feature = "pin", since = "1.33.0")]
311     pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
312         unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
313     }
314
315     /////////////////////////////////////////////////////////////////////////
316     // Getting to contained values
317     /////////////////////////////////////////////////////////////////////////
318
319     /// Unwraps an option, yielding the content of a [`Some`].
320     ///
321     /// # Panics
322     ///
323     /// Panics if the value is a [`None`] with a custom panic message provided by
324     /// `msg`.
325     ///
326     /// [`Some`]: #variant.Some
327     /// [`None`]: #variant.None
328     ///
329     /// # Examples
330     ///
331     /// ```
332     /// let x = Some("value");
333     /// assert_eq!(x.expect("the world is ending"), "value");
334     /// ```
335     ///
336     /// ```{.should_panic}
337     /// let x: Option<&str> = None;
338     /// x.expect("the world is ending"); // panics with `the world is ending`
339     /// ```
340     #[inline]
341     #[track_caller]
342     #[stable(feature = "rust1", since = "1.0.0")]
343     pub fn expect(self, msg: &str) -> T {
344         match self {
345             Some(val) => val,
346             None => expect_failed(msg),
347         }
348     }
349
350     /// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`].
351     ///
352     /// In general, because this function may panic, its use is discouraged.
353     /// Instead, prefer to use pattern matching and handle the [`None`]
354     /// case explicitly.
355     ///
356     /// # Panics
357     ///
358     /// Panics if the self value equals [`None`].
359     ///
360     /// [`Some(v)`]: #variant.Some
361     /// [`None`]: #variant.None
362     ///
363     /// # Examples
364     ///
365     /// ```
366     /// let x = Some("air");
367     /// assert_eq!(x.unwrap(), "air");
368     /// ```
369     ///
370     /// ```{.should_panic}
371     /// let x: Option<&str> = None;
372     /// assert_eq!(x.unwrap(), "air"); // fails
373     /// ```
374     #[inline]
375     #[track_caller]
376     #[stable(feature = "rust1", since = "1.0.0")]
377     pub fn unwrap(self) -> T {
378         match self {
379             Some(val) => val,
380             None => panic!("called `Option::unwrap()` on a `None` value"),
381         }
382     }
383
384     /// Returns the contained value or a default.
385     ///
386     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
387     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
388     /// which is lazily evaluated.
389     ///
390     /// [`unwrap_or_else`]: #method.unwrap_or_else
391     ///
392     /// # Examples
393     ///
394     /// ```
395     /// assert_eq!(Some("car").unwrap_or("bike"), "car");
396     /// assert_eq!(None.unwrap_or("bike"), "bike");
397     /// ```
398     #[inline]
399     #[stable(feature = "rust1", since = "1.0.0")]
400     pub fn unwrap_or(self, default: T) -> T {
401         match self {
402             Some(x) => x,
403             None => default,
404         }
405     }
406
407     /// Returns the contained value or computes it from a closure.
408     ///
409     /// # Examples
410     ///
411     /// ```
412     /// let k = 10;
413     /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
414     /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
415     /// ```
416     #[inline]
417     #[stable(feature = "rust1", since = "1.0.0")]
418     pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
419         match self {
420             Some(x) => x,
421             None => f(),
422         }
423     }
424
425     /////////////////////////////////////////////////////////////////////////
426     // Transforming contained values
427     /////////////////////////////////////////////////////////////////////////
428
429     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
430     ///
431     /// # Examples
432     ///
433     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
434     ///
435     /// [`String`]: ../../std/string/struct.String.html
436     /// [`usize`]: ../../std/primitive.usize.html
437     ///
438     /// ```
439     /// let maybe_some_string = Some(String::from("Hello, World!"));
440     /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
441     /// let maybe_some_len = maybe_some_string.map(|s| s.len());
442     ///
443     /// assert_eq!(maybe_some_len, Some(13));
444     /// ```
445     #[inline]
446     #[stable(feature = "rust1", since = "1.0.0")]
447     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
448         match self {
449             Some(x) => Some(f(x)),
450             None => None,
451         }
452     }
453
454     /// Applies a function to the contained value (if any),
455     /// or returns the provided default (if not).
456     ///
457     /// # Examples
458     ///
459     /// ```
460     /// let x = Some("foo");
461     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
462     ///
463     /// let x: Option<&str> = None;
464     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
465     /// ```
466     #[inline]
467     #[stable(feature = "rust1", since = "1.0.0")]
468     pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
469         match self {
470             Some(t) => f(t),
471             None => default,
472         }
473     }
474
475     /// Applies a function to the contained value (if any),
476     /// or computes a default (if not).
477     ///
478     /// # Examples
479     ///
480     /// ```
481     /// let k = 21;
482     ///
483     /// let x = Some("foo");
484     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
485     ///
486     /// let x: Option<&str> = None;
487     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
488     /// ```
489     #[inline]
490     #[stable(feature = "rust1", since = "1.0.0")]
491     pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
492         match self {
493             Some(t) => f(t),
494             None => default(),
495         }
496     }
497
498     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
499     /// [`Ok(v)`] and [`None`] to [`Err(err)`].
500     ///
501     /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
502     /// result of a function call, it is recommended to use [`ok_or_else`], which is
503     /// lazily evaluated.
504     ///
505     /// [`Result<T, E>`]: ../../std/result/enum.Result.html
506     /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
507     /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
508     /// [`None`]: #variant.None
509     /// [`Some(v)`]: #variant.Some
510     /// [`ok_or_else`]: #method.ok_or_else
511     ///
512     /// # Examples
513     ///
514     /// ```
515     /// let x = Some("foo");
516     /// assert_eq!(x.ok_or(0), Ok("foo"));
517     ///
518     /// let x: Option<&str> = None;
519     /// assert_eq!(x.ok_or(0), Err(0));
520     /// ```
521     #[inline]
522     #[stable(feature = "rust1", since = "1.0.0")]
523     pub fn ok_or<E>(self, err: E) -> Result<T, E> {
524         match self {
525             Some(v) => Ok(v),
526             None => Err(err),
527         }
528     }
529
530     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
531     /// [`Ok(v)`] and [`None`] to [`Err(err())`].
532     ///
533     /// [`Result<T, E>`]: ../../std/result/enum.Result.html
534     /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
535     /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
536     /// [`None`]: #variant.None
537     /// [`Some(v)`]: #variant.Some
538     ///
539     /// # Examples
540     ///
541     /// ```
542     /// let x = Some("foo");
543     /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
544     ///
545     /// let x: Option<&str> = None;
546     /// assert_eq!(x.ok_or_else(|| 0), Err(0));
547     /// ```
548     #[inline]
549     #[stable(feature = "rust1", since = "1.0.0")]
550     pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
551         match self {
552             Some(v) => Ok(v),
553             None => Err(err()),
554         }
555     }
556
557     /////////////////////////////////////////////////////////////////////////
558     // Iterator constructors
559     /////////////////////////////////////////////////////////////////////////
560
561     /// Returns an iterator over the possibly contained value.
562     ///
563     /// # Examples
564     ///
565     /// ```
566     /// let x = Some(4);
567     /// assert_eq!(x.iter().next(), Some(&4));
568     ///
569     /// let x: Option<u32> = None;
570     /// assert_eq!(x.iter().next(), None);
571     /// ```
572     #[inline]
573     #[stable(feature = "rust1", since = "1.0.0")]
574     pub fn iter(&self) -> Iter<'_, T> {
575         Iter { inner: Item { opt: self.as_ref() } }
576     }
577
578     /// Returns a mutable iterator over the possibly contained value.
579     ///
580     /// # Examples
581     ///
582     /// ```
583     /// let mut x = Some(4);
584     /// match x.iter_mut().next() {
585     ///     Some(v) => *v = 42,
586     ///     None => {},
587     /// }
588     /// assert_eq!(x, Some(42));
589     ///
590     /// let mut x: Option<u32> = None;
591     /// assert_eq!(x.iter_mut().next(), None);
592     /// ```
593     #[inline]
594     #[stable(feature = "rust1", since = "1.0.0")]
595     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
596         IterMut { inner: Item { opt: self.as_mut() } }
597     }
598
599     /////////////////////////////////////////////////////////////////////////
600     // Boolean operations on the values, eager and lazy
601     /////////////////////////////////////////////////////////////////////////
602
603     /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
604     ///
605     /// [`None`]: #variant.None
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// let x = Some(2);
611     /// let y: Option<&str> = None;
612     /// assert_eq!(x.and(y), None);
613     ///
614     /// let x: Option<u32> = None;
615     /// let y = Some("foo");
616     /// assert_eq!(x.and(y), None);
617     ///
618     /// let x = Some(2);
619     /// let y = Some("foo");
620     /// assert_eq!(x.and(y), Some("foo"));
621     ///
622     /// let x: Option<u32> = None;
623     /// let y: Option<&str> = None;
624     /// assert_eq!(x.and(y), None);
625     /// ```
626     #[inline]
627     #[stable(feature = "rust1", since = "1.0.0")]
628     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
629         match self {
630             Some(_) => optb,
631             None => None,
632         }
633     }
634
635     /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
636     /// wrapped value and returns the result.
637     ///
638     /// Some languages call this operation flatmap.
639     ///
640     /// [`None`]: #variant.None
641     ///
642     /// # Examples
643     ///
644     /// ```
645     /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
646     /// fn nope(_: u32) -> Option<u32> { None }
647     ///
648     /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
649     /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
650     /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
651     /// assert_eq!(None.and_then(sq).and_then(sq), None);
652     /// ```
653     #[inline]
654     #[stable(feature = "rust1", since = "1.0.0")]
655     pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
656         match self {
657             Some(x) => f(x),
658             None => None,
659         }
660     }
661
662     /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
663     /// with the wrapped value and returns:
664     ///
665     /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
666     ///   value), and
667     /// - [`None`] if `predicate` returns `false`.
668     ///
669     /// This function works similar to [`Iterator::filter()`]. You can imagine
670     /// the `Option<T>` being an iterator over one or zero elements. `filter()`
671     /// lets you decide which elements to keep.
672     ///
673     /// # Examples
674     ///
675     /// ```rust
676     /// fn is_even(n: &i32) -> bool {
677     ///     n % 2 == 0
678     /// }
679     ///
680     /// assert_eq!(None.filter(is_even), None);
681     /// assert_eq!(Some(3).filter(is_even), None);
682     /// assert_eq!(Some(4).filter(is_even), Some(4));
683     /// ```
684     ///
685     /// [`None`]: #variant.None
686     /// [`Some(t)`]: #variant.Some
687     /// [`Iterator::filter()`]: ../../std/iter/trait.Iterator.html#method.filter
688     #[inline]
689     #[stable(feature = "option_filter", since = "1.27.0")]
690     pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
691         if let Some(x) = self {
692             if predicate(&x) {
693                 return Some(x);
694             }
695         }
696         None
697     }
698
699     /// Returns the option if it contains a value, otherwise returns `optb`.
700     ///
701     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
702     /// result of a function call, it is recommended to use [`or_else`], which is
703     /// lazily evaluated.
704     ///
705     /// [`or_else`]: #method.or_else
706     ///
707     /// # Examples
708     ///
709     /// ```
710     /// let x = Some(2);
711     /// let y = None;
712     /// assert_eq!(x.or(y), Some(2));
713     ///
714     /// let x = None;
715     /// let y = Some(100);
716     /// assert_eq!(x.or(y), Some(100));
717     ///
718     /// let x = Some(2);
719     /// let y = Some(100);
720     /// assert_eq!(x.or(y), Some(2));
721     ///
722     /// let x: Option<u32> = None;
723     /// let y = None;
724     /// assert_eq!(x.or(y), None);
725     /// ```
726     #[inline]
727     #[stable(feature = "rust1", since = "1.0.0")]
728     pub fn or(self, optb: Option<T>) -> Option<T> {
729         match self {
730             Some(_) => self,
731             None => optb,
732         }
733     }
734
735     /// Returns the option if it contains a value, otherwise calls `f` and
736     /// returns the result.
737     ///
738     /// # Examples
739     ///
740     /// ```
741     /// fn nobody() -> Option<&'static str> { None }
742     /// fn vikings() -> Option<&'static str> { Some("vikings") }
743     ///
744     /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
745     /// assert_eq!(None.or_else(vikings), Some("vikings"));
746     /// assert_eq!(None.or_else(nobody), None);
747     /// ```
748     #[inline]
749     #[stable(feature = "rust1", since = "1.0.0")]
750     pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
751         match self {
752             Some(_) => self,
753             None => f(),
754         }
755     }
756
757     /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
758     ///
759     /// [`Some`]: #variant.Some
760     /// [`None`]: #variant.None
761     ///
762     /// # Examples
763     ///
764     /// ```
765     /// let x = Some(2);
766     /// let y: Option<u32> = None;
767     /// assert_eq!(x.xor(y), Some(2));
768     ///
769     /// let x: Option<u32> = None;
770     /// let y = Some(2);
771     /// assert_eq!(x.xor(y), Some(2));
772     ///
773     /// let x = Some(2);
774     /// let y = Some(2);
775     /// assert_eq!(x.xor(y), None);
776     ///
777     /// let x: Option<u32> = None;
778     /// let y: Option<u32> = None;
779     /// assert_eq!(x.xor(y), None);
780     /// ```
781     #[inline]
782     #[stable(feature = "option_xor", since = "1.37.0")]
783     pub fn xor(self, optb: Option<T>) -> Option<T> {
784         match (self, optb) {
785             (Some(a), None) => Some(a),
786             (None, Some(b)) => Some(b),
787             _ => None,
788         }
789     }
790
791     /////////////////////////////////////////////////////////////////////////
792     // Entry-like operations to insert if None and return a reference
793     /////////////////////////////////////////////////////////////////////////
794
795     /// Inserts `v` into the option if it is [`None`], then
796     /// returns a mutable reference to the contained value.
797     ///
798     /// [`None`]: #variant.None
799     ///
800     /// # Examples
801     ///
802     /// ```
803     /// let mut x = None;
804     ///
805     /// {
806     ///     let y: &mut u32 = x.get_or_insert(5);
807     ///     assert_eq!(y, &5);
808     ///
809     ///     *y = 7;
810     /// }
811     ///
812     /// assert_eq!(x, Some(7));
813     /// ```
814     #[inline]
815     #[stable(feature = "option_entry", since = "1.20.0")]
816     pub fn get_or_insert(&mut self, v: T) -> &mut T {
817         self.get_or_insert_with(|| v)
818     }
819
820     /// Inserts a value computed from `f` into the option if it is [`None`], then
821     /// returns a mutable reference to the contained value.
822     ///
823     /// [`None`]: #variant.None
824     ///
825     /// # Examples
826     ///
827     /// ```
828     /// let mut x = None;
829     ///
830     /// {
831     ///     let y: &mut u32 = x.get_or_insert_with(|| 5);
832     ///     assert_eq!(y, &5);
833     ///
834     ///     *y = 7;
835     /// }
836     ///
837     /// assert_eq!(x, Some(7));
838     /// ```
839     #[inline]
840     #[stable(feature = "option_entry", since = "1.20.0")]
841     pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
842         if let None = *self {
843             *self = Some(f());
844         }
845
846         match *self {
847             Some(ref mut v) => v,
848             None => unsafe { hint::unreachable_unchecked() },
849         }
850     }
851
852     /////////////////////////////////////////////////////////////////////////
853     // Misc
854     /////////////////////////////////////////////////////////////////////////
855
856     /// Takes the value out of the option, leaving a [`None`] in its place.
857     ///
858     /// [`None`]: #variant.None
859     ///
860     /// # Examples
861     ///
862     /// ```
863     /// let mut x = Some(2);
864     /// let y = x.take();
865     /// assert_eq!(x, None);
866     /// assert_eq!(y, Some(2));
867     ///
868     /// let mut x: Option<u32> = None;
869     /// let y = x.take();
870     /// assert_eq!(x, None);
871     /// assert_eq!(y, None);
872     /// ```
873     #[inline]
874     #[stable(feature = "rust1", since = "1.0.0")]
875     pub fn take(&mut self) -> Option<T> {
876         mem::take(self)
877     }
878
879     /// Replaces the actual value in the option by the value given in parameter,
880     /// returning the old value if present,
881     /// leaving a [`Some`] in its place without deinitializing either one.
882     ///
883     /// [`Some`]: #variant.Some
884     ///
885     /// # Examples
886     ///
887     /// ```
888     /// let mut x = Some(2);
889     /// let old = x.replace(5);
890     /// assert_eq!(x, Some(5));
891     /// assert_eq!(old, Some(2));
892     ///
893     /// let mut x = None;
894     /// let old = x.replace(3);
895     /// assert_eq!(x, Some(3));
896     /// assert_eq!(old, None);
897     /// ```
898     #[inline]
899     #[stable(feature = "option_replace", since = "1.31.0")]
900     pub fn replace(&mut self, value: T) -> Option<T> {
901         mem::replace(self, Some(value))
902     }
903 }
904
905 impl<T: Copy> Option<&T> {
906     /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
907     /// option.
908     ///
909     /// # Examples
910     ///
911     /// ```
912     /// let x = 12;
913     /// let opt_x = Some(&x);
914     /// assert_eq!(opt_x, Some(&12));
915     /// let copied = opt_x.copied();
916     /// assert_eq!(copied, Some(12));
917     /// ```
918     #[stable(feature = "copied", since = "1.35.0")]
919     pub fn copied(self) -> Option<T> {
920         self.map(|&t| t)
921     }
922 }
923
924 impl<T: Copy> Option<&mut T> {
925     /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
926     /// option.
927     ///
928     /// # Examples
929     ///
930     /// ```
931     /// let mut x = 12;
932     /// let opt_x = Some(&mut x);
933     /// assert_eq!(opt_x, Some(&mut 12));
934     /// let copied = opt_x.copied();
935     /// assert_eq!(copied, Some(12));
936     /// ```
937     #[stable(feature = "copied", since = "1.35.0")]
938     pub fn copied(self) -> Option<T> {
939         self.map(|&mut t| t)
940     }
941 }
942
943 impl<T: Clone> Option<&T> {
944     /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
945     /// option.
946     ///
947     /// # Examples
948     ///
949     /// ```
950     /// let x = 12;
951     /// let opt_x = Some(&x);
952     /// assert_eq!(opt_x, Some(&12));
953     /// let cloned = opt_x.cloned();
954     /// assert_eq!(cloned, Some(12));
955     /// ```
956     #[stable(feature = "rust1", since = "1.0.0")]
957     pub fn cloned(self) -> Option<T> {
958         self.map(|t| t.clone())
959     }
960 }
961
962 impl<T: Clone> Option<&mut T> {
963     /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
964     /// option.
965     ///
966     /// # Examples
967     ///
968     /// ```
969     /// let mut x = 12;
970     /// let opt_x = Some(&mut x);
971     /// assert_eq!(opt_x, Some(&mut 12));
972     /// let cloned = opt_x.cloned();
973     /// assert_eq!(cloned, Some(12));
974     /// ```
975     #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
976     pub fn cloned(self) -> Option<T> {
977         self.map(|t| t.clone())
978     }
979 }
980
981 impl<T: fmt::Debug> Option<T> {
982     /// Unwraps an option, expecting [`None`] and returning nothing.
983     ///
984     /// # Panics
985     ///
986     /// Panics if the value is a [`Some`], with a panic message including the
987     /// passed message, and the content of the [`Some`].
988     ///
989     /// [`Some`]: #variant.Some
990     /// [`None`]: #variant.None
991     ///
992     /// # Examples
993     ///
994     /// ```
995     /// #![feature(option_expect_none)]
996     ///
997     /// use std::collections::HashMap;
998     /// let mut squares = HashMap::new();
999     /// for i in -10..=10 {
1000     ///     // This will not panic, since all keys are unique.
1001     ///     squares.insert(i, i * i).expect_none("duplicate key");
1002     /// }
1003     /// ```
1004     ///
1005     /// ```{.should_panic}
1006     /// #![feature(option_expect_none)]
1007     ///
1008     /// use std::collections::HashMap;
1009     /// let mut sqrts = HashMap::new();
1010     /// for i in -10..=10 {
1011     ///     // This will panic, since both negative and positive `i` will
1012     ///     // insert the same `i * i` key, returning the old `Some(i)`.
1013     ///     sqrts.insert(i * i, i).expect_none("duplicate key");
1014     /// }
1015     /// ```
1016     #[inline]
1017     #[track_caller]
1018     #[unstable(feature = "option_expect_none", reason = "newly added", issue = "62633")]
1019     pub fn expect_none(self, msg: &str) {
1020         if let Some(val) = self {
1021             expect_none_failed(msg, &val);
1022         }
1023     }
1024
1025     /// Unwraps an option, expecting [`None`] and returning nothing.
1026     ///
1027     /// # Panics
1028     ///
1029     /// Panics if the value is a [`Some`], with a custom panic message provided
1030     /// by the [`Some`]'s value.
1031     ///
1032     /// [`Some(v)`]: #variant.Some
1033     /// [`None`]: #variant.None
1034     ///
1035     /// # Examples
1036     ///
1037     /// ```
1038     /// #![feature(option_unwrap_none)]
1039     ///
1040     /// use std::collections::HashMap;
1041     /// let mut squares = HashMap::new();
1042     /// for i in -10..=10 {
1043     ///     // This will not panic, since all keys are unique.
1044     ///     squares.insert(i, i * i).unwrap_none();
1045     /// }
1046     /// ```
1047     ///
1048     /// ```{.should_panic}
1049     /// #![feature(option_unwrap_none)]
1050     ///
1051     /// use std::collections::HashMap;
1052     /// let mut sqrts = HashMap::new();
1053     /// for i in -10..=10 {
1054     ///     // This will panic, since both negative and positive `i` will
1055     ///     // insert the same `i * i` key, returning the old `Some(i)`.
1056     ///     sqrts.insert(i * i, i).unwrap_none();
1057     /// }
1058     /// ```
1059     #[inline]
1060     #[track_caller]
1061     #[unstable(feature = "option_unwrap_none", reason = "newly added", issue = "62633")]
1062     pub fn unwrap_none(self) {
1063         if let Some(val) = self {
1064             expect_none_failed("called `Option::unwrap_none()` on a `Some` value", &val);
1065         }
1066     }
1067 }
1068
1069 impl<T: Default> Option<T> {
1070     /// Returns the contained value or a default
1071     ///
1072     /// Consumes the `self` argument then, if [`Some`], returns the contained
1073     /// value, otherwise if [`None`], returns the [default value] for that
1074     /// type.
1075     ///
1076     /// # Examples
1077     ///
1078     /// Converts a string to an integer, turning poorly-formed strings
1079     /// into 0 (the default value for integers). [`parse`] converts
1080     /// a string to any other type that implements [`FromStr`], returning
1081     /// [`None`] on error.
1082     ///
1083     /// ```
1084     /// let good_year_from_input = "1909";
1085     /// let bad_year_from_input = "190blarg";
1086     /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1087     /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1088     ///
1089     /// assert_eq!(1909, good_year);
1090     /// assert_eq!(0, bad_year);
1091     /// ```
1092     ///
1093     /// [`Some`]: #variant.Some
1094     /// [`None`]: #variant.None
1095     /// [default value]: ../default/trait.Default.html#tymethod.default
1096     /// [`parse`]: ../../std/primitive.str.html#method.parse
1097     /// [`FromStr`]: ../../std/str/trait.FromStr.html
1098     #[inline]
1099     #[stable(feature = "rust1", since = "1.0.0")]
1100     pub fn unwrap_or_default(self) -> T {
1101         match self {
1102             Some(x) => x,
1103             None => Default::default(),
1104         }
1105     }
1106 }
1107
1108 impl<T: Deref> Option<T> {
1109     /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1110     ///
1111     /// Leaves the original Option in-place, creating a new one with a reference
1112     /// to the original one, additionally coercing the contents via [`Deref`].
1113     ///
1114     /// [`Deref`]: ../../std/ops/trait.Deref.html
1115     ///
1116     /// # Examples
1117     ///
1118     /// ```
1119     /// let x: Option<String> = Some("hey".to_owned());
1120     /// assert_eq!(x.as_deref(), Some("hey"));
1121     ///
1122     /// let x: Option<String> = None;
1123     /// assert_eq!(x.as_deref(), None);
1124     /// ```
1125     #[stable(feature = "option_deref", since = "1.40.0")]
1126     pub fn as_deref(&self) -> Option<&T::Target> {
1127         self.as_ref().map(|t| t.deref())
1128     }
1129 }
1130
1131 impl<T: DerefMut> Option<T> {
1132     /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1133     ///
1134     /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1135     /// the inner type's `Deref::Target` type.
1136     ///
1137     /// # Examples
1138     ///
1139     /// ```
1140     /// let mut x: Option<String> = Some("hey".to_owned());
1141     /// assert_eq!(x.as_deref_mut().map(|x| {
1142     ///     x.make_ascii_uppercase();
1143     ///     x
1144     /// }), Some("HEY".to_owned().as_mut_str()));
1145     /// ```
1146     #[stable(feature = "option_deref", since = "1.40.0")]
1147     pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1148         self.as_mut().map(|t| t.deref_mut())
1149     }
1150 }
1151
1152 impl<T, E> Option<Result<T, E>> {
1153     /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1154     ///
1155     /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1156     /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1157     /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1158     ///
1159     /// [`None`]: #variant.None
1160     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
1161     /// [`Some`]: #variant.Some
1162     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1163     ///
1164     /// # Examples
1165     ///
1166     /// ```
1167     /// #[derive(Debug, Eq, PartialEq)]
1168     /// struct SomeErr;
1169     ///
1170     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1171     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1172     /// assert_eq!(x, y.transpose());
1173     /// ```
1174     #[inline]
1175     #[stable(feature = "transpose_result", since = "1.33.0")]
1176     pub fn transpose(self) -> Result<Option<T>, E> {
1177         match self {
1178             Some(Ok(x)) => Ok(Some(x)),
1179             Some(Err(e)) => Err(e),
1180             None => Ok(None),
1181         }
1182     }
1183 }
1184
1185 // This is a separate function to reduce the code size of .expect() itself.
1186 #[inline(never)]
1187 #[cold]
1188 #[track_caller]
1189 fn expect_failed(msg: &str) -> ! {
1190     panic!("{}", msg)
1191 }
1192
1193 // This is a separate function to reduce the code size of .expect_none() itself.
1194 #[inline(never)]
1195 #[cold]
1196 #[track_caller]
1197 fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
1198     panic!("{}: {:?}", msg, value)
1199 }
1200
1201 /////////////////////////////////////////////////////////////////////////////
1202 // Trait implementations
1203 /////////////////////////////////////////////////////////////////////////////
1204
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 impl<T: Clone> Clone for Option<T> {
1207     #[inline]
1208     fn clone(&self) -> Self {
1209         match self {
1210             Some(x) => Some(x.clone()),
1211             None => None,
1212         }
1213     }
1214
1215     #[inline]
1216     fn clone_from(&mut self, source: &Self) {
1217         match (self, source) {
1218             (Some(to), Some(from)) => to.clone_from(from),
1219             (to, from) => *to = from.clone(),
1220         }
1221     }
1222 }
1223
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 impl<T> Default for Option<T> {
1226     /// Returns [`None`][Option::None].
1227     ///
1228     /// # Examples
1229     ///
1230     /// ```
1231     /// let opt: Option<u32> = Option::default();
1232     /// assert!(opt.is_none());
1233     /// ```
1234     #[inline]
1235     fn default() -> Option<T> {
1236         None
1237     }
1238 }
1239
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 impl<T> IntoIterator for Option<T> {
1242     type Item = T;
1243     type IntoIter = IntoIter<T>;
1244
1245     /// Returns a consuming iterator over the possibly contained value.
1246     ///
1247     /// # Examples
1248     ///
1249     /// ```
1250     /// let x = Some("string");
1251     /// let v: Vec<&str> = x.into_iter().collect();
1252     /// assert_eq!(v, ["string"]);
1253     ///
1254     /// let x = None;
1255     /// let v: Vec<&str> = x.into_iter().collect();
1256     /// assert!(v.is_empty());
1257     /// ```
1258     #[inline]
1259     fn into_iter(self) -> IntoIter<T> {
1260         IntoIter { inner: Item { opt: self } }
1261     }
1262 }
1263
1264 #[stable(since = "1.4.0", feature = "option_iter")]
1265 impl<'a, T> IntoIterator for &'a Option<T> {
1266     type Item = &'a T;
1267     type IntoIter = Iter<'a, T>;
1268
1269     fn into_iter(self) -> Iter<'a, T> {
1270         self.iter()
1271     }
1272 }
1273
1274 #[stable(since = "1.4.0", feature = "option_iter")]
1275 impl<'a, T> IntoIterator for &'a mut Option<T> {
1276     type Item = &'a mut T;
1277     type IntoIter = IterMut<'a, T>;
1278
1279     fn into_iter(self) -> IterMut<'a, T> {
1280         self.iter_mut()
1281     }
1282 }
1283
1284 #[stable(since = "1.12.0", feature = "option_from")]
1285 impl<T> From<T> for Option<T> {
1286     fn from(val: T) -> Option<T> {
1287         Some(val)
1288     }
1289 }
1290
1291 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1292 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1293     fn from(o: &'a Option<T>) -> Option<&'a T> {
1294         o.as_ref()
1295     }
1296 }
1297
1298 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1299 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1300     fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1301         o.as_mut()
1302     }
1303 }
1304
1305 /////////////////////////////////////////////////////////////////////////////
1306 // The Option Iterators
1307 /////////////////////////////////////////////////////////////////////////////
1308
1309 #[derive(Clone, Debug)]
1310 struct Item<A> {
1311     opt: Option<A>,
1312 }
1313
1314 impl<A> Iterator for Item<A> {
1315     type Item = A;
1316
1317     #[inline]
1318     fn next(&mut self) -> Option<A> {
1319         self.opt.take()
1320     }
1321
1322     #[inline]
1323     fn size_hint(&self) -> (usize, Option<usize>) {
1324         match self.opt {
1325             Some(_) => (1, Some(1)),
1326             None => (0, Some(0)),
1327         }
1328     }
1329 }
1330
1331 impl<A> DoubleEndedIterator for Item<A> {
1332     #[inline]
1333     fn next_back(&mut self) -> Option<A> {
1334         self.opt.take()
1335     }
1336 }
1337
1338 impl<A> ExactSizeIterator for Item<A> {}
1339 impl<A> FusedIterator for Item<A> {}
1340 unsafe impl<A> TrustedLen for Item<A> {}
1341
1342 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1343 ///
1344 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1345 ///
1346 /// This `struct` is created by the [`Option::iter`] function.
1347 ///
1348 /// [`Option`]: enum.Option.html
1349 /// [`Some`]: enum.Option.html#variant.Some
1350 /// [`Option::iter`]: enum.Option.html#method.iter
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 #[derive(Debug)]
1353 pub struct Iter<'a, A: 'a> {
1354     inner: Item<&'a A>,
1355 }
1356
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 impl<'a, A> Iterator for Iter<'a, A> {
1359     type Item = &'a A;
1360
1361     #[inline]
1362     fn next(&mut self) -> Option<&'a A> {
1363         self.inner.next()
1364     }
1365     #[inline]
1366     fn size_hint(&self) -> (usize, Option<usize>) {
1367         self.inner.size_hint()
1368     }
1369 }
1370
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1373     #[inline]
1374     fn next_back(&mut self) -> Option<&'a A> {
1375         self.inner.next_back()
1376     }
1377 }
1378
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl<A> ExactSizeIterator for Iter<'_, A> {}
1381
1382 #[stable(feature = "fused", since = "1.26.0")]
1383 impl<A> FusedIterator for Iter<'_, A> {}
1384
1385 #[unstable(feature = "trusted_len", issue = "37572")]
1386 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1387
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 impl<A> Clone for Iter<'_, A> {
1390     #[inline]
1391     fn clone(&self) -> Self {
1392         Iter { inner: self.inner.clone() }
1393     }
1394 }
1395
1396 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1397 ///
1398 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1399 ///
1400 /// This `struct` is created by the [`Option::iter_mut`] function.
1401 ///
1402 /// [`Option`]: enum.Option.html
1403 /// [`Some`]: enum.Option.html#variant.Some
1404 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 #[derive(Debug)]
1407 pub struct IterMut<'a, A: 'a> {
1408     inner: Item<&'a mut A>,
1409 }
1410
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl<'a, A> Iterator for IterMut<'a, A> {
1413     type Item = &'a mut A;
1414
1415     #[inline]
1416     fn next(&mut self) -> Option<&'a mut A> {
1417         self.inner.next()
1418     }
1419     #[inline]
1420     fn size_hint(&self) -> (usize, Option<usize>) {
1421         self.inner.size_hint()
1422     }
1423 }
1424
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1427     #[inline]
1428     fn next_back(&mut self) -> Option<&'a mut A> {
1429         self.inner.next_back()
1430     }
1431 }
1432
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1435
1436 #[stable(feature = "fused", since = "1.26.0")]
1437 impl<A> FusedIterator for IterMut<'_, A> {}
1438 #[unstable(feature = "trusted_len", issue = "37572")]
1439 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1440
1441 /// An iterator over the value in [`Some`] variant of an [`Option`].
1442 ///
1443 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1444 ///
1445 /// This `struct` is created by the [`Option::into_iter`] function.
1446 ///
1447 /// [`Option`]: enum.Option.html
1448 /// [`Some`]: enum.Option.html#variant.Some
1449 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1450 #[derive(Clone, Debug)]
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 pub struct IntoIter<A> {
1453     inner: Item<A>,
1454 }
1455
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl<A> Iterator for IntoIter<A> {
1458     type Item = A;
1459
1460     #[inline]
1461     fn next(&mut self) -> Option<A> {
1462         self.inner.next()
1463     }
1464     #[inline]
1465     fn size_hint(&self) -> (usize, Option<usize>) {
1466         self.inner.size_hint()
1467     }
1468 }
1469
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 impl<A> DoubleEndedIterator for IntoIter<A> {
1472     #[inline]
1473     fn next_back(&mut self) -> Option<A> {
1474         self.inner.next_back()
1475     }
1476 }
1477
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl<A> ExactSizeIterator for IntoIter<A> {}
1480
1481 #[stable(feature = "fused", since = "1.26.0")]
1482 impl<A> FusedIterator for IntoIter<A> {}
1483
1484 #[unstable(feature = "trusted_len", issue = "37572")]
1485 unsafe impl<A> TrustedLen for IntoIter<A> {}
1486
1487 /////////////////////////////////////////////////////////////////////////////
1488 // FromIterator
1489 /////////////////////////////////////////////////////////////////////////////
1490
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1493     /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1494     /// no further elements are taken, and the [`None`][Option::None] is
1495     /// returned. Should no [`None`][Option::None] occur, a container with the
1496     /// values of each [`Option`] is returned.
1497     ///
1498     /// # Examples
1499     ///
1500     /// Here is an example which increments every integer in a vector.
1501     /// We use the checked variant of `add` that returns `None` when the
1502     /// calculation would result in an overflow.
1503     ///
1504     /// ```
1505     /// let items = vec![0_u16, 1, 2];
1506     ///
1507     /// let res: Option<Vec<u16>> = items
1508     ///     .iter()
1509     ///     .map(|x| x.checked_add(1))
1510     ///     .collect();
1511     ///
1512     /// assert_eq!(res, Some(vec![1, 2, 3]));
1513     /// ```
1514     ///
1515     /// As you can see, this will return the expected, valid items.
1516     ///
1517     /// Here is another example that tries to subtract one from another list
1518     /// of integers, this time checking for underflow:
1519     ///
1520     /// ```
1521     /// let items = vec![2_u16, 1, 0];
1522     ///
1523     /// let res: Option<Vec<u16>> = items
1524     ///     .iter()
1525     ///     .map(|x| x.checked_sub(1))
1526     ///     .collect();
1527     ///
1528     /// assert_eq!(res, None);
1529     /// ```
1530     ///
1531     /// Since the last element is zero, it would underflow. Thus, the resulting
1532     /// value is `None`.
1533     ///
1534     /// Here is a variation on the previous example, showing that no
1535     /// further elements are taken from `iter` after the first `None`.
1536     ///
1537     /// ```
1538     /// let items = vec![3_u16, 2, 1, 10];
1539     ///
1540     /// let mut shared = 0;
1541     ///
1542     /// let res: Option<Vec<u16>> = items
1543     ///     .iter()
1544     ///     .map(|x| { shared += x; x.checked_sub(2) })
1545     ///     .collect();
1546     ///
1547     /// assert_eq!(res, None);
1548     /// assert_eq!(shared, 6);
1549     /// ```
1550     ///
1551     /// Since the third element caused an underflow, no further elements were taken,
1552     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1553     ///
1554     /// [`Iterator`]: ../iter/trait.Iterator.html
1555     #[inline]
1556     fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1557         // FIXME(#11084): This could be replaced with Iterator::scan when this
1558         // performance bug is closed.
1559
1560         iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1561     }
1562 }
1563
1564 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1565 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1566 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1567 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1568 #[unstable(feature = "try_trait", issue = "42327")]
1569 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1570 pub struct NoneError;
1571
1572 #[unstable(feature = "try_trait", issue = "42327")]
1573 impl<T> ops::Try for Option<T> {
1574     type Ok = T;
1575     type Error = NoneError;
1576
1577     #[inline]
1578     fn into_result(self) -> Result<T, NoneError> {
1579         self.ok_or(NoneError)
1580     }
1581
1582     #[inline]
1583     fn from_ok(v: T) -> Self {
1584         Some(v)
1585     }
1586
1587     #[inline]
1588     fn from_error(_: NoneError) -> Self {
1589         None
1590     }
1591 }
1592
1593 impl<T> Option<Option<T>> {
1594     /// Converts from `Option<Option<T>>` to `Option<T>`
1595     ///
1596     /// # Examples
1597     /// Basic usage:
1598     /// ```
1599     /// let x: Option<Option<u32>> = Some(Some(6));
1600     /// assert_eq!(Some(6), x.flatten());
1601     ///
1602     /// let x: Option<Option<u32>> = Some(None);
1603     /// assert_eq!(None, x.flatten());
1604     ///
1605     /// let x: Option<Option<u32>> = None;
1606     /// assert_eq!(None, x.flatten());
1607     /// ```
1608     /// Flattening once only removes one level of nesting:
1609     /// ```
1610     /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1611     /// assert_eq!(Some(Some(6)), x.flatten());
1612     /// assert_eq!(Some(6), x.flatten().flatten());
1613     /// ```
1614     #[inline]
1615     #[stable(feature = "option_flattening", since = "1.40.0")]
1616     pub fn flatten(self) -> Option<T> {
1617         self.and_then(convert::identity)
1618     }
1619 }