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