]> git.lizzy.rs Git - rust.git/blob - src/libcore/option.rs
std: Rename slice::Vector to Slice
[rust.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 //! `int`. Notice that in order to use the inner `int` 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<int>> = None;
70 //! check_optional(&optional);
71 //!
72 //! let optional: Option<Box<int>> = Some(box 9000);
73 //! check_optional(&optional);
74 //!
75 //! fn check_optional(optional: &Option<Box<int>>) {
76 //!     match *optional {
77 //!         Some(ref p) => println!("have value {}", p),
78 //!         None => println!("have no value")
79 //!     }
80 //! }
81 //! ```
82 //!
83 //! This usage of `Option` to create safe nullable pointers is so
84 //! common that Rust does special optimizations to make the
85 //! representation of `Option<Box<T>>` a single pointer. Optional pointers
86 //! in Rust are stored as efficiently as any other pointer type.
87 //!
88 //! # Examples
89 //!
90 //! Basic pattern matching on `Option`:
91 //!
92 //! ```
93 //! let msg = Some("howdy");
94 //!
95 //! // Take a reference to the contained string
96 //! match msg {
97 //!     Some(ref m) => println!("{}", *m),
98 //!     None => ()
99 //! }
100 //!
101 //! // Remove the contained string, destroying the Option
102 //! let unwrapped_msg = match msg {
103 //!     Some(m) => m,
104 //!     None => "default message"
105 //! };
106 //! ```
107 //!
108 //! Initialize a result to `None` before a loop:
109 //!
110 //! ```
111 //! enum Kingdom { Plant(uint, &'static str), Animal(uint, &'static str) }
112 //!
113 //! // A list of data to search through.
114 //! let all_the_big_things = [
115 //!     Plant(250, "redwood"),
116 //!     Plant(230, "noble fir"),
117 //!     Plant(229, "sugar pine"),
118 //!     Animal(25, "blue whale"),
119 //!     Animal(19, "fin whale"),
120 //!     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 //!         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 //!         Animal(..) | Plant(..) => ()
135 //!     }
136 //! }
137 //!
138 //! match name_of_biggest_animal {
139 //!     Some(name) => println!("the biggest animal is {}", name),
140 //!     None => println!("there are no animals :(")
141 //! }
142 //! ```
143
144 use cmp::{PartialEq, Eq, Ord};
145 use default::Default;
146 use slice::Slice;
147 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
148 use mem;
149 use slice;
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.
157 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Show)]
158 pub enum Option<T> {
159     /// No value
160     None,
161     /// Some value `T`
162     Some(T)
163 }
164
165 /////////////////////////////////////////////////////////////////////////////
166 // Type implementation
167 /////////////////////////////////////////////////////////////////////////////
168
169 impl<T> Option<T> {
170     /////////////////////////////////////////////////////////////////////////
171     // Querying the contained values
172     /////////////////////////////////////////////////////////////////////////
173
174     /// Returns `true` if the option is a `Some` value
175     #[inline]
176     pub fn is_some(&self) -> bool {
177         match *self {
178             Some(_) => true,
179             None => false
180         }
181     }
182
183     /// Returns `true` if the option is a `None` value
184     #[inline]
185     pub fn is_none(&self) -> bool {
186         !self.is_some()
187     }
188
189     /////////////////////////////////////////////////////////////////////////
190     // Adapter for working with references
191     /////////////////////////////////////////////////////////////////////////
192
193     /// Convert from `Option<T>` to `Option<&T>`
194     ///
195     /// # Example
196     ///
197     /// Convert an `Option<String>` into an `Option<int>`, preserving the original.
198     /// The `map` method takes the `self` argument by value, consuming the original,
199     /// so this technique uses `as_ref` to first take an `Option` to a reference
200     /// to the value inside the original.
201     ///
202     /// ```
203     /// let num_as_str: Option<String> = Some("10".to_string());
204     /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
205     /// // then consume *that* with `map`, leaving `num_as_str` on the stack.
206     /// let num_as_int: Option<uint> = num_as_str.as_ref().map(|n| n.len());
207     /// println!("still can print num_as_str: {}", num_as_str);
208     /// ```
209     #[inline]
210     pub fn as_ref<'r>(&'r self) -> Option<&'r T> {
211         match *self { Some(ref x) => Some(x), None => None }
212     }
213
214     /// Convert from `Option<T>` to `Option<&mut T>`
215     #[inline]
216     pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
217         match *self { Some(ref mut x) => Some(x), None => None }
218     }
219
220     /// Convert from `Option<T>` to `&mut [T]` (without copying)
221     #[inline]
222     pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
223         match *self {
224             Some(ref mut x) => slice::mut_ref_slice(x),
225             None => &mut []
226         }
227     }
228
229     /////////////////////////////////////////////////////////////////////////
230     // Getting to contained values
231     /////////////////////////////////////////////////////////////////////////
232
233     /// Unwraps an option, yielding the content of a `Some`
234     ///
235     /// # Failure
236     ///
237     /// Fails if the value is a `None` with a custom failure message provided by
238     /// `msg`.
239     #[inline]
240     pub fn expect(self, msg: &str) -> T {
241         match self {
242             Some(val) => val,
243             None => fail!(msg),
244         }
245     }
246
247     /// Moves a value out of an option type and returns it, consuming the `Option`.
248     ///
249     /// # Failure
250     ///
251     /// Fails if the self value equals `None`.
252     ///
253     /// # Safety note
254     ///
255     /// In general, because this function may fail, its use is discouraged.
256     /// Instead, prefer to use pattern matching and handle the `None`
257     /// case explicitly.
258     #[inline]
259     pub fn unwrap(self) -> T {
260         match self {
261             Some(val) => val,
262             None => fail!("called `Option::unwrap()` on a `None` value"),
263         }
264     }
265
266     /// Returns the contained value or a default.
267     #[inline]
268     pub fn unwrap_or(self, def: T) -> T {
269         match self {
270             Some(x) => x,
271             None => def
272         }
273     }
274
275     /// Returns the contained value or computes it from a closure.
276     #[inline]
277     pub fn unwrap_or_else(self, f: || -> T) -> T {
278         match self {
279             Some(x) => x,
280             None => f()
281         }
282     }
283
284     /////////////////////////////////////////////////////////////////////////
285     // Transforming contained values
286     /////////////////////////////////////////////////////////////////////////
287
288     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value
289     ///
290     /// # Example
291     ///
292     /// Convert an `Option<String>` into an `Option<uint>`, consuming the original:
293     ///
294     /// ```
295     /// let num_as_str: Option<String> = Some("10".to_string());
296     /// // `Option::map` takes self *by value*, consuming `num_as_str`
297     /// let num_as_int: Option<uint> = num_as_str.map(|n| n.len());
298     /// ```
299     #[inline]
300     pub fn map<U>(self, f: |T| -> U) -> Option<U> {
301         match self { Some(x) => Some(f(x)), None => None }
302     }
303
304     /// Applies a function to the contained value or returns a default.
305     #[inline]
306     pub fn map_or<U>(self, def: U, f: |T| -> U) -> U {
307         match self { None => def, Some(t) => f(t) }
308     }
309
310     /// Applies a function to the contained value or does nothing.
311     /// Returns true if the contained value was mutated.
312     pub fn mutate(&mut self, f: |T| -> T) -> bool {
313         if self.is_some() {
314             *self = Some(f(self.take_unwrap()));
315             true
316         } else { false }
317     }
318
319     /// Applies a function to the contained value or sets it to a default.
320     /// Returns true if the contained value was mutated, or false if set to the default.
321     pub fn mutate_or_set(&mut self, def: T, f: |T| -> T) -> bool {
322         if self.is_some() {
323             *self = Some(f(self.take_unwrap()));
324             true
325         } else {
326             *self = Some(def);
327             false
328         }
329     }
330
331     /////////////////////////////////////////////////////////////////////////
332     // Iterator constructors
333     /////////////////////////////////////////////////////////////////////////
334
335     /// Returns an iterator over the possibly contained value.
336     #[inline]
337     pub fn iter<'r>(&'r self) -> Item<&'r T> {
338         Item{opt: self.as_ref()}
339     }
340
341     /// Returns a mutable iterator over the possibly contained value.
342     #[inline]
343     pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
344         Item{opt: self.as_mut()}
345     }
346
347     /// Returns a consuming iterator over the possibly contained value.
348     #[inline]
349     pub fn move_iter(self) -> Item<T> {
350         Item{opt: self}
351     }
352
353     /////////////////////////////////////////////////////////////////////////
354     // Boolean operations on the values, eager and lazy
355     /////////////////////////////////////////////////////////////////////////
356
357     /// Returns `None` if the option is `None`, otherwise returns `optb`.
358     #[inline]
359     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
360         match self {
361             Some(_) => optb,
362             None => None,
363         }
364     }
365
366     /// Returns `None` if the option is `None`, otherwise calls `f` with the
367     /// wrapped value and returns the result.
368     #[inline]
369     pub fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U> {
370         match self {
371             Some(x) => f(x),
372             None => None,
373         }
374     }
375
376     /// Returns the option if it contains a value, otherwise returns `optb`.
377     #[inline]
378     pub fn or(self, optb: Option<T>) -> Option<T> {
379         match self {
380             Some(_) => self,
381             None => optb
382         }
383     }
384
385     /// Returns the option if it contains a value, otherwise calls `f` and
386     /// returns the result.
387     #[inline]
388     pub fn or_else(self, f: || -> Option<T>) -> Option<T> {
389         match self {
390             Some(_) => self,
391             None => f()
392         }
393     }
394
395     /////////////////////////////////////////////////////////////////////////
396     // Misc
397     /////////////////////////////////////////////////////////////////////////
398
399     /// Takes the value out of the option, leaving a `None` in its place.
400     #[inline]
401     pub fn take(&mut self) -> Option<T> {
402         mem::replace(self, None)
403     }
404
405     /// Filters an optional value using a given function.
406     #[inline(always)]
407     pub fn filtered(self, f: |t: &T| -> bool) -> Option<T> {
408         match self {
409             Some(x) => if f(&x) { Some(x) } else { None },
410             None => None
411         }
412     }
413
414     /// Applies a function zero or more times until the result is `None`.
415     #[inline]
416     pub fn while_some(self, f: |v: T| -> Option<T>) {
417         let mut opt = self;
418         loop {
419             match opt {
420                 Some(x) => opt = f(x),
421                 None => break
422             }
423         }
424     }
425
426     /////////////////////////////////////////////////////////////////////////
427     // Common special cases
428     /////////////////////////////////////////////////////////////////////////
429
430     /// The option dance. Moves a value out of an option type and returns it,
431     /// replacing the original with `None`.
432     ///
433     /// # Failure
434     ///
435     /// Fails if the value equals `None`.
436     #[inline]
437     pub fn take_unwrap(&mut self) -> T {
438         match self.take() {
439             Some(x) => x,
440             None => fail!("called `Option::take_unwrap()` on a `None` value")
441         }
442     }
443
444     /// Gets an immutable reference to the value inside an option.
445     ///
446     /// # Failure
447     ///
448     /// Fails if the value equals `None`
449     ///
450     /// # Safety note
451     ///
452     /// In general, because this function may fail, its use is discouraged
453     /// (calling `get` on `None` is akin to dereferencing a null pointer).
454     /// Instead, prefer to use pattern matching and handle the `None`
455     /// case explicitly.
456     #[inline]
457     pub fn get_ref<'a>(&'a self) -> &'a T {
458         match *self {
459             Some(ref x) => x,
460             None => fail!("called `Option::get_ref()` on a `None` value"),
461         }
462     }
463
464     /// Gets a mutable reference to the value inside an option.
465     ///
466     /// # Failure
467     ///
468     /// Fails if the value equals `None`
469     ///
470     /// # Safety note
471     ///
472     /// In general, because this function may fail, its use is discouraged
473     /// (calling `get` on `None` is akin to dereferencing a null pointer).
474     /// Instead, prefer to use pattern matching and handle the `None`
475     /// case explicitly.
476     #[inline]
477     pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
478         match *self {
479             Some(ref mut x) => x,
480             None => fail!("called `Option::get_mut_ref()` on a `None` value"),
481         }
482     }
483 }
484
485 impl<T: Default> Option<T> {
486     /// Returns the contained value or a default
487     ///
488     /// Consumes the `self` argument then, if `Some`, returns the contained
489     /// value, otherwise if `None`, returns the default value for that
490     /// type.
491     ///
492     /// # Example
493     ///
494     /// Convert a string to an integer, turning poorly-formed strings
495     /// into 0 (the default value for integers). `from_str` converts
496     /// a string to any other type that implements `FromStr`, returning
497     /// `None` on error.
498     ///
499     /// ```
500     /// let good_year_from_input = "1909";
501     /// let bad_year_from_input = "190blarg";
502     /// let good_year = from_str(good_year_from_input).unwrap_or_default();
503     /// let bad_year = from_str(bad_year_from_input).unwrap_or_default();
504     ///
505     /// assert_eq!(1909i, good_year);
506     /// assert_eq!(0i, bad_year);
507     /// ```
508     #[inline]
509     pub fn unwrap_or_default(self) -> T {
510         match self {
511             Some(x) => x,
512             None => Default::default()
513         }
514     }
515 }
516
517 /////////////////////////////////////////////////////////////////////////////
518 // Trait implementations
519 /////////////////////////////////////////////////////////////////////////////
520
521 impl<T> Slice<T> for Option<T> {
522     /// Convert from `Option<T>` to `&[T]` (without copying)
523     #[inline]
524     fn as_slice<'a>(&'a self) -> &'a [T] {
525         match *self {
526             Some(ref x) => slice::ref_slice(x),
527             None => &[]
528         }
529     }
530 }
531
532 impl<T> Default for Option<T> {
533     #[inline]
534     fn default() -> Option<T> { None }
535 }
536
537 /////////////////////////////////////////////////////////////////////////////
538 // The Option Iterator
539 /////////////////////////////////////////////////////////////////////////////
540
541 /// An `Option` iterator that yields either one or zero elements
542 ///
543 /// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
544 /// methods on `Option`.
545 #[deriving(Clone)]
546 pub struct Item<A> {
547     opt: Option<A>
548 }
549
550 impl<A> Iterator<A> for Item<A> {
551     #[inline]
552     fn next(&mut self) -> Option<A> {
553         self.opt.take()
554     }
555
556     #[inline]
557     fn size_hint(&self) -> (uint, Option<uint>) {
558         match self.opt {
559             Some(_) => (1, Some(1)),
560             None => (0, Some(0)),
561         }
562     }
563 }
564
565 impl<A> DoubleEndedIterator<A> for Item<A> {
566     #[inline]
567     fn next_back(&mut self) -> Option<A> {
568         self.opt.take()
569     }
570 }
571
572 impl<A> ExactSize<A> for Item<A> {}
573
574 /////////////////////////////////////////////////////////////////////////////
575 // Free functions
576 /////////////////////////////////////////////////////////////////////////////
577
578 /// Takes each element in the `Iterator`: if it is `None`, no further
579 /// elements are taken, and the `None` is returned. Should no `None` occur, a
580 /// vector containing the values of each `Option` is returned.
581 ///
582 /// Here is an example which increments every integer in a vector,
583 /// checking for overflow:
584 ///
585 /// ```rust
586 /// use std::option;
587 /// use std::uint;
588 ///
589 /// let v = vec!(1u, 2u);
590 /// let res: Option<Vec<uint>> = option::collect(v.iter().map(|x: &uint|
591 ///     if *x == uint::MAX { None }
592 ///     else { Some(x + 1) }
593 /// ));
594 /// assert!(res == Some(vec!(2u, 3u)));
595 /// ```
596 #[inline]
597 pub fn collect<T, Iter: Iterator<Option<T>>, V: FromIterator<T>>(iter: Iter) -> Option<V> {
598     // FIXME(#11084): This could be replaced with Iterator::scan when this
599     // performance bug is closed.
600
601     struct Adapter<Iter> {
602         iter: Iter,
603         found_none: bool,
604     }
605
606     impl<T, Iter: Iterator<Option<T>>> Iterator<T> for Adapter<Iter> {
607         #[inline]
608         fn next(&mut self) -> Option<T> {
609             match self.iter.next() {
610                 Some(Some(value)) => Some(value),
611                 Some(None) => {
612                     self.found_none = true;
613                     None
614                 }
615                 None => None,
616             }
617         }
618     }
619
620     let mut adapter = Adapter { iter: iter, found_none: false };
621     let v: V = FromIterator::from_iter(adapter.by_ref());
622
623     if adapter.found_none {
624         None
625     } else {
626         Some(v)
627     }
628 }