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