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