]> git.lizzy.rs Git - rust.git/blob - src/libcore/option.rs
a4d33ae802851d1d9dced4d807b974d0a4c605a0
[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 iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
147 use mem;
148 use slice;
149
150 /// The `Option`
151 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, 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<String>` 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<String> = Some("10".to_string());
198     /// // First, cast `Option<String>` to `Option<&String>` 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
241     /// `msg`.
242     #[inline]
243     pub fn expect(self, msg: &str) -> T {
244         match self {
245             Some(val) => val,
246             None => fail!(msg),
247         }
248     }
249
250     /// Moves a value out of an option type and returns it, consuming the `Option`.
251     ///
252     /// # Failure
253     ///
254     /// Fails if the self value equals `None`.
255     ///
256     /// # Safety note
257     ///
258     /// In general, because this function may fail, its use is discouraged.
259     /// Instead, prefer to use pattern matching and handle the `None`
260     /// case explicitly.
261     #[inline]
262     pub fn unwrap(self) -> T {
263         match self {
264             Some(val) => val,
265             None => fail!("called `Option::unwrap()` on a `None` value"),
266         }
267     }
268
269     /// Returns the contained value or a default.
270     #[inline]
271     pub fn unwrap_or(self, def: T) -> T {
272         match self {
273             Some(x) => x,
274             None => def
275         }
276     }
277
278     /// Returns the contained value or computes it from a closure.
279     #[inline]
280     pub fn unwrap_or_else(self, f: || -> T) -> T {
281         match self {
282             Some(x) => x,
283             None => f()
284         }
285     }
286
287     /////////////////////////////////////////////////////////////////////////
288     // Transforming contained values
289     /////////////////////////////////////////////////////////////////////////
290
291     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value
292     ///
293     /// # Example
294     ///
295     /// Convert an `Option<String>` into an `Option<uint>`, consuming the original:
296     ///
297     /// ```
298     /// let num_as_str: Option<String> = Some("10".to_string());
299     /// // `Option::map` takes self *by value*, consuming `num_as_str`
300     /// let num_as_int: Option<uint> = num_as_str.map(|n| n.len());
301     /// ```
302     #[inline]
303     pub fn map<U>(self, f: |T| -> U) -> Option<U> {
304         match self { Some(x) => Some(f(x)), None => None }
305     }
306
307     /// Applies a function to the contained value or returns a default.
308     #[inline]
309     pub fn map_or<U>(self, def: U, f: |T| -> U) -> U {
310         match self { None => def, Some(t) => f(t) }
311     }
312
313     /// Applies a function to the contained value or does nothing.
314     /// Returns true if the contained value was mutated.
315     pub fn mutate(&mut self, f: |T| -> T) -> bool {
316         if self.is_some() {
317             *self = Some(f(self.take_unwrap()));
318             true
319         } else { false }
320     }
321
322     /// Applies a function to the contained value or sets it to a default.
323     /// Returns true if the contained value was mutated, or false if set to the default.
324     pub fn mutate_or_set(&mut self, def: T, f: |T| -> T) -> bool {
325         if self.is_some() {
326             *self = Some(f(self.take_unwrap()));
327             true
328         } else {
329             *self = Some(def);
330             false
331         }
332     }
333
334     /////////////////////////////////////////////////////////////////////////
335     // Iterator constructors
336     /////////////////////////////////////////////////////////////////////////
337
338     /// Returns an iterator over the possibly contained value.
339     #[inline]
340     pub fn iter<'r>(&'r self) -> Item<&'r T> {
341         Item{opt: self.as_ref()}
342     }
343
344     /// Returns a mutable iterator over the possibly contained value.
345     #[inline]
346     pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
347         Item{opt: self.as_mut()}
348     }
349
350     /// Returns a consuming iterator over the possibly contained value.
351     #[inline]
352     pub fn move_iter(self) -> Item<T> {
353         Item{opt: self}
354     }
355
356     /////////////////////////////////////////////////////////////////////////
357     // Boolean operations on the values, eager and lazy
358     /////////////////////////////////////////////////////////////////////////
359
360     /// Returns `None` if the option is `None`, otherwise returns `optb`.
361     #[inline]
362     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
363         match self {
364             Some(_) => optb,
365             None => None,
366         }
367     }
368
369     /// Returns `None` if the option is `None`, otherwise calls `f` with the
370     /// wrapped value and returns the result.
371     #[inline]
372     pub fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U> {
373         match self {
374             Some(x) => f(x),
375             None => None,
376         }
377     }
378
379     /// Returns the option if it contains a value, otherwise returns `optb`.
380     #[inline]
381     pub fn or(self, optb: Option<T>) -> Option<T> {
382         match self {
383             Some(_) => self,
384             None => optb
385         }
386     }
387
388     /// Returns the option if it contains a value, otherwise calls `f` and
389     /// returns the result.
390     #[inline]
391     pub fn or_else(self, f: || -> Option<T>) -> Option<T> {
392         match self {
393             Some(_) => self,
394             None => f()
395         }
396     }
397
398     /////////////////////////////////////////////////////////////////////////
399     // Misc
400     /////////////////////////////////////////////////////////////////////////
401
402     /// Takes the value out of the option, leaving a `None` in its place.
403     #[inline]
404     pub fn take(&mut self) -> Option<T> {
405         mem::replace(self, None)
406     }
407
408     /// Filters an optional value using a given function.
409     #[inline(always)]
410     pub fn filtered(self, f: |t: &T| -> bool) -> Option<T> {
411         match self {
412             Some(x) => if f(&x) { Some(x) } else { None },
413             None => None
414         }
415     }
416
417     /// Applies a function zero or more times until the result is `None`.
418     #[inline]
419     pub fn while_some(self, f: |v: T| -> Option<T>) {
420         let mut opt = self;
421         loop {
422             match opt {
423                 Some(x) => opt = f(x),
424                 None => break
425             }
426         }
427     }
428
429     /////////////////////////////////////////////////////////////////////////
430     // Common special cases
431     /////////////////////////////////////////////////////////////////////////
432
433     /// The option dance. Moves a value out of an option type and returns it,
434     /// replacing the original with `None`.
435     ///
436     /// # Failure
437     ///
438     /// Fails if the value equals `None`.
439     #[inline]
440     pub fn take_unwrap(&mut self) -> T {
441         match self.take() {
442             Some(x) => x,
443             None => fail!("called `Option::take_unwrap()` on a `None` value")
444         }
445     }
446
447     /// Gets an immutable reference to the value inside an option.
448     ///
449     /// # Failure
450     ///
451     /// Fails if the value equals `None`
452     ///
453     /// # Safety note
454     ///
455     /// In general, because this function may fail, its use is discouraged
456     /// (calling `get` on `None` is akin to dereferencing a null pointer).
457     /// Instead, prefer to use pattern matching and handle the `None`
458     /// case explicitly.
459     #[inline]
460     pub fn get_ref<'a>(&'a self) -> &'a T {
461         match *self {
462             Some(ref x) => x,
463             None => fail!("called `Option::get_ref()` on a `None` value"),
464         }
465     }
466
467     /// Gets a mutable reference to the value inside an option.
468     ///
469     /// # Failure
470     ///
471     /// Fails if the value equals `None`
472     ///
473     /// # Safety note
474     ///
475     /// In general, because this function may fail, its use is discouraged
476     /// (calling `get` on `None` is akin to dereferencing a null pointer).
477     /// Instead, prefer to use pattern matching and handle the `None`
478     /// case explicitly.
479     #[inline]
480     pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
481         match *self {
482             Some(ref mut x) => x,
483             None => fail!("called `Option::get_mut_ref()` on a `None` value"),
484         }
485     }
486 }
487
488 impl<T: Default> Option<T> {
489     /// Returns the contained value or a default
490     ///
491     /// Consumes the `self` argument then, if `Some`, returns the contained
492     /// value, otherwise if `None`, returns the default value for that
493     /// type.
494     ///
495     /// # Example
496     ///
497     /// Convert a string to an integer, turning poorly-formed strings
498     /// into 0 (the default value for integers). `from_str` converts
499     /// a string to any other type that implements `FromStr`, returning
500     /// `None` on error.
501     ///
502     /// ```
503     /// let good_year_from_input = "1909";
504     /// let bad_year_from_input = "190blarg";
505     /// let good_year = from_str(good_year_from_input).unwrap_or_default();
506     /// let bad_year = from_str(bad_year_from_input).unwrap_or_default();
507     ///
508     /// assert_eq!(1909, good_year);
509     /// assert_eq!(0, bad_year);
510     /// ```
511     #[inline]
512     pub fn unwrap_or_default(self) -> T {
513         match self {
514             Some(x) => x,
515             None => Default::default()
516         }
517     }
518 }
519
520 /////////////////////////////////////////////////////////////////////////////
521 // Trait implementations
522 /////////////////////////////////////////////////////////////////////////////
523
524 impl<T> Default for Option<T> {
525     #[inline]
526     fn default() -> Option<T> { None }
527 }
528
529 /////////////////////////////////////////////////////////////////////////////
530 // The Option Iterator
531 /////////////////////////////////////////////////////////////////////////////
532
533 /// An `Option` iterator that yields either one or zero elements
534 ///
535 /// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
536 /// methods on `Option`.
537 #[deriving(Clone)]
538 pub struct Item<A> {
539     opt: Option<A>
540 }
541
542 impl<A> Iterator<A> for Item<A> {
543     #[inline]
544     fn next(&mut self) -> Option<A> {
545         self.opt.take()
546     }
547
548     #[inline]
549     fn size_hint(&self) -> (uint, Option<uint>) {
550         match self.opt {
551             Some(_) => (1, Some(1)),
552             None => (0, Some(0)),
553         }
554     }
555 }
556
557 impl<A> DoubleEndedIterator<A> for Item<A> {
558     #[inline]
559     fn next_back(&mut self) -> Option<A> {
560         self.opt.take()
561     }
562 }
563
564 impl<A> ExactSize<A> for Item<A> {}
565
566 /////////////////////////////////////////////////////////////////////////////
567 // Free functions
568 /////////////////////////////////////////////////////////////////////////////
569
570 /// Takes each element in the `Iterator`: if it is `None`, no further
571 /// elements are taken, and the `None` is returned. Should no `None` occur, a
572 /// vector containing the values of each `Option` is returned.
573 ///
574 /// Here is an example which increments every integer in a vector,
575 /// checking for overflow:
576 ///
577 /// ```rust
578 /// use std::option;
579 /// use std::uint;
580 ///
581 /// let v = vec!(1u, 2u);
582 /// let res: Option<Vec<uint>> = option::collect(v.iter().map(|x: &uint|
583 ///     if *x == uint::MAX { None }
584 ///     else { Some(x + 1) }
585 /// ));
586 /// assert!(res == Some(vec!(2u, 3u)));
587 /// ```
588 #[inline]
589 pub fn collect<T, Iter: Iterator<Option<T>>, V: FromIterator<T>>(iter: Iter) -> Option<V> {
590     // FIXME(#11084): This should be twice as fast once this bug is closed.
591     let mut iter = iter.scan(false, |state, x| {
592         match x {
593             Some(x) => Some(x),
594             None => {
595                 *state = true;
596                 None
597             }
598         }
599     });
600
601     let v: V = FromIterator::from_iter(iter.by_ref());
602
603     if iter.state {
604         None
605     } else {
606         Some(v)
607     }
608 }
609
610 /////////////////////////////////////////////////////////////////////////////
611 // Tests
612 /////////////////////////////////////////////////////////////////////////////
613
614 #[cfg(test)]
615 mod tests {
616     use realstd::vec::Vec;
617     use realstd::string::String;
618     use option::collect;
619     use prelude::*;
620     use realstd::str::{Str, StrAllocating};
621     use iter::range;
622
623     use str::StrSlice;
624     use kinds::marker;
625     use slice::ImmutableVector;
626
627     #[test]
628     fn test_get_ptr() {
629         unsafe {
630             let x = box 0;
631             let addr_x: *int = ::mem::transmute(&*x);
632             let opt = Some(x);
633             let y = opt.unwrap();
634             let addr_y: *int = ::mem::transmute(&*y);
635             assert_eq!(addr_x, addr_y);
636         }
637     }
638
639     #[test]
640     fn test_get_str() {
641         let x = "test".to_string();
642         let addr_x = x.as_slice().as_ptr();
643         let opt = Some(x);
644         let y = opt.unwrap();
645         let addr_y = y.as_slice().as_ptr();
646         assert_eq!(addr_x, addr_y);
647     }
648
649     #[test]
650     fn test_get_resource() {
651         use realstd::rc::Rc;
652         use cell::RefCell;
653
654         struct R {
655            i: Rc<RefCell<int>>,
656         }
657
658         #[unsafe_destructor]
659         impl ::ops::Drop for R {
660            fn drop(&mut self) {
661                 let ii = &*self.i;
662                 let i = *ii.borrow();
663                 *ii.borrow_mut() = i + 1;
664             }
665         }
666
667         fn r(i: Rc<RefCell<int>>) -> R {
668             R {
669                 i: i
670             }
671         }
672
673         fn realclone<T: ::realstd::clone::Clone>(t: &T) -> T {
674             use realstd::clone::Clone;
675             t.clone()
676         }
677
678         let i = Rc::new(RefCell::new(0));
679         {
680             let x = r(realclone(&i));
681             let opt = Some(x);
682             let _y = opt.unwrap();
683         }
684         assert_eq!(*i.borrow(), 1);
685     }
686
687     #[test]
688     fn test_option_dance() {
689         let x = Some(());
690         let mut y = Some(5);
691         let mut y2 = 0;
692         for _x in x.iter() {
693             y2 = y.take_unwrap();
694         }
695         assert_eq!(y2, 5);
696         assert!(y.is_none());
697     }
698
699     #[test] #[should_fail]
700     fn test_option_too_much_dance() {
701         let mut y = Some(marker::NoCopy);
702         let _y2 = y.take_unwrap();
703         let _y3 = y.take_unwrap();
704     }
705
706     #[test]
707     fn test_and() {
708         let x: Option<int> = Some(1);
709         assert_eq!(x.and(Some(2)), Some(2));
710         assert_eq!(x.and(None::<int>), None);
711
712         let x: Option<int> = None;
713         assert_eq!(x.and(Some(2)), None);
714         assert_eq!(x.and(None::<int>), None);
715     }
716
717     #[test]
718     fn test_and_then() {
719         let x: Option<int> = Some(1);
720         assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
721         assert_eq!(x.and_then(|_| None::<int>), None);
722
723         let x: Option<int> = None;
724         assert_eq!(x.and_then(|x| Some(x + 1)), None);
725         assert_eq!(x.and_then(|_| None::<int>), None);
726     }
727
728     #[test]
729     fn test_or() {
730         let x: Option<int> = Some(1);
731         assert_eq!(x.or(Some(2)), Some(1));
732         assert_eq!(x.or(None), Some(1));
733
734         let x: Option<int> = None;
735         assert_eq!(x.or(Some(2)), Some(2));
736         assert_eq!(x.or(None), None);
737     }
738
739     #[test]
740     fn test_or_else() {
741         let x: Option<int> = Some(1);
742         assert_eq!(x.or_else(|| Some(2)), Some(1));
743         assert_eq!(x.or_else(|| None), Some(1));
744
745         let x: Option<int> = None;
746         assert_eq!(x.or_else(|| Some(2)), Some(2));
747         assert_eq!(x.or_else(|| None), None);
748     }
749
750     #[test]
751     fn test_option_while_some() {
752         let mut i = 0;
753         Some(10).while_some(|j| {
754             i += 1;
755             if j > 0 {
756                 Some(j-1)
757             } else {
758                 None
759             }
760         });
761         assert_eq!(i, 11);
762     }
763
764     #[test]
765     fn test_unwrap() {
766         assert_eq!(Some(1).unwrap(), 1);
767         let s = Some("hello".to_string()).unwrap();
768         assert_eq!(s.as_slice(), "hello");
769     }
770
771     #[test]
772     #[should_fail]
773     fn test_unwrap_fail1() {
774         let x: Option<int> = None;
775         x.unwrap();
776     }
777
778     #[test]
779     #[should_fail]
780     fn test_unwrap_fail2() {
781         let x: Option<String> = None;
782         x.unwrap();
783     }
784
785     #[test]
786     fn test_unwrap_or() {
787         let x: Option<int> = Some(1);
788         assert_eq!(x.unwrap_or(2), 1);
789
790         let x: Option<int> = None;
791         assert_eq!(x.unwrap_or(2), 2);
792     }
793
794     #[test]
795     fn test_unwrap_or_else() {
796         let x: Option<int> = Some(1);
797         assert_eq!(x.unwrap_or_else(|| 2), 1);
798
799         let x: Option<int> = None;
800         assert_eq!(x.unwrap_or_else(|| 2), 2);
801     }
802
803     #[test]
804     fn test_filtered() {
805         let some_stuff = Some(42);
806         let modified_stuff = some_stuff.filtered(|&x| {x < 10});
807         assert_eq!(some_stuff.unwrap(), 42);
808         assert!(modified_stuff.is_none());
809     }
810
811     #[test]
812     fn test_iter() {
813         let val = 5;
814
815         let x = Some(val);
816         let mut it = x.iter();
817
818         assert_eq!(it.size_hint(), (1, Some(1)));
819         assert_eq!(it.next(), Some(&val));
820         assert_eq!(it.size_hint(), (0, Some(0)));
821         assert!(it.next().is_none());
822     }
823
824     #[test]
825     fn test_mut_iter() {
826         let val = 5;
827         let new_val = 11;
828
829         let mut x = Some(val);
830         {
831             let mut it = x.mut_iter();
832
833             assert_eq!(it.size_hint(), (1, Some(1)));
834
835             match it.next() {
836                 Some(interior) => {
837                     assert_eq!(*interior, val);
838                     *interior = new_val;
839                 }
840                 None => assert!(false),
841             }
842
843             assert_eq!(it.size_hint(), (0, Some(0)));
844             assert!(it.next().is_none());
845         }
846         assert_eq!(x, Some(new_val));
847     }
848
849     #[test]
850     fn test_ord() {
851         let small = Some(1.0);
852         let big = Some(5.0);
853         let nan = Some(0.0/0.0);
854         assert!(!(nan < big));
855         assert!(!(nan > big));
856         assert!(small < big);
857         assert!(None < big);
858         assert!(big > None);
859     }
860
861     #[test]
862     fn test_mutate() {
863         let mut x = Some(3i);
864         assert!(x.mutate(|i| i+1));
865         assert_eq!(x, Some(4i));
866         assert!(x.mutate_or_set(0, |i| i+1));
867         assert_eq!(x, Some(5i));
868         x = None;
869         assert!(!x.mutate(|i| i+1));
870         assert_eq!(x, None);
871         assert!(!x.mutate_or_set(0i, |i| i+1));
872         assert_eq!(x, Some(0i));
873     }
874
875     #[test]
876     fn test_collect() {
877         let v: Option<Vec<int>> = collect(range(0, 0)
878                                           .map(|_| Some(0)));
879         assert!(v == Some(vec![]));
880
881         let v: Option<Vec<int>> = collect(range(0, 3)
882                                           .map(|x| Some(x)));
883         assert!(v == Some(vec![0, 1, 2]));
884
885         let v: Option<Vec<int>> = collect(range(0, 3)
886                                           .map(|x| if x > 1 { None } else { Some(x) }));
887         assert!(v == None);
888
889         // test that it does not take more elements than it needs
890         let mut functions = [|| Some(()), || None, || fail!()];
891
892         let v: Option<Vec<()>> = collect(functions.mut_iter().map(|f| (*f)()));
893
894         assert!(v == None);
895     }
896 }