]> git.proxmox.com Git - rustc.git/blob - src/libcore/option.rs
Imported Upstream version 1.3.0+dfsg1
[rustc.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<'r>(&'r self) -> Option<&'r 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<'r>(&'r mut self) -> Option<&'r 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 pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
292 match *self {
293 Some(ref mut x) => {
294 let result: &mut [T] = slice::mut_ref_slice(x);
295 result
296 }
297 None => {
298 let result: &mut [T] = &mut [];
299 result
300 }
301 }
302 }
303
304 /////////////////////////////////////////////////////////////////////////
305 // Getting to contained values
306 /////////////////////////////////////////////////////////////////////////
307
308 /// Unwraps an option, yielding the content of a `Some`
309 ///
310 /// # Panics
311 ///
312 /// Panics if the value is a `None` with a custom panic message provided by
313 /// `msg`.
314 ///
315 /// # Examples
316 ///
317 /// ```
318 /// let x = Some("value");
319 /// assert_eq!(x.expect("the world is ending"), "value");
320 /// ```
321 ///
322 /// ```{.should_panic}
323 /// let x: Option<&str> = None;
324 /// x.expect("the world is ending"); // panics with `the world is ending`
325 /// ```
326 #[inline]
327 #[stable(feature = "rust1", since = "1.0.0")]
328 pub fn expect(self, msg: &str) -> T {
329 match self {
330 Some(val) => val,
331 None => panic!("{}", msg),
332 }
333 }
334
335 /// Moves the value `v` out of the `Option<T>` if it is `Some(v)`.
336 ///
337 /// # Panics
338 ///
339 /// Panics if the self value equals `None`.
340 ///
341 /// # Safety note
342 ///
343 /// In general, because this function may panic, its use is discouraged.
344 /// Instead, prefer to use pattern matching and handle the `None`
345 /// case explicitly.
346 ///
347 /// # Examples
348 ///
349 /// ```
350 /// let x = Some("air");
351 /// assert_eq!(x.unwrap(), "air");
352 /// ```
353 ///
354 /// ```{.should_panic}
355 /// let x: Option<&str> = None;
356 /// assert_eq!(x.unwrap(), "air"); // fails
357 /// ```
358 #[inline]
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn unwrap(self) -> T {
361 match self {
362 Some(val) => val,
363 None => panic!("called `Option::unwrap()` on a `None` value"),
364 }
365 }
366
367 /// Returns the contained value or a default.
368 ///
369 /// # Examples
370 ///
371 /// ```
372 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
373 /// assert_eq!(None.unwrap_or("bike"), "bike");
374 /// ```
375 #[inline]
376 #[stable(feature = "rust1", since = "1.0.0")]
377 pub fn unwrap_or(self, def: T) -> T {
378 match self {
379 Some(x) => x,
380 None => def,
381 }
382 }
383
384 /// Returns the contained value or computes it from a closure.
385 ///
386 /// # Examples
387 ///
388 /// ```
389 /// let k = 10;
390 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
391 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
392 /// ```
393 #[inline]
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
396 match self {
397 Some(x) => x,
398 None => f(),
399 }
400 }
401
402 /////////////////////////////////////////////////////////////////////////
403 // Transforming contained values
404 /////////////////////////////////////////////////////////////////////////
405
406 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value
407 ///
408 /// # Examples
409 ///
410 /// Convert an `Option<String>` into an `Option<usize>`, consuming the original:
411 ///
412 /// ```
413 /// let maybe_some_string = Some(String::from("Hello, World!"));
414 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
415 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
416 ///
417 /// assert_eq!(maybe_some_len, Some(13));
418 /// ```
419 #[inline]
420 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
422 match self {
423 Some(x) => Some(f(x)),
424 None => None,
425 }
426 }
427
428 /// Applies a function to the contained value (if any),
429 /// or returns a `default` (if not).
430 ///
431 /// # Examples
432 ///
433 /// ```
434 /// let x = Some("foo");
435 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
436 ///
437 /// let x: Option<&str> = None;
438 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
439 /// ```
440 #[inline]
441 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
443 match self {
444 Some(t) => f(t),
445 None => default,
446 }
447 }
448
449 /// Applies a function to the contained value (if any),
450 /// or computes a `default` (if not).
451 ///
452 /// # Examples
453 ///
454 /// ```
455 /// let k = 21;
456 ///
457 /// let x = Some("foo");
458 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
459 ///
460 /// let x: Option<&str> = None;
461 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
462 /// ```
463 #[inline]
464 #[stable(feature = "rust1", since = "1.0.0")]
465 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
466 match self {
467 Some(t) => f(t),
468 None => default(),
469 }
470 }
471
472 /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
473 /// `Ok(v)` and `None` to `Err(err)`.
474 ///
475 /// # Examples
476 ///
477 /// ```
478 /// let x = Some("foo");
479 /// assert_eq!(x.ok_or(0), Ok("foo"));
480 ///
481 /// let x: Option<&str> = None;
482 /// assert_eq!(x.ok_or(0), Err(0));
483 /// ```
484 #[inline]
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
487 match self {
488 Some(v) => Ok(v),
489 None => Err(err),
490 }
491 }
492
493 /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
494 /// `Ok(v)` and `None` to `Err(err())`.
495 ///
496 /// # Examples
497 ///
498 /// ```
499 /// let x = Some("foo");
500 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
501 ///
502 /// let x: Option<&str> = None;
503 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
504 /// ```
505 #[inline]
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
508 match self {
509 Some(v) => Ok(v),
510 None => Err(err()),
511 }
512 }
513
514 /////////////////////////////////////////////////////////////////////////
515 // Iterator constructors
516 /////////////////////////////////////////////////////////////////////////
517
518 /// Returns an iterator over the possibly contained value.
519 ///
520 /// # Examples
521 ///
522 /// ```
523 /// let x = Some(4);
524 /// assert_eq!(x.iter().next(), Some(&4));
525 ///
526 /// let x: Option<u32> = None;
527 /// assert_eq!(x.iter().next(), None);
528 /// ```
529 #[inline]
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn iter(&self) -> Iter<T> {
532 Iter { inner: Item { opt: self.as_ref() } }
533 }
534
535 /// Returns a mutable iterator over the possibly contained value.
536 ///
537 /// # Examples
538 ///
539 /// ```
540 /// let mut x = Some(4);
541 /// match x.iter_mut().next() {
542 /// Some(&mut ref mut v) => *v = 42,
543 /// None => {},
544 /// }
545 /// assert_eq!(x, Some(42));
546 ///
547 /// let mut x: Option<u32> = None;
548 /// assert_eq!(x.iter_mut().next(), None);
549 /// ```
550 #[inline]
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn iter_mut(&mut self) -> IterMut<T> {
553 IterMut { inner: Item { opt: self.as_mut() } }
554 }
555
556 /////////////////////////////////////////////////////////////////////////
557 // Boolean operations on the values, eager and lazy
558 /////////////////////////////////////////////////////////////////////////
559
560 /// Returns `None` if the option is `None`, otherwise returns `optb`.
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// let x = Some(2);
566 /// let y: Option<&str> = None;
567 /// assert_eq!(x.and(y), None);
568 ///
569 /// let x: Option<u32> = None;
570 /// let y = Some("foo");
571 /// assert_eq!(x.and(y), None);
572 ///
573 /// let x = Some(2);
574 /// let y = Some("foo");
575 /// assert_eq!(x.and(y), Some("foo"));
576 ///
577 /// let x: Option<u32> = None;
578 /// let y: Option<&str> = None;
579 /// assert_eq!(x.and(y), None);
580 /// ```
581 #[inline]
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
584 match self {
585 Some(_) => optb,
586 None => None,
587 }
588 }
589
590 /// Returns `None` if the option is `None`, otherwise calls `f` with the
591 /// wrapped value and returns the result.
592 ///
593 /// Some languages call this operation flatmap.
594 ///
595 /// # Examples
596 ///
597 /// ```
598 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
599 /// fn nope(_: u32) -> Option<u32> { None }
600 ///
601 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
602 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
603 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
604 /// assert_eq!(None.and_then(sq).and_then(sq), None);
605 /// ```
606 #[inline]
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
609 match self {
610 Some(x) => f(x),
611 None => None,
612 }
613 }
614
615 /// Returns the option if it contains a value, otherwise returns `optb`.
616 ///
617 /// # Examples
618 ///
619 /// ```
620 /// let x = Some(2);
621 /// let y = None;
622 /// assert_eq!(x.or(y), Some(2));
623 ///
624 /// let x = None;
625 /// let y = Some(100);
626 /// assert_eq!(x.or(y), Some(100));
627 ///
628 /// let x = Some(2);
629 /// let y = Some(100);
630 /// assert_eq!(x.or(y), Some(2));
631 ///
632 /// let x: Option<u32> = None;
633 /// let y = None;
634 /// assert_eq!(x.or(y), None);
635 /// ```
636 #[inline]
637 #[stable(feature = "rust1", since = "1.0.0")]
638 pub fn or(self, optb: Option<T>) -> Option<T> {
639 match self {
640 Some(_) => self,
641 None => optb,
642 }
643 }
644
645 /// Returns the option if it contains a value, otherwise calls `f` and
646 /// returns the result.
647 ///
648 /// # Examples
649 ///
650 /// ```
651 /// fn nobody() -> Option<&'static str> { None }
652 /// fn vikings() -> Option<&'static str> { Some("vikings") }
653 ///
654 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
655 /// assert_eq!(None.or_else(vikings), Some("vikings"));
656 /// assert_eq!(None.or_else(nobody), None);
657 /// ```
658 #[inline]
659 #[stable(feature = "rust1", since = "1.0.0")]
660 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
661 match self {
662 Some(_) => self,
663 None => f(),
664 }
665 }
666
667 /////////////////////////////////////////////////////////////////////////
668 // Misc
669 /////////////////////////////////////////////////////////////////////////
670
671 /// Takes the value out of the option, leaving a `None` in its place.
672 ///
673 /// # Examples
674 ///
675 /// ```
676 /// let mut x = Some(2);
677 /// x.take();
678 /// assert_eq!(x, None);
679 ///
680 /// let mut x: Option<u32> = None;
681 /// x.take();
682 /// assert_eq!(x, None);
683 /// ```
684 #[inline]
685 #[stable(feature = "rust1", since = "1.0.0")]
686 pub fn take(&mut self) -> Option<T> {
687 mem::replace(self, None)
688 }
689
690 /// Converts from `Option<T>` to `&[T]` (without copying)
691 #[inline]
692 #[unstable(feature = "as_slice", since = "unsure of the utility here")]
693 pub fn as_slice<'a>(&'a self) -> &'a [T] {
694 match *self {
695 Some(ref x) => slice::ref_slice(x),
696 None => {
697 let result: &[_] = &[];
698 result
699 }
700 }
701 }
702 }
703
704 impl<'a, T: Clone> Option<&'a T> {
705 /// Maps an Option<&T> to an Option<T> by cloning the contents of the Option.
706 #[stable(feature = "rust1", since = "1.0.0")]
707 pub fn cloned(self) -> Option<T> {
708 self.map(|t| t.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 /// # Examples
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().ok().unwrap_or_default();
730 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
731 ///
732 /// assert_eq!(1909, good_year);
733 /// assert_eq!(0, bad_year);
734 /// ```
735 #[inline]
736 #[stable(feature = "rust1", since = "1.0.0")]
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 #[stable(feature = "rust1", since = "1.0.0")]
750 impl<T> Default for Option<T> {
751 #[inline]
752 #[stable(feature = "rust1", since = "1.0.0")]
753 fn default() -> Option<T> { None }
754 }
755
756 #[stable(feature = "rust1", since = "1.0.0")]
757 impl<T> IntoIterator for Option<T> {
758 type Item = T;
759 type IntoIter = IntoIter<T>;
760
761 /// Returns a consuming iterator over the possibly contained value.
762 ///
763 /// # Examples
764 ///
765 /// ```
766 /// let x = Some("string");
767 /// let v: Vec<&str> = x.into_iter().collect();
768 /// assert_eq!(v, ["string"]);
769 ///
770 /// let x = None;
771 /// let v: Vec<&str> = x.into_iter().collect();
772 /// assert!(v.is_empty());
773 /// ```
774 #[inline]
775 fn into_iter(self) -> IntoIter<T> {
776 IntoIter { inner: Item { opt: self } }
777 }
778 }
779
780 /////////////////////////////////////////////////////////////////////////////
781 // The Option Iterators
782 /////////////////////////////////////////////////////////////////////////////
783
784 #[derive(Clone)]
785 struct Item<A> {
786 opt: Option<A>
787 }
788
789 impl<A> Iterator for Item<A> {
790 type Item = A;
791
792 #[inline]
793 fn next(&mut self) -> Option<A> {
794 self.opt.take()
795 }
796
797 #[inline]
798 fn size_hint(&self) -> (usize, Option<usize>) {
799 match self.opt {
800 Some(_) => (1, Some(1)),
801 None => (0, Some(0)),
802 }
803 }
804 }
805
806 impl<A> DoubleEndedIterator for Item<A> {
807 #[inline]
808 fn next_back(&mut self) -> Option<A> {
809 self.opt.take()
810 }
811 }
812
813 impl<A> ExactSizeIterator for Item<A> {}
814
815 /// An iterator over a reference of the contained item in an Option.
816 #[stable(feature = "rust1", since = "1.0.0")]
817 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
818
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl<'a, A> Iterator for Iter<'a, A> {
821 type Item = &'a A;
822
823 #[inline]
824 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
825 #[inline]
826 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
827 }
828
829 #[stable(feature = "rust1", since = "1.0.0")]
830 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
831 #[inline]
832 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
833 }
834
835 #[stable(feature = "rust1", since = "1.0.0")]
836 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
837
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<'a, A> Clone for Iter<'a, A> {
840 fn clone(&self) -> Iter<'a, A> {
841 Iter { inner: self.inner.clone() }
842 }
843 }
844
845 /// An iterator over a mutable reference of the contained item in an Option.
846 #[stable(feature = "rust1", since = "1.0.0")]
847 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
848
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<'a, A> Iterator for IterMut<'a, A> {
851 type Item = &'a mut A;
852
853 #[inline]
854 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
855 #[inline]
856 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
857 }
858
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
861 #[inline]
862 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
863 }
864
865 #[stable(feature = "rust1", since = "1.0.0")]
866 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
867
868 /// An iterator over the item contained inside an Option.
869 #[derive(Clone)]
870 #[stable(feature = "rust1", since = "1.0.0")]
871 pub struct IntoIter<A> { inner: Item<A> }
872
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<A> Iterator for IntoIter<A> {
875 type Item = A;
876
877 #[inline]
878 fn next(&mut self) -> Option<A> { self.inner.next() }
879 #[inline]
880 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
881 }
882
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<A> DoubleEndedIterator for IntoIter<A> {
885 #[inline]
886 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
887 }
888
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<A> ExactSizeIterator for IntoIter<A> {}
891
892 /////////////////////////////////////////////////////////////////////////////
893 // FromIterator
894 /////////////////////////////////////////////////////////////////////////////
895
896 #[stable(feature = "rust1", since = "1.0.0")]
897 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
898 /// Takes each element in the `Iterator`: if it is `None`, no further
899 /// elements are taken, and the `None` is returned. Should no `None` occur, a
900 /// container with the values of each `Option` is returned.
901 ///
902 /// Here is an example which increments every integer in a vector,
903 /// checking for overflow:
904 ///
905 /// ```
906 /// use std::u16;
907 ///
908 /// let v = vec!(1, 2);
909 /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
910 /// if x == u16::MAX { None }
911 /// else { Some(x + 1) }
912 /// ).collect();
913 /// assert!(res == Some(vec!(2, 3)));
914 /// ```
915 #[inline]
916 #[stable(feature = "rust1", since = "1.0.0")]
917 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
918 // FIXME(#11084): This could be replaced with Iterator::scan when this
919 // performance bug is closed.
920
921 struct Adapter<Iter> {
922 iter: Iter,
923 found_none: bool,
924 }
925
926 impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
927 type Item = T;
928
929 #[inline]
930 fn next(&mut self) -> Option<T> {
931 match self.iter.next() {
932 Some(Some(value)) => Some(value),
933 Some(None) => {
934 self.found_none = true;
935 None
936 }
937 None => None,
938 }
939 }
940 }
941
942 let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
943 let v: V = FromIterator::from_iter(adapter.by_ref());
944
945 if adapter.found_none {
946 None
947 } else {
948 Some(v)
949 }
950 }
951 }