]> git.lizzy.rs Git - rust.git/blob - src/libcore/option.rs
Merge pull request #20510 from tshepang/patch-6
[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 //! `int`. Notice that in order to use the inner `int` 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<int>> = None;
70 //! check_optional(&optional);
71 //!
72 //! let optional: Option<Box<int>> = Some(box 9000);
73 //! check_optional(&optional);
74 //!
75 //! fn check_optional(optional: &Option<Box<int>>) {
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(uint, &'static str), Animal(uint, &'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.iter() {
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]
145
146 use self::Option::*;
147
148 use cmp::{Eq, Ord};
149 use default::Default;
150 use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator};
151 use iter::{ExactSizeIterator};
152 use mem;
153 use result::Result;
154 use result::Result::{Ok, Err};
155 use slice;
156 use slice::AsSlice;
157 use clone::Clone;
158 use ops::{Deref, FnOnce};
159
160 // Note that this is not a lang item per se, but it has a hidden dependency on
161 // `Iterator`, which is one. The compiler assumes that the `next` method of
162 // `Iterator` is an enumeration with one type parameter and two variants,
163 // which basically means it must be `Option`.
164
165 /// The `Option` type.
166 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show, Hash)]
167 #[stable]
168 pub enum Option<T> {
169     /// No value
170     #[stable]
171     None,
172     /// Some value `T`
173     #[stable]
174     Some(T)
175 }
176
177 /////////////////////////////////////////////////////////////////////////////
178 // Type implementation
179 /////////////////////////////////////////////////////////////////////////////
180
181 impl<T> Option<T> {
182     /////////////////////////////////////////////////////////////////////////
183     // Querying the contained values
184     /////////////////////////////////////////////////////////////////////////
185
186     /// Returns `true` if the option is a `Some` value
187     ///
188     /// # Example
189     ///
190     /// ```
191     /// let x: Option<uint> = Some(2);
192     /// assert_eq!(x.is_some(), true);
193     ///
194     /// let x: Option<uint> = None;
195     /// assert_eq!(x.is_some(), false);
196     /// ```
197     #[inline]
198     #[stable]
199     pub fn is_some(&self) -> bool {
200         match *self {
201             Some(_) => true,
202             None => false
203         }
204     }
205
206     /// Returns `true` if the option is a `None` value
207     ///
208     /// # Example
209     ///
210     /// ```
211     /// let x: Option<uint> = Some(2);
212     /// assert_eq!(x.is_none(), false);
213     ///
214     /// let x: Option<uint> = None;
215     /// assert_eq!(x.is_none(), true);
216     /// ```
217     #[inline]
218     #[stable]
219     pub fn is_none(&self) -> bool {
220         !self.is_some()
221     }
222
223     /////////////////////////////////////////////////////////////////////////
224     // Adapter for working with references
225     /////////////////////////////////////////////////////////////////////////
226
227     /// Convert from `Option<T>` to `Option<&T>`
228     ///
229     /// # Example
230     ///
231     /// Convert an `Option<String>` into an `Option<int>`, preserving the original.
232     /// The `map` method takes the `self` argument by value, consuming the original,
233     /// so this technique uses `as_ref` to first take an `Option` to a reference
234     /// to the value inside the original.
235     ///
236     /// ```
237     /// let num_as_str: Option<String> = Some("10".to_string());
238     /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
239     /// // then consume *that* with `map`, leaving `num_as_str` on the stack.
240     /// let num_as_int: Option<uint> = num_as_str.as_ref().map(|n| n.len());
241     /// println!("still can print num_as_str: {}", num_as_str);
242     /// ```
243     #[inline]
244     #[stable]
245     pub fn as_ref<'r>(&'r self) -> Option<&'r T> {
246         match *self {
247             Some(ref x) => Some(x),
248             None => None
249         }
250     }
251
252     /// Convert from `Option<T>` to `Option<&mut T>`
253     ///
254     /// # Example
255     ///
256     /// ```
257     /// let mut x = Some(2u);
258     /// match x.as_mut() {
259     ///     Some(v) => *v = 42,
260     ///     None => {},
261     /// }
262     /// assert_eq!(x, Some(42u));
263     /// ```
264     #[inline]
265     #[stable]
266     pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
267         match *self {
268             Some(ref mut x) => Some(x),
269             None => None
270         }
271     }
272
273     /// Convert from `Option<T>` to `&mut [T]` (without copying)
274     ///
275     /// # Example
276     ///
277     /// ```
278     /// let mut x = Some("Diamonds");
279     /// {
280     ///     let v = x.as_mut_slice();
281     ///     assert!(v == ["Diamonds"]);
282     ///     v[0] = "Dirt";
283     ///     assert!(v == ["Dirt"]);
284     /// }
285     /// assert_eq!(x, Some("Dirt"));
286     /// ```
287     #[inline]
288     #[unstable = "waiting for mut conventions"]
289     pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
290         match *self {
291             Some(ref mut x) => {
292                 let result: &mut [T] = slice::mut_ref_slice(x);
293                 result
294             }
295             None => {
296                 let result: &mut [T] = &mut [];
297                 result
298             }
299         }
300     }
301
302     /////////////////////////////////////////////////////////////////////////
303     // Getting to contained values
304     /////////////////////////////////////////////////////////////////////////
305
306     /// Unwraps an option, yielding the content of a `Some`
307     ///
308     /// # Panics
309     ///
310     /// Panics if the value is a `None` with a custom panic message provided by
311     /// `msg`.
312     ///
313     /// # Example
314     ///
315     /// ```
316     /// let x = Some("value");
317     /// assert_eq!(x.expect("the world is ending"), "value");
318     /// ```
319     ///
320     /// ```{.should_fail}
321     /// let x: Option<&str> = None;
322     /// x.expect("the world is ending"); // panics with `world is ending`
323     /// ```
324     #[inline]
325     #[stable]
326     pub fn expect(self, msg: &str) -> T {
327         match self {
328             Some(val) => val,
329             None => panic!("{}", msg),
330         }
331     }
332
333     /// Returns the inner `T` of a `Some(T)`.
334     ///
335     /// # Panics
336     ///
337     /// Panics if the self value equals `None`.
338     ///
339     /// # Safety note
340     ///
341     /// In general, because this function may panic, its use is discouraged.
342     /// Instead, prefer to use pattern matching and handle the `None`
343     /// case explicitly.
344     ///
345     /// # Example
346     ///
347     /// ```
348     /// let x = Some("air");
349     /// assert_eq!(x.unwrap(), "air");
350     /// ```
351     ///
352     /// ```{.should_fail}
353     /// let x: Option<&str> = None;
354     /// assert_eq!(x.unwrap(), "air"); // fails
355     /// ```
356     #[inline]
357     #[stable]
358     pub fn unwrap(self) -> T {
359         match self {
360             Some(val) => val,
361             None => panic!("called `Option::unwrap()` on a `None` value"),
362         }
363     }
364
365     /// Returns the contained value or a default.
366     ///
367     /// # Example
368     ///
369     /// ```
370     /// assert_eq!(Some("car").unwrap_or("bike"), "car");
371     /// assert_eq!(None.unwrap_or("bike"), "bike");
372     /// ```
373     #[inline]
374     #[stable]
375     pub fn unwrap_or(self, def: T) -> T {
376         match self {
377             Some(x) => x,
378             None => def
379         }
380     }
381
382     /// Returns the contained value or computes it from a closure.
383     ///
384     /// # Example
385     ///
386     /// ```
387     /// let k = 10u;
388     /// assert_eq!(Some(4u).unwrap_or_else(|| 2 * k), 4u);
389     /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20u);
390     /// ```
391     #[inline]
392     #[stable]
393     pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
394         match self {
395             Some(x) => x,
396             None => f()
397         }
398     }
399
400     /////////////////////////////////////////////////////////////////////////
401     // Transforming contained values
402     /////////////////////////////////////////////////////////////////////////
403
404     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value
405     ///
406     /// # Example
407     ///
408     /// Convert an `Option<String>` into an `Option<uint>`, consuming the original:
409     ///
410     /// ```
411     /// let num_as_str: Option<String> = Some("10".to_string());
412     /// // `Option::map` takes self *by value*, consuming `num_as_str`
413     /// let num_as_int: Option<uint> = num_as_str.map(|n| n.len());
414     /// ```
415     #[inline]
416     #[stable]
417     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
418         match self {
419             Some(x) => Some(f(x)),
420             None => None
421         }
422     }
423
424     /// Applies a function to the contained value or returns a default.
425     ///
426     /// # Example
427     ///
428     /// ```
429     /// let x = Some("foo");
430     /// assert_eq!(x.map_or(42u, |v| v.len()), 3u);
431     ///
432     /// let x: Option<&str> = None;
433     /// assert_eq!(x.map_or(42u, |v| v.len()), 42u);
434     /// ```
435     #[inline]
436     #[stable]
437     pub fn map_or<U, F: FnOnce(T) -> U>(self, def: U, f: F) -> U {
438         match self {
439             Some(t) => f(t),
440             None => def
441         }
442     }
443
444     /// Applies a function to the contained value or computes a default.
445     ///
446     /// # Example
447     ///
448     /// ```
449     /// let k = 21u;
450     ///
451     /// let x = Some("foo");
452     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3u);
453     ///
454     /// let x: Option<&str> = None;
455     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42u);
456     /// ```
457     #[inline]
458     #[stable]
459     pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, def: D, f: F) -> U {
460         match self {
461             Some(t) => f(t),
462             None => def()
463         }
464     }
465
466     /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
467     /// `Ok(v)` and `None` to `Err(err)`.
468     ///
469     /// # Example
470     ///
471     /// ```
472     /// let x = Some("foo");
473     /// assert_eq!(x.ok_or(0i), Ok("foo"));
474     ///
475     /// let x: Option<&str> = None;
476     /// assert_eq!(x.ok_or(0i), Err(0i));
477     /// ```
478     #[inline]
479     #[experimental]
480     pub fn ok_or<E>(self, err: E) -> Result<T, E> {
481         match self {
482             Some(v) => Ok(v),
483             None => Err(err),
484         }
485     }
486
487     /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
488     /// `Ok(v)` and `None` to `Err(err())`.
489     ///
490     /// # Example
491     ///
492     /// ```
493     /// let x = Some("foo");
494     /// assert_eq!(x.ok_or_else(|| 0i), Ok("foo"));
495     ///
496     /// let x: Option<&str> = None;
497     /// assert_eq!(x.ok_or_else(|| 0i), Err(0i));
498     /// ```
499     #[inline]
500     #[experimental]
501     pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
502         match self {
503             Some(v) => Ok(v),
504             None => Err(err()),
505         }
506     }
507
508     /////////////////////////////////////////////////////////////////////////
509     // Iterator constructors
510     /////////////////////////////////////////////////////////////////////////
511
512     /// Returns an iterator over the possibly contained value.
513     ///
514     /// # Example
515     ///
516     /// ```
517     /// let x = Some(4u);
518     /// assert_eq!(x.iter().next(), Some(&4));
519     ///
520     /// let x: Option<uint> = None;
521     /// assert_eq!(x.iter().next(), None);
522     /// ```
523     #[inline]
524     #[stable]
525     pub fn iter(&self) -> Iter<T> {
526         Iter { inner: Item { opt: self.as_ref() } }
527     }
528
529     /// Returns a mutable iterator over the possibly contained value.
530     ///
531     /// # Example
532     ///
533     /// ```
534     /// let mut x = Some(4u);
535     /// match x.iter_mut().next() {
536     ///     Some(&ref mut v) => *v = 42u,
537     ///     None => {},
538     /// }
539     /// assert_eq!(x, Some(42));
540     ///
541     /// let mut x: Option<uint> = None;
542     /// assert_eq!(x.iter_mut().next(), None);
543     /// ```
544     #[inline]
545     #[unstable = "waiting for iterator conventions"]
546     pub fn iter_mut(&mut self) -> IterMut<T> {
547         IterMut { inner: Item { opt: self.as_mut() } }
548     }
549
550     /// Returns a consuming iterator over the possibly contained value.
551     ///
552     /// # Example
553     ///
554     /// ```
555     /// let x = Some("string");
556     /// let v: Vec<&str> = x.into_iter().collect();
557     /// assert_eq!(v, vec!["string"]);
558     ///
559     /// let x = None;
560     /// let v: Vec<&str> = x.into_iter().collect();
561     /// assert!(v.is_empty());
562     /// ```
563     #[inline]
564     #[stable]
565     pub fn into_iter(self) -> IntoIter<T> {
566         IntoIter { inner: Item { opt: self } }
567     }
568
569     /////////////////////////////////////////////////////////////////////////
570     // Boolean operations on the values, eager and lazy
571     /////////////////////////////////////////////////////////////////////////
572
573     /// Returns `None` if the option is `None`, otherwise returns `optb`.
574     ///
575     /// # Example
576     ///
577     /// ```
578     /// let x = Some(2u);
579     /// let y: Option<&str> = None;
580     /// assert_eq!(x.and(y), None);
581     ///
582     /// let x: Option<uint> = None;
583     /// let y = Some("foo");
584     /// assert_eq!(x.and(y), None);
585     ///
586     /// let x = Some(2u);
587     /// let y = Some("foo");
588     /// assert_eq!(x.and(y), Some("foo"));
589     ///
590     /// let x: Option<uint> = None;
591     /// let y: Option<&str> = None;
592     /// assert_eq!(x.and(y), None);
593     /// ```
594     #[inline]
595     #[stable]
596     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
597         match self {
598             Some(_) => optb,
599             None => None,
600         }
601     }
602
603     /// Returns `None` if the option is `None`, otherwise calls `f` with the
604     /// wrapped value and returns the result.
605     ///
606     /// # Example
607     ///
608     /// ```
609     /// fn sq(x: uint) -> Option<uint> { Some(x * x) }
610     /// fn nope(_: uint) -> Option<uint> { None }
611     ///
612     /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
613     /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
614     /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
615     /// assert_eq!(None.and_then(sq).and_then(sq), None);
616     /// ```
617     #[inline]
618     #[stable]
619     pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
620         match self {
621             Some(x) => f(x),
622             None => None,
623         }
624     }
625
626     /// Returns the option if it contains a value, otherwise returns `optb`.
627     ///
628     /// # Example
629     ///
630     /// ```
631     /// let x = Some(2u);
632     /// let y = None;
633     /// assert_eq!(x.or(y), Some(2u));
634     ///
635     /// let x = None;
636     /// let y = Some(100u);
637     /// assert_eq!(x.or(y), Some(100u));
638     ///
639     /// let x = Some(2u);
640     /// let y = Some(100u);
641     /// assert_eq!(x.or(y), Some(2u));
642     ///
643     /// let x: Option<uint> = None;
644     /// let y = None;
645     /// assert_eq!(x.or(y), None);
646     /// ```
647     #[inline]
648     #[stable]
649     pub fn or(self, optb: Option<T>) -> Option<T> {
650         match self {
651             Some(_) => self,
652             None => optb
653         }
654     }
655
656     /// Returns the option if it contains a value, otherwise calls `f` and
657     /// returns the result.
658     ///
659     /// # Example
660     ///
661     /// ```
662     /// fn nobody() -> Option<&'static str> { None }
663     /// fn vikings() -> Option<&'static str> { Some("vikings") }
664     ///
665     /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
666     /// assert_eq!(None.or_else(vikings), Some("vikings"));
667     /// assert_eq!(None.or_else(nobody), None);
668     /// ```
669     #[inline]
670     #[stable]
671     pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
672         match self {
673             Some(_) => self,
674             None => f()
675         }
676     }
677
678     /////////////////////////////////////////////////////////////////////////
679     // Misc
680     /////////////////////////////////////////////////////////////////////////
681
682     /// Takes the value out of the option, leaving a `None` in its place.
683     ///
684     /// # Example
685     ///
686     /// ```
687     /// let mut x = Some(2u);
688     /// x.take();
689     /// assert_eq!(x, None);
690     ///
691     /// let mut x: Option<uint> = None;
692     /// x.take();
693     /// assert_eq!(x, None);
694     /// ```
695     #[inline]
696     #[stable]
697     pub fn take(&mut self) -> Option<T> {
698         mem::replace(self, None)
699     }
700 }
701
702 impl<'a, T: Clone, D: Deref<Target=T>> Option<D> {
703     /// Maps an Option<D> to an Option<T> by dereffing and cloning the contents of the Option.
704     /// Useful for converting an Option<&T> to an Option<T>.
705     #[unstable = "recently added as part of collections reform"]
706     pub fn cloned(self) -> Option<T> {
707         self.map(|t| t.deref().clone())
708     }
709 }
710
711 impl<T: Default> Option<T> {
712     /// Returns the contained value or a default
713     ///
714     /// Consumes the `self` argument then, if `Some`, returns the contained
715     /// value, otherwise if `None`, returns the default value for that
716     /// type.
717     ///
718     /// # Example
719     ///
720     /// Convert a string to an integer, turning poorly-formed strings
721     /// into 0 (the default value for integers). `parse` converts
722     /// a string to any other type that implements `FromStr`, returning
723     /// `None` on error.
724     ///
725     /// ```
726     /// let good_year_from_input = "1909";
727     /// let bad_year_from_input = "190blarg";
728     /// let good_year = good_year_from_input.parse().unwrap_or_default();
729     /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
730     ///
731     /// assert_eq!(1909i, good_year);
732     /// assert_eq!(0i, bad_year);
733     /// ```
734     #[inline]
735     #[stable]
736     pub fn unwrap_or_default(self) -> T {
737         match self {
738             Some(x) => x,
739             None => Default::default()
740         }
741     }
742 }
743
744 /////////////////////////////////////////////////////////////////////////////
745 // Trait implementations
746 /////////////////////////////////////////////////////////////////////////////
747
748 #[unstable = "waiting on the stability of the trait itself"]
749 impl<T> AsSlice<T> for Option<T> {
750     /// Convert from `Option<T>` to `&[T]` (without copying)
751     #[inline]
752     fn as_slice<'a>(&'a self) -> &'a [T] {
753         match *self {
754             Some(ref x) => slice::ref_slice(x),
755             None => {
756                 let result: &[_] = &[];
757                 result
758             }
759         }
760     }
761 }
762
763 #[stable]
764 impl<T> Default for Option<T> {
765     #[stable]
766     #[inline]
767     #[stable]
768     fn default() -> Option<T> { None }
769 }
770
771 /////////////////////////////////////////////////////////////////////////////
772 // The Option Iterators
773 /////////////////////////////////////////////////////////////////////////////
774
775 #[derive(Clone)]
776 struct Item<A> {
777     opt: Option<A>
778 }
779
780 impl<A> Iterator for Item<A> {
781     type Item = A;
782
783     #[inline]
784     fn next(&mut self) -> Option<A> {
785         self.opt.take()
786     }
787
788     #[inline]
789     fn size_hint(&self) -> (uint, Option<uint>) {
790         match self.opt {
791             Some(_) => (1, Some(1)),
792             None => (0, Some(0)),
793         }
794     }
795 }
796
797 impl<A> DoubleEndedIterator for Item<A> {
798     #[inline]
799     fn next_back(&mut self) -> Option<A> {
800         self.opt.take()
801     }
802 }
803
804 impl<A> ExactSizeIterator for Item<A> {}
805
806 /// An iterator over a reference of the contained item in an Option.
807 #[stable]
808 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
809
810 impl<'a, A> Iterator for Iter<'a, A> {
811     type Item = &'a A;
812
813     #[inline]
814     fn next(&mut self) -> Option<&'a A> { self.inner.next() }
815     #[inline]
816     fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
817 }
818
819 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
820     #[inline]
821     fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
822 }
823
824 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
825
826 #[stable]
827 impl<'a, A> Clone for Iter<'a, A> {
828     fn clone(&self) -> Iter<'a, A> {
829         Iter { inner: self.inner.clone() }
830     }
831 }
832
833 /// An iterator over a mutable reference of the contained item in an Option.
834 #[stable]
835 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
836
837 impl<'a, A> Iterator for IterMut<'a, A> {
838     type Item = &'a mut A;
839
840     #[inline]
841     fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
842     #[inline]
843     fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
844 }
845
846 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
847     #[inline]
848     fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
849 }
850
851 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
852
853 /// An iterator over the item contained inside an Option.
854 #[stable]
855 pub struct IntoIter<A> { inner: Item<A> }
856
857 impl<A> Iterator for IntoIter<A> {
858     type Item = A;
859
860     #[inline]
861     fn next(&mut self) -> Option<A> { self.inner.next() }
862     #[inline]
863     fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
864 }
865
866 impl<A> DoubleEndedIterator for IntoIter<A> {
867     #[inline]
868     fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
869 }
870
871 impl<A> ExactSizeIterator for IntoIter<A> {}
872
873 /////////////////////////////////////////////////////////////////////////////
874 // FromIterator
875 /////////////////////////////////////////////////////////////////////////////
876
877 #[stable]
878 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
879     /// Takes each element in the `Iterator`: if it is `None`, no further
880     /// elements are taken, and the `None` is returned. Should no `None` occur, a
881     /// container with the values of each `Option` is returned.
882     ///
883     /// Here is an example which increments every integer in a vector,
884     /// checking for overflow:
885     ///
886     /// ```rust
887     /// use std::uint;
888     ///
889     /// let v = vec!(1u, 2u);
890     /// let res: Option<Vec<uint>> = v.iter().map(|&x: &uint|
891     ///     if x == uint::MAX { None }
892     ///     else { Some(x + 1) }
893     /// ).collect();
894     /// assert!(res == Some(vec!(2u, 3u)));
895     /// ```
896     #[inline]
897     #[stable]
898     fn from_iter<I: Iterator<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, 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 }