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