]> git.lizzy.rs Git - rust.git/blob - src/libcore/option.rs
Rollup merge of #31347 - GuillaumeGomez:fix_E0118, r=Manishearth
[rust.git] / src / libcore / option.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Optional values
12 //!
13 //! Type `Option` represents an optional value: every `Option`
14 //! is either `Some` and contains a value, or `None`, and
15 //! does not. `Option` types are very common in Rust code, as
16 //! they have a number of uses:
17 //!
18 //! * Initial values
19 //! * Return values for functions that are not defined
20 //!   over their entire input range (partial functions)
21 //! * Return value for otherwise reporting simple errors, where `None` is
22 //!   returned on error
23 //! * Optional struct fields
24 //! * Struct fields that can be loaned or "taken"
25 //! * Optional function arguments
26 //! * Nullable pointers
27 //! * Swapping things out of difficult situations
28 //!
29 //! Options are commonly paired with pattern matching to query the presence
30 //! of a value and take action, always accounting for the `None` case.
31 //!
32 //! ```
33 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
34 //!     if denominator == 0.0 {
35 //!         None
36 //!     } else {
37 //!         Some(numerator / denominator)
38 //!     }
39 //! }
40 //!
41 //! // The return value of the function is an option
42 //! let result = divide(2.0, 3.0);
43 //!
44 //! // Pattern match to retrieve the value
45 //! match result {
46 //!     // The division was valid
47 //!     Some(x) => println!("Result: {}", x),
48 //!     // The division was invalid
49 //!     None    => println!("Cannot divide by 0"),
50 //! }
51 //! ```
52 //!
53 //
54 // FIXME: Show how `Option` is used in practice, with lots of methods
55 //
56 //! # Options and pointers ("nullable" pointers)
57 //!
58 //! Rust's pointer types must always point to a valid location; there are
59 //! no "null" pointers. Instead, Rust has *optional* pointers, like
60 //! the optional owned box, `Option<Box<T>>`.
61 //!
62 //! The following example uses `Option` to create an optional box of
63 //! `i32`. Notice that in order to use the inner `i32` value first the
64 //! `check_optional` function needs to use pattern matching to
65 //! determine whether the box has a value (i.e. it is `Some(...)`) or
66 //! not (`None`).
67 //!
68 //! ```
69 //! let optional: Option<Box<i32>> = None;
70 //! check_optional(&optional);
71 //!
72 //! let optional: Option<Box<i32>> = Some(Box::new(9000));
73 //! check_optional(&optional);
74 //!
75 //! fn check_optional(optional: &Option<Box<i32>>) {
76 //!     match *optional {
77 //!         Some(ref p) => println!("have value {}", p),
78 //!         None => println!("have no value"),
79 //!     }
80 //! }
81 //! ```
82 //!
83 //! This usage of `Option` to create safe nullable pointers is so
84 //! common that Rust does special optimizations to make the
85 //! representation of `Option<Box<T>>` a single pointer. Optional pointers
86 //! in Rust are stored as efficiently as any other pointer type.
87 //!
88 //! # Examples
89 //!
90 //! Basic pattern matching on `Option`:
91 //!
92 //! ```
93 //! let msg = Some("howdy");
94 //!
95 //! // Take a reference to the contained string
96 //! match msg {
97 //!     Some(ref m) => println!("{}", *m),
98 //!     None => (),
99 //! }
100 //!
101 //! // Remove the contained string, destroying the Option
102 //! let unwrapped_msg = match msg {
103 //!     Some(m) => m,
104 //!     None => "default message",
105 //! };
106 //! ```
107 //!
108 //! Initialize a result to `None` before a loop:
109 //!
110 //! ```
111 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
112 //!
113 //! // A list of data to search through.
114 //! let all_the_big_things = [
115 //!     Kingdom::Plant(250, "redwood"),
116 //!     Kingdom::Plant(230, "noble fir"),
117 //!     Kingdom::Plant(229, "sugar pine"),
118 //!     Kingdom::Animal(25, "blue whale"),
119 //!     Kingdom::Animal(19, "fin whale"),
120 //!     Kingdom::Animal(15, "north pacific right whale"),
121 //! ];
122 //!
123 //! // We're going to search for the name of the biggest animal,
124 //! // but to start with we've just got `None`.
125 //! let mut name_of_biggest_animal = None;
126 //! let mut size_of_biggest_animal = 0;
127 //! for big_thing in &all_the_big_things {
128 //!     match *big_thing {
129 //!         Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
130 //!             // Now we've found the name of some big animal
131 //!             size_of_biggest_animal = size;
132 //!             name_of_biggest_animal = Some(name);
133 //!         }
134 //!         Kingdom::Animal(..) | Kingdom::Plant(..) => ()
135 //!     }
136 //! }
137 //!
138 //! match name_of_biggest_animal {
139 //!     Some(name) => println!("the biggest animal is {}", name),
140 //!     None => println!("there are no animals :("),
141 //! }
142 //! ```
143
144 #![stable(feature = "rust1", since = "1.0.0")]
145
146 use self::Option::*;
147
148 use clone::Clone;
149 use cmp::{Eq, Ord};
150 use default::Default;
151 use iter::ExactSizeIterator;
152 use iter::{Iterator, DoubleEndedIterator, FromIterator, IntoIterator};
153 use mem;
154 use ops::FnOnce;
155 use result::Result::{Ok, Err};
156 use result::Result;
157
158 // Note that this is not a lang item per se, but it has a hidden dependency on
159 // `Iterator`, which is one. The compiler assumes that the `next` method of
160 // `Iterator` is an enumeration with one type parameter and two variants,
161 // which basically means it must be `Option`.
162
163 /// The `Option` type. See [the module level documentation](index.html) for more.
164 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
165 #[stable(feature = "rust1", since = "1.0.0")]
166 pub enum Option<T> {
167     /// No value
168     #[stable(feature = "rust1", since = "1.0.0")]
169     None,
170     /// Some value `T`
171     #[stable(feature = "rust1", since = "1.0.0")]
172     Some(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] T)
173 }
174
175 /////////////////////////////////////////////////////////////////////////////
176 // Type implementation
177 /////////////////////////////////////////////////////////////////////////////
178
179 impl<T> Option<T> {
180     /////////////////////////////////////////////////////////////////////////
181     // Querying the contained values
182     /////////////////////////////////////////////////////////////////////////
183
184     /// Returns `true` if the option is a `Some` value
185     ///
186     /// # Examples
187     ///
188     /// ```
189     /// let x: Option<u32> = Some(2);
190     /// assert_eq!(x.is_some(), true);
191     ///
192     /// let x: Option<u32> = None;
193     /// assert_eq!(x.is_some(), false);
194     /// ```
195     #[inline]
196     #[stable(feature = "rust1", since = "1.0.0")]
197     pub fn is_some(&self) -> bool {
198         match *self {
199             Some(_) => true,
200             None => false,
201         }
202     }
203
204     /// Returns `true` if the option is a `None` value
205     ///
206     /// # Examples
207     ///
208     /// ```
209     /// let x: Option<u32> = Some(2);
210     /// assert_eq!(x.is_none(), false);
211     ///
212     /// let x: Option<u32> = None;
213     /// assert_eq!(x.is_none(), true);
214     /// ```
215     #[inline]
216     #[stable(feature = "rust1", since = "1.0.0")]
217     pub fn is_none(&self) -> bool {
218         !self.is_some()
219     }
220
221     /////////////////////////////////////////////////////////////////////////
222     // Adapter for working with references
223     /////////////////////////////////////////////////////////////////////////
224
225     /// Converts from `Option<T>` to `Option<&T>`
226     ///
227     /// # Examples
228     ///
229     /// Convert an `Option<String>` into an `Option<usize>`, preserving the original.
230     /// The `map` method takes the `self` argument by value, consuming the original,
231     /// so this technique uses `as_ref` to first take an `Option` to a reference
232     /// to the value inside the original.
233     ///
234     /// ```
235     /// let num_as_str: Option<String> = Some("10".to_string());
236     /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
237     /// // then consume *that* with `map`, leaving `num_as_str` on the stack.
238     /// let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len());
239     /// println!("still can print num_as_str: {:?}", num_as_str);
240     /// ```
241     #[inline]
242     #[stable(feature = "rust1", since = "1.0.0")]
243     pub fn as_ref(&self) -> Option<&T> {
244         match *self {
245             Some(ref x) => Some(x),
246             None => None,
247         }
248     }
249
250     /// Converts from `Option<T>` to `Option<&mut T>`
251     ///
252     /// # Examples
253     ///
254     /// ```
255     /// let mut x = Some(2);
256     /// match x.as_mut() {
257     ///     Some(v) => *v = 42,
258     ///     None => {},
259     /// }
260     /// assert_eq!(x, Some(42));
261     /// ```
262     #[inline]
263     #[stable(feature = "rust1", since = "1.0.0")]
264     pub fn as_mut(&mut self) -> Option<&mut T> {
265         match *self {
266             Some(ref mut x) => Some(x),
267             None => None,
268         }
269     }
270
271     /////////////////////////////////////////////////////////////////////////
272     // Getting to contained values
273     /////////////////////////////////////////////////////////////////////////
274
275     /// Unwraps an option, yielding the content of a `Some`.
276     ///
277     /// # Panics
278     ///
279     /// Panics if the value is a `None` with a custom panic message provided by
280     /// `msg`.
281     ///
282     /// # Examples
283     ///
284     /// ```
285     /// let x = Some("value");
286     /// assert_eq!(x.expect("the world is ending"), "value");
287     /// ```
288     ///
289     /// ```{.should_panic}
290     /// let x: Option<&str> = None;
291     /// x.expect("the world is ending"); // panics with `the world is ending`
292     /// ```
293     #[inline]
294     #[stable(feature = "rust1", since = "1.0.0")]
295     pub fn expect(self, msg: &str) -> T {
296         match self {
297             Some(val) => val,
298             None => expect_failed(msg),
299         }
300     }
301
302     /// Moves the value `v` out of the `Option<T>` if it is `Some(v)`.
303     ///
304     /// # Panics
305     ///
306     /// Panics if the self value equals `None`.
307     ///
308     /// # Safety note
309     ///
310     /// In general, because this function may panic, its use is discouraged.
311     /// Instead, prefer to use pattern matching and handle the `None`
312     /// case explicitly.
313     ///
314     /// # Examples
315     ///
316     /// ```
317     /// let x = Some("air");
318     /// assert_eq!(x.unwrap(), "air");
319     /// ```
320     ///
321     /// ```{.should_panic}
322     /// let x: Option<&str> = None;
323     /// assert_eq!(x.unwrap(), "air"); // fails
324     /// ```
325     #[inline]
326     #[stable(feature = "rust1", since = "1.0.0")]
327     pub fn unwrap(self) -> T {
328         match self {
329             Some(val) => val,
330             None => panic!("called `Option::unwrap()` on a `None` value"),
331         }
332     }
333
334     /// Returns the contained value or a default.
335     ///
336     /// # Examples
337     ///
338     /// ```
339     /// assert_eq!(Some("car").unwrap_or("bike"), "car");
340     /// assert_eq!(None.unwrap_or("bike"), "bike");
341     /// ```
342     #[inline]
343     #[stable(feature = "rust1", since = "1.0.0")]
344     pub fn unwrap_or(self, def: T) -> T {
345         match self {
346             Some(x) => x,
347             None => def,
348         }
349     }
350
351     /// Returns the contained value or computes it from a closure.
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// let k = 10;
357     /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
358     /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
359     /// ```
360     #[inline]
361     #[stable(feature = "rust1", since = "1.0.0")]
362     pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
363         match self {
364             Some(x) => x,
365             None => f(),
366         }
367     }
368
369     /////////////////////////////////////////////////////////////////////////
370     // Transforming contained values
371     /////////////////////////////////////////////////////////////////////////
372
373     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value
374     ///
375     /// # Examples
376     ///
377     /// Convert an `Option<String>` into an `Option<usize>`, consuming the original:
378     ///
379     /// ```
380     /// let maybe_some_string = Some(String::from("Hello, World!"));
381     /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
382     /// let maybe_some_len = maybe_some_string.map(|s| s.len());
383     ///
384     /// assert_eq!(maybe_some_len, Some(13));
385     /// ```
386     #[inline]
387     #[stable(feature = "rust1", since = "1.0.0")]
388     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
389         match self {
390             Some(x) => Some(f(x)),
391             None => None,
392         }
393     }
394
395     /// Applies a function to the contained value (if any),
396     /// or returns a `default` (if not).
397     ///
398     /// # Examples
399     ///
400     /// ```
401     /// let x = Some("foo");
402     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
403     ///
404     /// let x: Option<&str> = None;
405     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
406     /// ```
407     #[inline]
408     #[stable(feature = "rust1", since = "1.0.0")]
409     pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
410         match self {
411             Some(t) => f(t),
412             None => default,
413         }
414     }
415
416     /// Applies a function to the contained value (if any),
417     /// or computes a `default` (if not).
418     ///
419     /// # Examples
420     ///
421     /// ```
422     /// let k = 21;
423     ///
424     /// let x = Some("foo");
425     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
426     ///
427     /// let x: Option<&str> = None;
428     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
429     /// ```
430     #[inline]
431     #[stable(feature = "rust1", since = "1.0.0")]
432     pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
433         match self {
434             Some(t) => f(t),
435             None => default(),
436         }
437     }
438
439     /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
440     /// `Ok(v)` and `None` to `Err(err)`.
441     ///
442     /// # Examples
443     ///
444     /// ```
445     /// let x = Some("foo");
446     /// assert_eq!(x.ok_or(0), Ok("foo"));
447     ///
448     /// let x: Option<&str> = None;
449     /// assert_eq!(x.ok_or(0), Err(0));
450     /// ```
451     #[inline]
452     #[stable(feature = "rust1", since = "1.0.0")]
453     pub fn ok_or<E>(self, err: E) -> Result<T, E> {
454         match self {
455             Some(v) => Ok(v),
456             None => Err(err),
457         }
458     }
459
460     /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
461     /// `Ok(v)` and `None` to `Err(err())`.
462     ///
463     /// # Examples
464     ///
465     /// ```
466     /// let x = Some("foo");
467     /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
468     ///
469     /// let x: Option<&str> = None;
470     /// assert_eq!(x.ok_or_else(|| 0), Err(0));
471     /// ```
472     #[inline]
473     #[stable(feature = "rust1", since = "1.0.0")]
474     pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
475         match self {
476             Some(v) => Ok(v),
477             None => Err(err()),
478         }
479     }
480
481     /////////////////////////////////////////////////////////////////////////
482     // Iterator constructors
483     /////////////////////////////////////////////////////////////////////////
484
485     /// Returns an iterator over the possibly contained value.
486     ///
487     /// # Examples
488     ///
489     /// ```
490     /// let x = Some(4);
491     /// assert_eq!(x.iter().next(), Some(&4));
492     ///
493     /// let x: Option<u32> = None;
494     /// assert_eq!(x.iter().next(), None);
495     /// ```
496     #[inline]
497     #[stable(feature = "rust1", since = "1.0.0")]
498     pub fn iter(&self) -> Iter<T> {
499         Iter { inner: Item { opt: self.as_ref() } }
500     }
501
502     /// Returns a mutable iterator over the possibly contained value.
503     ///
504     /// # Examples
505     ///
506     /// ```
507     /// let mut x = Some(4);
508     /// match x.iter_mut().next() {
509     ///     Some(v) => *v = 42,
510     ///     None => {},
511     /// }
512     /// assert_eq!(x, Some(42));
513     ///
514     /// let mut x: Option<u32> = None;
515     /// assert_eq!(x.iter_mut().next(), None);
516     /// ```
517     #[inline]
518     #[stable(feature = "rust1", since = "1.0.0")]
519     pub fn iter_mut(&mut self) -> IterMut<T> {
520         IterMut { inner: Item { opt: self.as_mut() } }
521     }
522
523     /////////////////////////////////////////////////////////////////////////
524     // Boolean operations on the values, eager and lazy
525     /////////////////////////////////////////////////////////////////////////
526
527     /// Returns `None` if the option is `None`, otherwise returns `optb`.
528     ///
529     /// # Examples
530     ///
531     /// ```
532     /// let x = Some(2);
533     /// let y: Option<&str> = None;
534     /// assert_eq!(x.and(y), None);
535     ///
536     /// let x: Option<u32> = None;
537     /// let y = Some("foo");
538     /// assert_eq!(x.and(y), None);
539     ///
540     /// let x = Some(2);
541     /// let y = Some("foo");
542     /// assert_eq!(x.and(y), Some("foo"));
543     ///
544     /// let x: Option<u32> = None;
545     /// let y: Option<&str> = None;
546     /// assert_eq!(x.and(y), None);
547     /// ```
548     #[inline]
549     #[stable(feature = "rust1", since = "1.0.0")]
550     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
551         match self {
552             Some(_) => optb,
553             None => None,
554         }
555     }
556
557     /// Returns `None` if the option is `None`, otherwise calls `f` with the
558     /// wrapped value and returns the result.
559     ///
560     /// Some languages call this operation flatmap.
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
566     /// fn nope(_: u32) -> Option<u32> { None }
567     ///
568     /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
569     /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
570     /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
571     /// assert_eq!(None.and_then(sq).and_then(sq), None);
572     /// ```
573     #[inline]
574     #[stable(feature = "rust1", since = "1.0.0")]
575     pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
576         match self {
577             Some(x) => f(x),
578             None => None,
579         }
580     }
581
582     /// Returns the option if it contains a value, otherwise returns `optb`.
583     ///
584     /// # Examples
585     ///
586     /// ```
587     /// let x = Some(2);
588     /// let y = None;
589     /// assert_eq!(x.or(y), Some(2));
590     ///
591     /// let x = None;
592     /// let y = Some(100);
593     /// assert_eq!(x.or(y), Some(100));
594     ///
595     /// let x = Some(2);
596     /// let y = Some(100);
597     /// assert_eq!(x.or(y), Some(2));
598     ///
599     /// let x: Option<u32> = None;
600     /// let y = None;
601     /// assert_eq!(x.or(y), None);
602     /// ```
603     #[inline]
604     #[stable(feature = "rust1", since = "1.0.0")]
605     pub fn or(self, optb: Option<T>) -> Option<T> {
606         match self {
607             Some(_) => self,
608             None => optb,
609         }
610     }
611
612     /// Returns the option if it contains a value, otherwise calls `f` and
613     /// returns the result.
614     ///
615     /// # Examples
616     ///
617     /// ```
618     /// fn nobody() -> Option<&'static str> { None }
619     /// fn vikings() -> Option<&'static str> { Some("vikings") }
620     ///
621     /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
622     /// assert_eq!(None.or_else(vikings), Some("vikings"));
623     /// assert_eq!(None.or_else(nobody), None);
624     /// ```
625     #[inline]
626     #[stable(feature = "rust1", since = "1.0.0")]
627     pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
628         match self {
629             Some(_) => self,
630             None => f(),
631         }
632     }
633
634     /////////////////////////////////////////////////////////////////////////
635     // Misc
636     /////////////////////////////////////////////////////////////////////////
637
638     /// Takes the value out of the option, leaving a `None` in its place.
639     ///
640     /// # Examples
641     ///
642     /// ```
643     /// let mut x = Some(2);
644     /// x.take();
645     /// assert_eq!(x, None);
646     ///
647     /// let mut x: Option<u32> = None;
648     /// x.take();
649     /// assert_eq!(x, None);
650     /// ```
651     #[inline]
652     #[stable(feature = "rust1", since = "1.0.0")]
653     pub fn take(&mut self) -> Option<T> {
654         mem::replace(self, None)
655     }
656 }
657
658 impl<'a, T: Clone> Option<&'a T> {
659     /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
660     /// option.
661     #[stable(feature = "rust1", since = "1.0.0")]
662     pub fn cloned(self) -> Option<T> {
663         self.map(|t| t.clone())
664     }
665 }
666
667 impl<T: Default> Option<T> {
668     /// Returns the contained value or a default
669     ///
670     /// Consumes the `self` argument then, if `Some`, returns the contained
671     /// value, otherwise if `None`, returns the default value for that
672     /// type.
673     ///
674     /// # Examples
675     ///
676     /// Convert a string to an integer, turning poorly-formed strings
677     /// into 0 (the default value for integers). `parse` converts
678     /// a string to any other type that implements `FromStr`, returning
679     /// `None` on error.
680     ///
681     /// ```
682     /// let good_year_from_input = "1909";
683     /// let bad_year_from_input = "190blarg";
684     /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
685     /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
686     ///
687     /// assert_eq!(1909, good_year);
688     /// assert_eq!(0, bad_year);
689     /// ```
690     #[inline]
691     #[stable(feature = "rust1", since = "1.0.0")]
692     pub fn unwrap_or_default(self) -> T {
693         match self {
694             Some(x) => x,
695             None => Default::default(),
696         }
697     }
698 }
699
700 // This is a separate function to reduce the code size of .expect() itself.
701 #[inline(never)]
702 #[cold]
703 fn expect_failed(msg: &str) -> ! {
704     panic!("{}", msg)
705 }
706
707
708 /////////////////////////////////////////////////////////////////////////////
709 // Trait implementations
710 /////////////////////////////////////////////////////////////////////////////
711
712 #[stable(feature = "rust1", since = "1.0.0")]
713 impl<T> Default for Option<T> {
714     #[inline]
715     fn default() -> Option<T> { None }
716 }
717
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl<T> IntoIterator for Option<T> {
720     type Item = T;
721     type IntoIter = IntoIter<T>;
722
723     /// Returns a consuming iterator over the possibly contained value.
724     ///
725     /// # Examples
726     ///
727     /// ```
728     /// let x = Some("string");
729     /// let v: Vec<&str> = x.into_iter().collect();
730     /// assert_eq!(v, ["string"]);
731     ///
732     /// let x = None;
733     /// let v: Vec<&str> = x.into_iter().collect();
734     /// assert!(v.is_empty());
735     /// ```
736     #[inline]
737     fn into_iter(self) -> IntoIter<T> {
738         IntoIter { inner: Item { opt: self } }
739     }
740 }
741
742 #[stable(since = "1.4.0", feature = "option_iter")]
743 impl<'a, T> IntoIterator for &'a Option<T> {
744     type Item = &'a T;
745     type IntoIter = Iter<'a, T>;
746
747     fn into_iter(self) -> Iter<'a, T> {
748         self.iter()
749     }
750 }
751
752 #[stable(since = "1.4.0", feature = "option_iter")]
753 impl<'a, T> IntoIterator for &'a mut Option<T> {
754     type Item = &'a mut T;
755     type IntoIter = IterMut<'a, T>;
756
757     fn into_iter(mut self) -> IterMut<'a, T> {
758         self.iter_mut()
759     }
760 }
761
762 /////////////////////////////////////////////////////////////////////////////
763 // The Option Iterators
764 /////////////////////////////////////////////////////////////////////////////
765
766 #[derive(Clone)]
767 struct Item<A> {
768     opt: Option<A>
769 }
770
771 impl<A> Iterator for Item<A> {
772     type Item = A;
773
774     #[inline]
775     fn next(&mut self) -> Option<A> {
776         self.opt.take()
777     }
778
779     #[inline]
780     fn size_hint(&self) -> (usize, Option<usize>) {
781         match self.opt {
782             Some(_) => (1, Some(1)),
783             None => (0, Some(0)),
784         }
785     }
786 }
787
788 impl<A> DoubleEndedIterator for Item<A> {
789     #[inline]
790     fn next_back(&mut self) -> Option<A> {
791         self.opt.take()
792     }
793 }
794
795 impl<A> ExactSizeIterator for Item<A> {}
796
797 /// An iterator over a reference of the contained item in an Option.
798 #[stable(feature = "rust1", since = "1.0.0")]
799 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
800
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl<'a, A> Iterator for Iter<'a, A> {
803     type Item = &'a A;
804
805     #[inline]
806     fn next(&mut self) -> Option<&'a A> { self.inner.next() }
807     #[inline]
808     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
809 }
810
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
813     #[inline]
814     fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
815 }
816
817 #[stable(feature = "rust1", since = "1.0.0")]
818 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
819
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl<'a, A> Clone for Iter<'a, A> {
822     fn clone(&self) -> Iter<'a, A> {
823         Iter { inner: self.inner.clone() }
824     }
825 }
826
827 /// An iterator over a mutable reference of the contained item in an Option.
828 #[stable(feature = "rust1", since = "1.0.0")]
829 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
830
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl<'a, A> Iterator for IterMut<'a, A> {
833     type Item = &'a mut A;
834
835     #[inline]
836     fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
837     #[inline]
838     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
839 }
840
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
843     #[inline]
844     fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
845 }
846
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
849
850 /// An iterator over the item contained inside an Option.
851 #[derive(Clone)]
852 #[stable(feature = "rust1", since = "1.0.0")]
853 pub struct IntoIter<A> { inner: Item<A> }
854
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl<A> Iterator for IntoIter<A> {
857     type Item = A;
858
859     #[inline]
860     fn next(&mut self) -> Option<A> { self.inner.next() }
861     #[inline]
862     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
863 }
864
865 #[stable(feature = "rust1", since = "1.0.0")]
866 impl<A> DoubleEndedIterator for IntoIter<A> {
867     #[inline]
868     fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
869 }
870
871 #[stable(feature = "rust1", since = "1.0.0")]
872 impl<A> ExactSizeIterator for IntoIter<A> {}
873
874 /////////////////////////////////////////////////////////////////////////////
875 // FromIterator
876 /////////////////////////////////////////////////////////////////////////////
877
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
880     /// Takes each element in the `Iterator`: if it is `None`, no further
881     /// elements are taken, and the `None` is returned. Should no `None` occur, a
882     /// container with the values of each `Option` is returned.
883     ///
884     /// Here is an example which increments every integer in a vector,
885     /// checking for overflow:
886     ///
887     /// ```
888     /// use std::u16;
889     ///
890     /// let v = vec!(1, 2);
891     /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
892     ///     if x == u16::MAX { None }
893     ///     else { Some(x + 1) }
894     /// ).collect();
895     /// assert!(res == Some(vec!(2, 3)));
896     /// ```
897     #[inline]
898     fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
899         // FIXME(#11084): This could be replaced with Iterator::scan when this
900         // performance bug is closed.
901
902         struct Adapter<Iter> {
903             iter: Iter,
904             found_none: bool,
905         }
906
907         impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
908             type Item = T;
909
910             #[inline]
911             fn next(&mut self) -> Option<T> {
912                 match self.iter.next() {
913                     Some(Some(value)) => Some(value),
914                     Some(None) => {
915                         self.found_none = true;
916                         None
917                     }
918                     None => None,
919                 }
920             }
921         }
922
923         let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
924         let v: V = FromIterator::from_iter(adapter.by_ref());
925
926         if adapter.found_none {
927             None
928         } else {
929             Some(v)
930         }
931     }
932 }