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