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