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