1 // Copyright 2012-2013 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.
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.
11 //! Operations on the ubiquitous `Option` type.
13 //! Type `Option` represents an optional value.
15 //! Every `Option<T>` value can either be `Some(T)` or `None`. Where in other
16 //! languages you might use a nullable type, in Rust you would use an option
19 //! Options are most commonly used with pattern matching to query the presence
20 //! of a value and take action, always accounting for the `None` case.
25 //! let msg = Some(~"howdy");
27 //! // Take a reference to the contained string
29 //! Some(ref m) => io::println(*m),
33 //! // Remove the contained string, destroying the Option
34 //! let unwrapped_msg = match msg {
36 //! None => ~"default message"
43 use cmp::{Eq, TotalEq, TotalOrd};
46 use iter::{Iterator, DoubleEndedIterator, ExactSize};
48 use result::{IntoResult, ToResult, AsResult};
49 use result::{Result, Ok, Err};
55 #[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, ToStr)]
63 /////////////////////////////////////////////////////////////////////////////
64 // Type implementation
65 /////////////////////////////////////////////////////////////////////////////
68 /////////////////////////////////////////////////////////////////////////
69 // Querying the contained values
70 /////////////////////////////////////////////////////////////////////////
72 /// Returns true if the option contains a `Some` value
74 pub fn is_some(&self) -> bool {
81 /// Returns true if the option equals `None`
83 pub fn is_none(&self) -> bool {
87 /////////////////////////////////////////////////////////////////////////
88 // Adapter for working with references
89 /////////////////////////////////////////////////////////////////////////
91 /// Convert from `Option<T>` to `Option<&T>`
93 pub fn as_ref<'r>(&'r self) -> Option<&'r T> {
94 match *self { Some(ref x) => Some(x), None => None }
97 /// Convert from `Option<T>` to `Option<&mut T>`
99 pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
100 match *self { Some(ref mut x) => Some(x), None => None }
103 /////////////////////////////////////////////////////////////////////////
104 // Getting to contained values
105 /////////////////////////////////////////////////////////////////////////
107 /// Unwraps a option, yielding the content of a `Some`
108 /// Fails if the value is a `None` with a custom failure message provided by `msg`.
110 pub fn expect<M: Any + Send>(self, msg: M) -> T {
117 /// Moves a value out of an option type and returns it.
119 /// Useful primarily for getting strings, vectors and unique pointers out
120 /// of option types without copying them.
124 /// Fails if the value equals `None`.
128 /// In general, because this function may fail, its use is discouraged.
129 /// Instead, prefer to use pattern matching and handle the `None`
132 pub fn unwrap(self) -> T {
135 None => fail!("called `Option::unwrap()` on a `None` value"),
139 /// Returns the contained value or a default
141 pub fn unwrap_or(self, def: T) -> T {
148 /// Returns the contained value or computes it from a closure
150 pub fn unwrap_or_else(self, f: || -> T) -> T {
157 /////////////////////////////////////////////////////////////////////////
158 // Transforming contained values
159 /////////////////////////////////////////////////////////////////////////
161 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
163 pub fn map<U>(self, f: |T| -> U) -> Option<U> {
164 match self { Some(x) => Some(f(x)), None => None }
167 /// Applies a function to the contained value or returns a default.
169 pub fn map_default<U>(self, def: U, f: |T| -> U) -> U {
170 match self { None => def, Some(t) => f(t) }
173 /// Apply a function to the contained value or do nothing.
174 /// Returns true if the contained value was mutated.
175 pub fn mutate(&mut self, f: |T| -> T) -> bool {
177 *self = Some(f(self.take_unwrap()));
182 /// Apply a function to the contained value or set it to a default.
183 /// Returns true if the contained value was mutated, or false if set to the default.
184 pub fn mutate_default(&mut self, def: T, f: |T| -> T) -> bool {
186 *self = Some(f(self.take_unwrap()));
194 /////////////////////////////////////////////////////////////////////////
195 // Iterator constructors
196 /////////////////////////////////////////////////////////////////////////
198 /// Return an iterator over the possibly contained value
200 pub fn iter<'r>(&'r self) -> OptionIterator<&'r T> {
202 Some(ref x) => OptionIterator{opt: Some(x)},
203 None => OptionIterator{opt: None}
207 /// Return a mutable iterator over the possibly contained value
209 pub fn mut_iter<'r>(&'r mut self) -> OptionIterator<&'r mut T> {
211 Some(ref mut x) => OptionIterator{opt: Some(x)},
212 None => OptionIterator{opt: None}
216 /// Return a consuming iterator over the possibly contained value
218 pub fn move_iter(self) -> OptionIterator<T> {
219 OptionIterator{opt: self}
222 /////////////////////////////////////////////////////////////////////////
223 // Boolean operations on the values, eager and lazy
224 /////////////////////////////////////////////////////////////////////////
226 /// Returns `None` if the option is `None`, otherwise returns `optb`.
228 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
235 /// Returns `None` if the option is `None`, otherwise calls `f` with the
236 /// wrapped value and returns the result.
238 pub fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U> {
245 /// Returns the option if it contains a value, otherwise returns `optb`.
247 pub fn or(self, optb: Option<T>) -> Option<T> {
254 /// Returns the option if it contains a value, otherwise calls `f` and
255 /// returns the result.
257 pub fn or_else(self, f: || -> Option<T>) -> Option<T> {
264 /////////////////////////////////////////////////////////////////////////
266 /////////////////////////////////////////////////////////////////////////
268 /// Take the value out of the option, leaving a `None` in its place.
270 pub fn take(&mut self) -> Option<T> {
271 util::replace(self, None)
274 /// Filters an optional value using a given function.
276 pub fn filtered(self, f: |t: &T| -> bool) -> Option<T> {
278 Some(x) => if(f(&x)) {Some(x)} else {None},
283 /// Applies a function zero or more times until the result is `None`.
285 pub fn while_some(self, blk: |v: T| -> Option<T>) {
287 while opt.is_some() {
288 opt = blk(opt.unwrap());
292 /////////////////////////////////////////////////////////////////////////
293 // Common special cases
294 /////////////////////////////////////////////////////////////////////////
296 /// The option dance. Moves a value out of an option type and returns it,
297 /// replacing the original with `None`.
301 /// Fails if the value equals `None`.
303 pub fn take_unwrap(&mut self) -> T {
305 fail!("called `Option::take_unwrap()` on a `None` value")
310 /// Gets an immutable reference to the value inside an option.
314 /// Fails if the value equals `None`
318 /// In general, because this function may fail, its use is discouraged
319 /// (calling `get` on `None` is akin to dereferencing a null pointer).
320 /// Instead, prefer to use pattern matching and handle the `None`
323 pub fn get_ref<'a>(&'a self) -> &'a T {
326 None => fail!("called `Option::get_ref()` on a `None` value"),
330 /// Gets a mutable reference to the value inside an option.
334 /// Fails if the value equals `None`
338 /// In general, because this function may fail, its use is discouraged
339 /// (calling `get` on `None` is akin to dereferencing a null pointer).
340 /// Instead, prefer to use pattern matching and handle the `None`
343 pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
345 Some(ref mut x) => x,
346 None => fail!("called `Option::get_mut_ref()` on a `None` value"),
351 impl<T: Default> Option<T> {
352 /// Returns the contained value or default (for this type)
354 pub fn unwrap_or_default(self) -> T {
357 None => Default::default()
362 /////////////////////////////////////////////////////////////////////////////
363 // Constructor extension trait
364 /////////////////////////////////////////////////////////////////////////////
366 /// A generic trait for converting a value to a `Option`
367 pub trait ToOption<T> {
368 /// Convert to the `option` type
369 fn to_option(&self) -> Option<T>;
372 /// A generic trait for converting a value to a `Option`
373 pub trait IntoOption<T> {
374 /// Convert to the `option` type
375 fn into_option(self) -> Option<T>;
378 /// A generic trait for converting a value to a `Option`
379 pub trait AsOption<T> {
380 /// Convert to the `option` type
381 fn as_option<'a>(&'a self) -> Option<&'a T>;
384 impl<T: Clone> ToOption<T> for Option<T> {
386 fn to_option(&self) -> Option<T> { self.clone() }
389 impl<T> IntoOption<T> for Option<T> {
391 fn into_option(self) -> Option<T> { self }
394 impl<T> AsOption<T> for Option<T> {
396 fn as_option<'a>(&'a self) -> Option<&'a T> {
398 Some(ref x) => Some(x),
404 /////////////////////////////////////////////////////////////////////////////
405 // Trait implementations
406 /////////////////////////////////////////////////////////////////////////////
408 impl<T: Clone> ToResult<T, ()> for Option<T> {
410 fn to_result(&self) -> Result<T, ()> {
412 Some(ref x) => Ok(x.clone()),
418 impl<T> IntoResult<T, ()> for Option<T> {
420 fn into_result(self) -> Result<T, ()> {
428 impl<T> AsResult<T, ()> for Option<T> {
430 fn as_result<'a>(&'a self) -> Result<&'a T, &'a ()> {
431 static UNIT: () = ();
433 Some(ref t) => Ok(t),
439 impl<T: fmt::Default> fmt::Default for Option<T> {
441 fn fmt(s: &Option<T>, f: &mut fmt::Formatter) {
443 Some(ref t) => write!(f.buf, "Some({})", *t),
444 None => write!(f.buf, "None")
449 impl<T> Default for Option<T> {
451 fn default() -> Option<T> { None }
454 /////////////////////////////////////////////////////////////////////////////
455 // The Option Iterator
456 /////////////////////////////////////////////////////////////////////////////
458 /// An iterator that yields either one or zero elements
459 #[deriving(Clone, DeepClone)]
460 pub struct OptionIterator<A> {
464 impl<A> Iterator<A> for OptionIterator<A> {
466 fn next(&mut self) -> Option<A> {
471 fn size_hint(&self) -> (uint, Option<uint>) {
473 Some(_) => (1, Some(1)),
474 None => (0, Some(0)),
479 impl<A> DoubleEndedIterator<A> for OptionIterator<A> {
481 fn next_back(&mut self) -> Option<A> {
486 impl<A> ExactSize<A> for OptionIterator<A> {}
488 /////////////////////////////////////////////////////////////////////////////
490 /////////////////////////////////////////////////////////////////////////////
496 use result::{IntoResult, ToResult};
497 use result::{Ok, Err};
505 let addr_x: *int = ::cast::transmute(&*x);
507 let y = opt.unwrap();
508 let addr_y: *int = ::cast::transmute(&*y);
509 assert_eq!(addr_x, addr_y);
516 let addr_x = x.as_imm_buf(|buf, _len| buf);
518 let y = opt.unwrap();
519 let addr_y = y.as_imm_buf(|buf, _len| buf);
520 assert_eq!(addr_x, addr_y);
524 fn test_get_resource() {
530 impl ::ops::Drop for R {
531 fn drop(&mut self) { *(self.i) += 1; }
534 fn R(i: @mut int) -> R {
544 let _y = opt.unwrap();
550 fn test_option_dance() {
555 y2 = y.take_unwrap();
558 assert!(y.is_none());
561 #[test] #[should_fail]
562 fn test_option_too_much_dance() {
563 let mut y = Some(util::NonCopyable);
564 let _y2 = y.take_unwrap();
565 let _y3 = y.take_unwrap();
570 let x: Option<int> = Some(1);
571 assert_eq!(x.and(Some(2)), Some(2));
572 assert_eq!(x.and(None::<int>), None);
574 let x: Option<int> = None;
575 assert_eq!(x.and(Some(2)), None);
576 assert_eq!(x.and(None::<int>), None);
581 let x: Option<int> = Some(1);
582 assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
583 assert_eq!(x.and_then(|_| None::<int>), None);
585 let x: Option<int> = None;
586 assert_eq!(x.and_then(|x| Some(x + 1)), None);
587 assert_eq!(x.and_then(|_| None::<int>), None);
592 let x: Option<int> = Some(1);
593 assert_eq!(x.or(Some(2)), Some(1));
594 assert_eq!(x.or(None), Some(1));
596 let x: Option<int> = None;
597 assert_eq!(x.or(Some(2)), Some(2));
598 assert_eq!(x.or(None), None);
603 let x: Option<int> = Some(1);
604 assert_eq!(x.or_else(|| Some(2)), Some(1));
605 assert_eq!(x.or_else(|| None), Some(1));
607 let x: Option<int> = None;
608 assert_eq!(x.or_else(|| Some(2)), Some(2));
609 assert_eq!(x.or_else(|| None), None);
613 fn test_option_while_some() {
615 Some(10).while_some(|j| {
628 assert_eq!(Some(1).unwrap(), 1);
629 assert_eq!(Some(~"hello").unwrap(), ~"hello");
634 fn test_unwrap_fail1() {
635 let x: Option<int> = None;
641 fn test_unwrap_fail2() {
642 let x: Option<~str> = None;
647 fn test_unwrap_or() {
648 let x: Option<int> = Some(1);
649 assert_eq!(x.unwrap_or(2), 1);
651 let x: Option<int> = None;
652 assert_eq!(x.unwrap_or(2), 2);
656 fn test_unwrap_or_else() {
657 let x: Option<int> = Some(1);
658 assert_eq!(x.unwrap_or_else(|| 2), 1);
660 let x: Option<int> = None;
661 assert_eq!(x.unwrap_or_else(|| 2), 2);
666 let some_stuff = Some(42);
667 let modified_stuff = some_stuff.filtered(|&x| {x < 10});
668 assert_eq!(some_stuff.unwrap(), 42);
669 assert!(modified_stuff.is_none());
677 let mut it = x.iter();
679 assert_eq!(it.size_hint(), (1, Some(1)));
680 assert_eq!(it.next(), Some(&val));
681 assert_eq!(it.size_hint(), (0, Some(0)));
682 assert!(it.next().is_none());
690 let mut x = Some(val);
692 let mut it = x.mut_iter();
694 assert_eq!(it.size_hint(), (1, Some(1)));
698 assert_eq!(*interior, val);
701 None => assert!(false),
704 assert_eq!(it.size_hint(), (0, Some(0)));
705 assert!(it.next().is_none());
707 assert_eq!(x, Some(new_val));
712 let small = Some(1.0);
714 let nan = Some(0.0/0.0);
715 assert!(!(nan < big));
716 assert!(!(nan > big));
717 assert!(small < big);
724 let mut x = Some(3i);
725 assert!(x.mutate(|i| i+1));
726 assert_eq!(x, Some(4i));
727 assert!(x.mutate_default(0, |i| i+1));
728 assert_eq!(x, Some(5i));
730 assert!(!x.mutate(|i| i+1));
732 assert!(!x.mutate_default(0i, |i| i+1));
733 assert_eq!(x, Some(0i));
737 pub fn test_to_option() {
738 let some: Option<int> = Some(100);
739 let none: Option<int> = None;
741 assert_eq!(some.to_option(), Some(100));
742 assert_eq!(none.to_option(), None);
746 pub fn test_into_option() {
747 let some: Option<int> = Some(100);
748 let none: Option<int> = None;
750 assert_eq!(some.into_option(), Some(100));
751 assert_eq!(none.into_option(), None);
755 pub fn test_as_option() {
756 let some: Option<int> = Some(100);
757 let none: Option<int> = None;
759 assert_eq!(some.as_option().unwrap(), &100);
760 assert_eq!(none.as_option(), None);
764 pub fn test_to_result() {
765 let some: Option<int> = Some(100);
766 let none: Option<int> = None;
768 assert_eq!(some.to_result(), Ok(100));
769 assert_eq!(none.to_result(), Err(()));
773 pub fn test_into_result() {
774 let some: Option<int> = Some(100);
775 let none: Option<int> = None;
777 assert_eq!(some.into_result(), Ok(100));
778 assert_eq!(none.into_result(), Err(()));