]> git.lizzy.rs Git - rust.git/blob - src/libstd/option.rs
auto merge of #13704 : edwardw/rust/doc-hidden, r=alexcrichton
[rust.git] / src / libstd / 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 //! # // FIXME This is not the greatest first example
34 //! // cow_says contains the word "moo"
35 //! let cow_says = Some("moo");
36 //! // dog_says does not contain a value
37 //! let dog_says: Option<&str> = None;
38 //!
39 //! // Pattern match to retrieve the value
40 //! match (cow_says, dog_says) {
41 //!     (Some(cow_words), Some(dog_words)) => {
42 //!         println!("Cow says {} and dog says {}!", cow_words, dog_words);
43 //!     }
44 //!     (Some(cow_words), None) => println!("Cow says {}", cow_words),
45 //!     (None, Some(dog_words)) => println!("Dog says {}", dog_words),
46 //!     (None, None) => println!("Cow and dog are suspiciously silent")
47 //! }
48 //! ```
49 //!
50 //
51 // FIXME: Show how `Option` is used in practice, with lots of methods
52 //
53 //! # Options and pointers ("nullable" pointers)
54 //!
55 //! Rust's pointer types must always point to a valid location; there are
56 //! no "null" pointers. Instead, Rust has *optional* pointers, like
57 //! the optional owned box, `Option<~T>`.
58 //!
59 //! The following example uses `Option` to create an optional box of
60 //! `int`. Notice that in order to use the inner `int` value first the
61 //! `check_optional` function needs to use pattern matching to
62 //! determine whether the box has a value (i.e. it is `Some(...)`) or
63 //! not (`None`).
64 //!
65 //! ```
66 //! let optional: Option<~int> = None;
67 //! check_optional(&optional);
68 //!
69 //! let optional: Option<~int> = Some(~9000);
70 //! check_optional(&optional);
71 //!
72 //! fn check_optional(optional: &Option<~int>) {
73 //!     match *optional {
74 //!         Some(ref p) => println!("have value {}", p),
75 //!         None => println!("have no value")
76 //!     }
77 //! }
78 //! ```
79 //!
80 //! This usage of `Option` to create safe nullable pointers is so
81 //! common that Rust does special optimizations to make the
82 //! representation of `Option<~T>` a single pointer. Optional pointers
83 //! in Rust are stored as efficiently as any other pointer type.
84 //!
85 //! # Examples
86 //!
87 //! Basic pattern matching on `Option`:
88 //!
89 //! ```
90 //! let msg = Some("howdy");
91 //!
92 //! // Take a reference to the contained string
93 //! match msg {
94 //!     Some(ref m) => println!("{}", *m),
95 //!     None => ()
96 //! }
97 //!
98 //! // Remove the contained string, destroying the Option
99 //! let unwrapped_msg = match msg {
100 //!     Some(m) => m,
101 //!     None => "default message"
102 //! };
103 //! ```
104 //!
105 //! Initialize a result to `None` before a loop:
106 //!
107 //! ```
108 //! enum Kingdom { Plant(uint, &'static str), Animal(uint, &'static str) }
109 //!
110 //! // A list of data to search through.
111 //! let all_the_big_things = [
112 //!     Plant(250, "redwood"),
113 //!     Plant(230, "noble fir"),
114 //!     Plant(229, "sugar pine"),
115 //!     Animal(25, "blue whale"),
116 //!     Animal(19, "fin whale"),
117 //!     Animal(15, "north pacific right whale"),
118 //! ];
119 //!
120 //! // We're going to search for the name of the biggest animal,
121 //! // but to start with we've just got `None`.
122 //! let mut name_of_biggest_animal = None;
123 //! let mut size_of_biggest_animal = 0;
124 //! for big_thing in all_the_big_things.iter() {
125 //!     match *big_thing {
126 //!         Animal(size, name) if size > size_of_biggest_animal => {
127 //!             // Now we've found the name of some big animal
128 //!             size_of_biggest_animal = size;
129 //!             name_of_biggest_animal = Some(name);
130 //!         }
131 //!         Animal(..) | Plant(..) => ()
132 //!     }
133 //! }
134 //!
135 //! match name_of_biggest_animal {
136 //!     Some(name) => println!("the biggest animal is {}", name),
137 //!     None => println!("there are no animals :(")
138 //! }
139 //! ```
140
141 use any::Any;
142 use clone::Clone;
143 use cmp::{Eq, TotalEq, TotalOrd};
144 use default::Default;
145 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
146 use kinds::Send;
147 use mem;
148 use slice;
149
150 /// The `Option`
151 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Show)]
152 pub enum Option<T> {
153     /// No value
154     None,
155     /// Some value `T`
156     Some(T)
157 }
158
159 /////////////////////////////////////////////////////////////////////////////
160 // Type implementation
161 /////////////////////////////////////////////////////////////////////////////
162
163 impl<T> Option<T> {
164     /////////////////////////////////////////////////////////////////////////
165     // Querying the contained values
166     /////////////////////////////////////////////////////////////////////////
167
168     /// Returns `true` if the option is a `Some` value
169     #[inline]
170     pub fn is_some(&self) -> bool {
171         match *self {
172             Some(_) => true,
173             None => false
174         }
175     }
176
177     /// Returns `true` if the option is a `None` value
178     #[inline]
179     pub fn is_none(&self) -> bool {
180         !self.is_some()
181     }
182
183     /////////////////////////////////////////////////////////////////////////
184     // Adapter for working with references
185     /////////////////////////////////////////////////////////////////////////
186
187     /// Convert from `Option<T>` to `Option<&T>`
188     ///
189     /// # Example
190     ///
191     /// Convert an `Option<~str>` into an `Option<int>`, preserving the original.
192     /// The `map` method takes the `self` argument by value, consuming the original,
193     /// so this technique uses `as_ref` to first take an `Option` to a reference
194     /// to the value inside the original.
195     ///
196     /// ```
197     /// let num_as_str: Option<~str> = Some("10".to_owned());
198     /// // First, cast `Option<~str>` to `Option<&~str>` with `as_ref`,
199     /// // then consume *that* with `map`, leaving `num_as_str` on the stack.
200     /// let num_as_int: Option<uint> = num_as_str.as_ref().map(|n| n.len());
201     /// println!("still can print num_as_str: {}", num_as_str);
202     /// ```
203     #[inline]
204     pub fn as_ref<'r>(&'r self) -> Option<&'r T> {
205         match *self { Some(ref x) => Some(x), None => None }
206     }
207
208     /// Convert from `Option<T>` to `Option<&mut T>`
209     #[inline]
210     pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
211         match *self { Some(ref mut x) => Some(x), None => None }
212     }
213
214     /// Convert from `Option<T>` to `&[T]` (without copying)
215     #[inline]
216     pub fn as_slice<'r>(&'r self) -> &'r [T] {
217         match *self {
218             Some(ref x) => slice::ref_slice(x),
219             None => &[]
220         }
221     }
222
223     /// Convert from `Option<T>` to `&mut [T]` (without copying)
224     #[inline]
225     pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
226         match *self {
227             Some(ref mut x) => slice::mut_ref_slice(x),
228             None => &mut []
229         }
230     }
231
232     /////////////////////////////////////////////////////////////////////////
233     // Getting to contained values
234     /////////////////////////////////////////////////////////////////////////
235
236     /// Unwraps an option, yielding the content of a `Some`
237     ///
238     /// # Failure
239     ///
240     /// Fails if the value is a `None` with a custom failure message provided by `msg`.
241     #[inline]
242     pub fn expect<M: Any + Send>(self, msg: M) -> T {
243         match self {
244             Some(val) => val,
245             None => fail!(msg),
246         }
247     }
248
249     /// Moves a value out of an option type and returns it, consuming the `Option`.
250     ///
251     /// # Failure
252     ///
253     /// Fails if the self value equals `None`.
254     ///
255     /// # Safety note
256     ///
257     /// In general, because this function may fail, its use is discouraged.
258     /// Instead, prefer to use pattern matching and handle the `None`
259     /// case explicitly.
260     #[inline]
261     pub fn unwrap(self) -> T {
262         match self {
263             Some(val) => val,
264             None => fail!("called `Option::unwrap()` on a `None` value"),
265         }
266     }
267
268     /// Returns the contained value or a default.
269     #[inline]
270     pub fn unwrap_or(self, def: T) -> T {
271         match self {
272             Some(x) => x,
273             None => def
274         }
275     }
276
277     /// Returns the contained value or computes it from a closure.
278     #[inline]
279     pub fn unwrap_or_else(self, f: || -> T) -> T {
280         match self {
281             Some(x) => x,
282             None => f()
283         }
284     }
285
286     /////////////////////////////////////////////////////////////////////////
287     // Transforming contained values
288     /////////////////////////////////////////////////////////////////////////
289
290     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value
291     ///
292     /// # Example
293     ///
294     /// Convert an `Option<~str>` into an `Option<uint>`, consuming the original:
295     ///
296     /// ```
297     /// let num_as_str: Option<~str> = Some("10".to_owned());
298     /// // `Option::map` takes self *by value*, consuming `num_as_str`
299     /// let num_as_int: Option<uint> = num_as_str.map(|n| n.len());
300     /// ```
301     #[inline]
302     pub fn map<U>(self, f: |T| -> U) -> Option<U> {
303         match self { Some(x) => Some(f(x)), None => None }
304     }
305
306     /// Applies a function to the contained value or returns a default.
307     #[inline]
308     pub fn map_or<U>(self, def: U, f: |T| -> U) -> U {
309         match self { None => def, Some(t) => f(t) }
310     }
311
312     /// Applies a function to the contained value or does nothing.
313     /// Returns true if the contained value was mutated.
314     pub fn mutate(&mut self, f: |T| -> T) -> bool {
315         if self.is_some() {
316             *self = Some(f(self.take_unwrap()));
317             true
318         } else { false }
319     }
320
321     /// Applies a function to the contained value or sets it to a default.
322     /// Returns true if the contained value was mutated, or false if set to the default.
323     pub fn mutate_or_set(&mut self, def: T, f: |T| -> T) -> bool {
324         if self.is_some() {
325             *self = Some(f(self.take_unwrap()));
326             true
327         } else {
328             *self = Some(def);
329             false
330         }
331     }
332
333     /////////////////////////////////////////////////////////////////////////
334     // Iterator constructors
335     /////////////////////////////////////////////////////////////////////////
336
337     /// Returns an iterator over the possibly contained value.
338     #[inline]
339     pub fn iter<'r>(&'r self) -> Item<&'r T> {
340         Item{opt: self.as_ref()}
341     }
342
343     /// Returns a mutable iterator over the possibly contained value.
344     #[inline]
345     pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
346         Item{opt: self.as_mut()}
347     }
348
349     /// Returns a consuming iterator over the possibly contained value.
350     #[inline]
351     pub fn move_iter(self) -> Item<T> {
352         Item{opt: self}
353     }
354
355     /////////////////////////////////////////////////////////////////////////
356     // Boolean operations on the values, eager and lazy
357     /////////////////////////////////////////////////////////////////////////
358
359     /// Returns `None` if the option is `None`, otherwise returns `optb`.
360     #[inline]
361     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
362         match self {
363             Some(_) => optb,
364             None => None,
365         }
366     }
367
368     /// Returns `None` if the option is `None`, otherwise calls `f` with the
369     /// wrapped value and returns the result.
370     #[inline]
371     pub fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U> {
372         match self {
373             Some(x) => f(x),
374             None => None,
375         }
376     }
377
378     /// Returns the option if it contains a value, otherwise returns `optb`.
379     #[inline]
380     pub fn or(self, optb: Option<T>) -> Option<T> {
381         match self {
382             Some(_) => self,
383             None => optb
384         }
385     }
386
387     /// Returns the option if it contains a value, otherwise calls `f` and
388     /// returns the result.
389     #[inline]
390     pub fn or_else(self, f: || -> Option<T>) -> Option<T> {
391         match self {
392             Some(_) => self,
393             None => f()
394         }
395     }
396
397     /////////////////////////////////////////////////////////////////////////
398     // Misc
399     /////////////////////////////////////////////////////////////////////////
400
401     /// Takes the value out of the option, leaving a `None` in its place.
402     #[inline]
403     pub fn take(&mut self) -> Option<T> {
404         mem::replace(self, None)
405     }
406
407     /// Filters an optional value using a given function.
408     #[inline(always)]
409     pub fn filtered(self, f: |t: &T| -> bool) -> Option<T> {
410         match self {
411             Some(x) => if f(&x) { Some(x) } else { None },
412             None => None
413         }
414     }
415
416     /// Applies a function zero or more times until the result is `None`.
417     #[inline]
418     pub fn while_some(self, f: |v: T| -> Option<T>) {
419         let mut opt = self;
420         loop {
421             match opt {
422                 Some(x) => opt = f(x),
423                 None => break
424             }
425         }
426     }
427
428     /////////////////////////////////////////////////////////////////////////
429     // Common special cases
430     /////////////////////////////////////////////////////////////////////////
431
432     /// The option dance. Moves a value out of an option type and returns it,
433     /// replacing the original with `None`.
434     ///
435     /// # Failure
436     ///
437     /// Fails if the value equals `None`.
438     #[inline]
439     pub fn take_unwrap(&mut self) -> T {
440         match self.take() {
441             Some(x) => x,
442             None => fail!("called `Option::take_unwrap()` on a `None` value")
443         }
444     }
445
446     /// Gets an immutable reference to the value inside an option.
447     ///
448     /// # Failure
449     ///
450     /// Fails if the value equals `None`
451     ///
452     /// # Safety note
453     ///
454     /// In general, because this function may fail, its use is discouraged
455     /// (calling `get` on `None` is akin to dereferencing a null pointer).
456     /// Instead, prefer to use pattern matching and handle the `None`
457     /// case explicitly.
458     #[inline]
459     pub fn get_ref<'a>(&'a self) -> &'a T {
460         match *self {
461             Some(ref x) => x,
462             None => fail!("called `Option::get_ref()` on a `None` value"),
463         }
464     }
465
466     /// Gets a mutable reference to the value inside an option.
467     ///
468     /// # Failure
469     ///
470     /// Fails if the value equals `None`
471     ///
472     /// # Safety note
473     ///
474     /// In general, because this function may fail, its use is discouraged
475     /// (calling `get` on `None` is akin to dereferencing a null pointer).
476     /// Instead, prefer to use pattern matching and handle the `None`
477     /// case explicitly.
478     #[inline]
479     pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
480         match *self {
481             Some(ref mut x) => x,
482             None => fail!("called `Option::get_mut_ref()` on a `None` value"),
483         }
484     }
485 }
486
487 impl<T: Default> Option<T> {
488     /// Returns the contained value or a default
489     ///
490     /// Consumes the `self` argument then, if `Some`, returns the contained
491     /// value, otherwise if `None`, returns the default value for that
492     /// type.
493     ///
494     /// # Example
495     ///
496     /// Convert a string to an integer, turning poorly-formed strings
497     /// into 0 (the default value for integers). `from_str` converts
498     /// a string to any other type that implements `FromStr`, returning
499     /// `None` on error.
500     ///
501     /// ```
502     /// let good_year_from_input = "1909";
503     /// let bad_year_from_input = "190blarg";
504     /// let good_year = from_str(good_year_from_input).unwrap_or_default();
505     /// let bad_year = from_str(bad_year_from_input).unwrap_or_default();
506     ///
507     /// assert_eq!(1909, good_year);
508     /// assert_eq!(0, bad_year);
509     /// ```
510     #[inline]
511     pub fn unwrap_or_default(self) -> T {
512         match self {
513             Some(x) => x,
514             None => Default::default()
515         }
516     }
517 }
518
519 /////////////////////////////////////////////////////////////////////////////
520 // Trait implementations
521 /////////////////////////////////////////////////////////////////////////////
522
523 impl<T> Default for Option<T> {
524     #[inline]
525     fn default() -> Option<T> { None }
526 }
527
528 /////////////////////////////////////////////////////////////////////////////
529 // The Option Iterator
530 /////////////////////////////////////////////////////////////////////////////
531
532 /// An `Option` iterator that yields either one or zero elements
533 ///
534 /// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
535 /// methods on `Option`.
536 #[deriving(Clone)]
537 pub struct Item<A> {
538     opt: Option<A>
539 }
540
541 impl<A> Iterator<A> for Item<A> {
542     #[inline]
543     fn next(&mut self) -> Option<A> {
544         self.opt.take()
545     }
546
547     #[inline]
548     fn size_hint(&self) -> (uint, Option<uint>) {
549         match self.opt {
550             Some(_) => (1, Some(1)),
551             None => (0, Some(0)),
552         }
553     }
554 }
555
556 impl<A> DoubleEndedIterator<A> for Item<A> {
557     #[inline]
558     fn next_back(&mut self) -> Option<A> {
559         self.opt.take()
560     }
561 }
562
563 impl<A> ExactSize<A> for Item<A> {}
564
565 /////////////////////////////////////////////////////////////////////////////
566 // Free functions
567 /////////////////////////////////////////////////////////////////////////////
568
569 /// Takes each element in the `Iterator`: if it is `None`, no further
570 /// elements are taken, and the `None` is returned. Should no `None` occur, a
571 /// vector containing the values of each `Option` is returned.
572 ///
573 /// Here is an example which increments every integer in a vector,
574 /// checking for overflow:
575 ///
576 ///     fn inc_conditionally(x: uint) -> Option<uint> {
577 ///         if x == uint::MAX { return None; }
578 ///         else { return Some(x+1u); }
579 ///     }
580 ///     let v = [1u, 2, 3];
581 ///     let res = collect(v.iter().map(|&x| inc_conditionally(x)));
582 ///     assert!(res == Some(~[2u, 3, 4]));
583 #[inline]
584 pub fn collect<T, Iter: Iterator<Option<T>>, V: FromIterator<T>>(iter: Iter) -> Option<V> {
585     // FIXME(#11084): This should be twice as fast once this bug is closed.
586     let mut iter = iter.scan(false, |state, x| {
587         match x {
588             Some(x) => Some(x),
589             None => {
590                 *state = true;
591                 None
592             }
593         }
594     });
595
596     let v: V = FromIterator::from_iter(iter.by_ref());
597
598     if iter.state {
599         None
600     } else {
601         Some(v)
602     }
603 }
604
605 /////////////////////////////////////////////////////////////////////////////
606 // Tests
607 /////////////////////////////////////////////////////////////////////////////
608
609 #[cfg(test)]
610 mod tests {
611     use super::*;
612     use prelude::*;
613
614     use iter::range;
615     use str::StrSlice;
616     use kinds::marker;
617     use slice::ImmutableVector;
618
619     #[test]
620     fn test_get_ptr() {
621         unsafe {
622             let x = ~0;
623             let addr_x: *int = ::cast::transmute(&*x);
624             let opt = Some(x);
625             let y = opt.unwrap();
626             let addr_y: *int = ::cast::transmute(&*y);
627             assert_eq!(addr_x, addr_y);
628         }
629     }
630
631     #[test]
632     fn test_get_str() {
633         let x = "test".to_owned();
634         let addr_x = x.as_ptr();
635         let opt = Some(x);
636         let y = opt.unwrap();
637         let addr_y = y.as_ptr();
638         assert_eq!(addr_x, addr_y);
639     }
640
641     #[test]
642     fn test_get_resource() {
643         use rc::Rc;
644         use cell::RefCell;
645
646         struct R {
647            i: Rc<RefCell<int>>,
648         }
649
650         #[unsafe_destructor]
651         impl ::ops::Drop for R {
652            fn drop(&mut self) {
653                 let ii = &*self.i;
654                 let i = ii.borrow().clone();
655                 *ii.borrow_mut() = i + 1;
656             }
657         }
658
659         fn R(i: Rc<RefCell<int>>) -> R {
660             R {
661                 i: i
662             }
663         }
664
665         let i = Rc::new(RefCell::new(0));
666         {
667             let x = R(i.clone());
668             let opt = Some(x);
669             let _y = opt.unwrap();
670         }
671         assert_eq!(*i.borrow(), 1);
672     }
673
674     #[test]
675     fn test_option_dance() {
676         let x = Some(());
677         let mut y = Some(5);
678         let mut y2 = 0;
679         for _x in x.iter() {
680             y2 = y.take_unwrap();
681         }
682         assert_eq!(y2, 5);
683         assert!(y.is_none());
684     }
685
686     #[test] #[should_fail]
687     fn test_option_too_much_dance() {
688         let mut y = Some(marker::NoCopy);
689         let _y2 = y.take_unwrap();
690         let _y3 = y.take_unwrap();
691     }
692
693     #[test]
694     fn test_and() {
695         let x: Option<int> = Some(1);
696         assert_eq!(x.and(Some(2)), Some(2));
697         assert_eq!(x.and(None::<int>), None);
698
699         let x: Option<int> = None;
700         assert_eq!(x.and(Some(2)), None);
701         assert_eq!(x.and(None::<int>), None);
702     }
703
704     #[test]
705     fn test_and_then() {
706         let x: Option<int> = Some(1);
707         assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
708         assert_eq!(x.and_then(|_| None::<int>), None);
709
710         let x: Option<int> = None;
711         assert_eq!(x.and_then(|x| Some(x + 1)), None);
712         assert_eq!(x.and_then(|_| None::<int>), None);
713     }
714
715     #[test]
716     fn test_or() {
717         let x: Option<int> = Some(1);
718         assert_eq!(x.or(Some(2)), Some(1));
719         assert_eq!(x.or(None), Some(1));
720
721         let x: Option<int> = None;
722         assert_eq!(x.or(Some(2)), Some(2));
723         assert_eq!(x.or(None), None);
724     }
725
726     #[test]
727     fn test_or_else() {
728         let x: Option<int> = Some(1);
729         assert_eq!(x.or_else(|| Some(2)), Some(1));
730         assert_eq!(x.or_else(|| None), Some(1));
731
732         let x: Option<int> = None;
733         assert_eq!(x.or_else(|| Some(2)), Some(2));
734         assert_eq!(x.or_else(|| None), None);
735     }
736
737     #[test]
738     fn test_option_while_some() {
739         let mut i = 0;
740         Some(10).while_some(|j| {
741             i += 1;
742             if j > 0 {
743                 Some(j-1)
744             } else {
745                 None
746             }
747         });
748         assert_eq!(i, 11);
749     }
750
751     #[test]
752     fn test_unwrap() {
753         assert_eq!(Some(1).unwrap(), 1);
754         assert_eq!(Some("hello".to_owned()).unwrap(), "hello".to_owned());
755     }
756
757     #[test]
758     #[should_fail]
759     fn test_unwrap_fail1() {
760         let x: Option<int> = None;
761         x.unwrap();
762     }
763
764     #[test]
765     #[should_fail]
766     fn test_unwrap_fail2() {
767         let x: Option<~str> = None;
768         x.unwrap();
769     }
770
771     #[test]
772     fn test_unwrap_or() {
773         let x: Option<int> = Some(1);
774         assert_eq!(x.unwrap_or(2), 1);
775
776         let x: Option<int> = None;
777         assert_eq!(x.unwrap_or(2), 2);
778     }
779
780     #[test]
781     fn test_unwrap_or_else() {
782         let x: Option<int> = Some(1);
783         assert_eq!(x.unwrap_or_else(|| 2), 1);
784
785         let x: Option<int> = None;
786         assert_eq!(x.unwrap_or_else(|| 2), 2);
787     }
788
789     #[test]
790     fn test_filtered() {
791         let some_stuff = Some(42);
792         let modified_stuff = some_stuff.filtered(|&x| {x < 10});
793         assert_eq!(some_stuff.unwrap(), 42);
794         assert!(modified_stuff.is_none());
795     }
796
797     #[test]
798     fn test_iter() {
799         let val = 5;
800
801         let x = Some(val);
802         let mut it = x.iter();
803
804         assert_eq!(it.size_hint(), (1, Some(1)));
805         assert_eq!(it.next(), Some(&val));
806         assert_eq!(it.size_hint(), (0, Some(0)));
807         assert!(it.next().is_none());
808     }
809
810     #[test]
811     fn test_mut_iter() {
812         let val = 5;
813         let new_val = 11;
814
815         let mut x = Some(val);
816         {
817             let mut it = x.mut_iter();
818
819             assert_eq!(it.size_hint(), (1, Some(1)));
820
821             match it.next() {
822                 Some(interior) => {
823                     assert_eq!(*interior, val);
824                     *interior = new_val;
825                 }
826                 None => assert!(false),
827             }
828
829             assert_eq!(it.size_hint(), (0, Some(0)));
830             assert!(it.next().is_none());
831         }
832         assert_eq!(x, Some(new_val));
833     }
834
835     #[test]
836     fn test_ord() {
837         let small = Some(1.0);
838         let big = Some(5.0);
839         let nan = Some(0.0/0.0);
840         assert!(!(nan < big));
841         assert!(!(nan > big));
842         assert!(small < big);
843         assert!(None < big);
844         assert!(big > None);
845     }
846
847     #[test]
848     fn test_mutate() {
849         let mut x = Some(3i);
850         assert!(x.mutate(|i| i+1));
851         assert_eq!(x, Some(4i));
852         assert!(x.mutate_or_set(0, |i| i+1));
853         assert_eq!(x, Some(5i));
854         x = None;
855         assert!(!x.mutate(|i| i+1));
856         assert_eq!(x, None);
857         assert!(!x.mutate_or_set(0i, |i| i+1));
858         assert_eq!(x, Some(0i));
859     }
860
861     #[test]
862     fn test_collect() {
863         let v: Option<~[int]> = collect(range(0, 0)
864                                         .map(|_| Some(0)));
865         assert_eq!(v, Some(~[]));
866
867         let v: Option<~[int]> = collect(range(0, 3)
868                                         .map(|x| Some(x)));
869         assert_eq!(v, Some(~[0, 1, 2]));
870
871         let v: Option<~[int]> = collect(range(0, 3)
872                                         .map(|x| if x > 1 { None } else { Some(x) }));
873         assert_eq!(v, None);
874
875         // test that it does not take more elements than it needs
876         let mut functions = [|| Some(()), || None, || fail!()];
877
878         let v: Option<~[()]> = collect(functions.mut_iter().map(|f| (*f)()));
879
880         assert_eq!(v, None);
881     }
882 }