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