]> git.lizzy.rs Git - rust.git/blob - src/libstd/option.rs
auto merge of #10519 : nikomatsakis/rust/issue-8624-borrowck-overly-permissive, r...
[rust.git] / src / libstd / option.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
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 //! Operations on the ubiquitous `Option` type.
12 //!
13 //! Type `Option` represents an optional value.
14 //!
15 //! Every `Option<T>` value can either be `Some(T)` or `None`. Where in other
16 //! languages you might use a nullable type, in Rust you would use an option
17 //! type.
18 //!
19 //! Options are most commonly used with pattern matching to query the presence
20 //! of a value and take action, always accounting for the `None` case.
21 //!
22 //! # Example
23 //!
24 //! ```
25 //! let msg = Some(~"howdy");
26 //!
27 //! // Take a reference to the contained string
28 //! match msg {
29 //!     Some(ref m) => io::println(*m),
30 //!     None => ()
31 //! }
32 //!
33 //! // Remove the contained string, destroying the Option
34 //! let unwrapped_msg = match msg {
35 //!     Some(m) => m,
36 //!     None => ~"default message"
37 //! };
38 //! ```
39
40 use any::Any;
41 use clone::Clone;
42 use clone::DeepClone;
43 use cmp::{Eq, TotalEq, TotalOrd};
44 use default::Default;
45 use fmt;
46 use iter::{Iterator, DoubleEndedIterator, ExactSize};
47 use kinds::Send;
48 use result::{IntoResult, ToResult, AsResult};
49 use result::{Result, Ok, Err};
50 use str::OwnedStr;
51 use to_str::ToStr;
52 use util;
53
54 /// The option type
55 #[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, ToStr)]
56 pub enum Option<T> {
57     /// No value
58     None,
59     /// Some value `T`
60     Some(T)
61 }
62
63 /////////////////////////////////////////////////////////////////////////////
64 // Type implementation
65 /////////////////////////////////////////////////////////////////////////////
66
67 impl<T> Option<T> {
68     /////////////////////////////////////////////////////////////////////////
69     // Querying the contained values
70     /////////////////////////////////////////////////////////////////////////
71
72     /// Returns true if the option contains a `Some` value
73     #[inline]
74     pub fn is_some(&self) -> bool {
75         match *self {
76             Some(_) => true,
77             None => false
78         }
79     }
80
81     /// Returns true if the option equals `None`
82     #[inline]
83     pub fn is_none(&self) -> bool {
84         !self.is_some()
85     }
86
87     /////////////////////////////////////////////////////////////////////////
88     // Adapter for working with references
89     /////////////////////////////////////////////////////////////////////////
90
91     /// Convert from `Option<T>` to `Option<&T>`
92     #[inline]
93     pub fn as_ref<'r>(&'r self) -> Option<&'r T> {
94         match *self { Some(ref x) => Some(x), None => None }
95     }
96
97     /// Convert from `Option<T>` to `Option<&mut T>`
98     #[inline]
99     pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
100         match *self { Some(ref mut x) => Some(x), None => None }
101     }
102
103     /////////////////////////////////////////////////////////////////////////
104     // Getting to contained values
105     /////////////////////////////////////////////////////////////////////////
106
107     /// Unwraps a option, yielding the content of a `Some`
108     /// Fails if the value is a `None` with a custom failure message provided by `msg`.
109     #[inline]
110     pub fn expect<M: Any + Send>(self, msg: M) -> T {
111         match self {
112             Some(val) => val,
113             None => fail!(msg),
114         }
115     }
116
117     /// Moves a value out of an option type and returns it.
118     ///
119     /// Useful primarily for getting strings, vectors and unique pointers out
120     /// of option types without copying them.
121     ///
122     /// # Failure
123     ///
124     /// Fails if the value equals `None`.
125     ///
126     /// # Safety note
127     ///
128     /// In general, because this function may fail, its use is discouraged.
129     /// Instead, prefer to use pattern matching and handle the `None`
130     /// case explicitly.
131     #[inline]
132     pub fn unwrap(self) -> T {
133         match self {
134             Some(val) => val,
135             None => fail!("called `Option::unwrap()` on a `None` value"),
136         }
137     }
138
139     /// Returns the contained value or a default
140     #[inline]
141     pub fn unwrap_or(self, def: T) -> T {
142         match self {
143             Some(x) => x,
144             None => def
145         }
146     }
147
148     /// Returns the contained value or computes it from a closure
149     #[inline]
150     pub fn unwrap_or_else(self, f: || -> T) -> T {
151         match self {
152             Some(x) => x,
153             None => f()
154         }
155     }
156
157     /////////////////////////////////////////////////////////////////////////
158     // Transforming contained values
159     /////////////////////////////////////////////////////////////////////////
160
161     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
162     #[inline]
163     pub fn map<U>(self, f: |T| -> U) -> Option<U> {
164         match self { Some(x) => Some(f(x)), None => None }
165     }
166
167     /// Applies a function to the contained value or returns a default.
168     #[inline]
169     pub fn map_default<U>(self, def: U, f: |T| -> U) -> U {
170         match self { None => def, Some(t) => f(t) }
171     }
172
173     /// Apply a function to the contained value or do nothing.
174     /// Returns true if the contained value was mutated.
175     pub fn mutate(&mut self, f: |T| -> T) -> bool {
176         if self.is_some() {
177             *self = Some(f(self.take_unwrap()));
178             true
179         } else { false }
180     }
181
182     /// Apply a function to the contained value or set it to a default.
183     /// Returns true if the contained value was mutated, or false if set to the default.
184     pub fn mutate_default(&mut self, def: T, f: |T| -> T) -> bool {
185         if self.is_some() {
186             *self = Some(f(self.take_unwrap()));
187             true
188         } else {
189             *self = Some(def);
190             false
191         }
192     }
193
194     /////////////////////////////////////////////////////////////////////////
195     // Iterator constructors
196     /////////////////////////////////////////////////////////////////////////
197
198     /// Return an iterator over the possibly contained value
199     #[inline]
200     pub fn iter<'r>(&'r self) -> OptionIterator<&'r T> {
201         match *self {
202             Some(ref x) => OptionIterator{opt: Some(x)},
203             None => OptionIterator{opt: None}
204         }
205     }
206
207     /// Return a mutable iterator over the possibly contained value
208     #[inline]
209     pub fn mut_iter<'r>(&'r mut self) -> OptionIterator<&'r mut T> {
210         match *self {
211             Some(ref mut x) => OptionIterator{opt: Some(x)},
212             None => OptionIterator{opt: None}
213         }
214     }
215
216     /// Return a consuming iterator over the possibly contained value
217     #[inline]
218     pub fn move_iter(self) -> OptionIterator<T> {
219         OptionIterator{opt: self}
220     }
221
222     /////////////////////////////////////////////////////////////////////////
223     // Boolean operations on the values, eager and lazy
224     /////////////////////////////////////////////////////////////////////////
225
226     /// Returns `None` if the option is `None`, otherwise returns `optb`.
227     #[inline]
228     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
229         match self {
230             Some(_) => optb,
231             None => None,
232         }
233     }
234
235     /// Returns `None` if the option is `None`, otherwise calls `f` with the
236     /// wrapped value and returns the result.
237     #[inline]
238     pub fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U> {
239         match self {
240             Some(x) => f(x),
241             None => None,
242         }
243     }
244
245     /// Returns the option if it contains a value, otherwise returns `optb`.
246     #[inline]
247     pub fn or(self, optb: Option<T>) -> Option<T> {
248         match self {
249             Some(_) => self,
250             None => optb
251         }
252     }
253
254     /// Returns the option if it contains a value, otherwise calls `f` and
255     /// returns the result.
256     #[inline]
257     pub fn or_else(self, f: || -> Option<T>) -> Option<T> {
258         match self {
259             Some(_) => self,
260             None => f(),
261         }
262     }
263
264     /////////////////////////////////////////////////////////////////////////
265     // Misc
266     /////////////////////////////////////////////////////////////////////////
267
268     /// Take the value out of the option, leaving a `None` in its place.
269     #[inline]
270     pub fn take(&mut self) -> Option<T> {
271         util::replace(self, None)
272     }
273
274     /// Filters an optional value using a given function.
275     #[inline(always)]
276     pub fn filtered(self, f: |t: &T| -> bool) -> Option<T> {
277         match self {
278             Some(x) => if(f(&x)) {Some(x)} else {None},
279             None => None
280         }
281     }
282
283     /// Applies a function zero or more times until the result is `None`.
284     #[inline]
285     pub fn while_some(self, blk: |v: T| -> Option<T>) {
286         let mut opt = self;
287         while opt.is_some() {
288             opt = blk(opt.unwrap());
289         }
290     }
291
292     /////////////////////////////////////////////////////////////////////////
293     // Common special cases
294     /////////////////////////////////////////////////////////////////////////
295
296     /// The option dance. Moves a value out of an option type and returns it,
297     /// replacing the original with `None`.
298     ///
299     /// # Failure
300     ///
301     /// Fails if the value equals `None`.
302     #[inline]
303     pub fn take_unwrap(&mut self) -> T {
304         if self.is_none() {
305             fail!("called `Option::take_unwrap()` on a `None` value")
306         }
307         self.take().unwrap()
308     }
309
310     /// Gets an immutable reference to the value inside an option.
311     ///
312     /// # Failure
313     ///
314     /// Fails if the value equals `None`
315     ///
316     /// # Safety note
317     ///
318     /// In general, because this function may fail, its use is discouraged
319     /// (calling `get` on `None` is akin to dereferencing a null pointer).
320     /// Instead, prefer to use pattern matching and handle the `None`
321     /// case explicitly.
322     #[inline]
323     pub fn get_ref<'a>(&'a self) -> &'a T {
324         match *self {
325             Some(ref x) => x,
326             None => fail!("called `Option::get_ref()` on a `None` value"),
327         }
328     }
329
330     /// Gets a mutable reference to the value inside an option.
331     ///
332     /// # Failure
333     ///
334     /// Fails if the value equals `None`
335     ///
336     /// # Safety note
337     ///
338     /// In general, because this function may fail, its use is discouraged
339     /// (calling `get` on `None` is akin to dereferencing a null pointer).
340     /// Instead, prefer to use pattern matching and handle the `None`
341     /// case explicitly.
342     #[inline]
343     pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
344         match *self {
345             Some(ref mut x) => x,
346             None => fail!("called `Option::get_mut_ref()` on a `None` value"),
347         }
348     }
349 }
350
351 impl<T: Default> Option<T> {
352     /// Returns the contained value or default (for this type)
353     #[inline]
354     pub fn unwrap_or_default(self) -> T {
355         match self {
356             Some(x) => x,
357             None => Default::default()
358         }
359     }
360 }
361
362 /////////////////////////////////////////////////////////////////////////////
363 // Constructor extension trait
364 /////////////////////////////////////////////////////////////////////////////
365
366 /// A generic trait for converting a value to a `Option`
367 pub trait ToOption<T> {
368     /// Convert to the `option` type
369     fn to_option(&self) -> Option<T>;
370 }
371
372 /// A generic trait for converting a value to a `Option`
373 pub trait IntoOption<T> {
374     /// Convert to the `option` type
375     fn into_option(self) -> Option<T>;
376 }
377
378 /// A generic trait for converting a value to a `Option`
379 pub trait AsOption<T> {
380     /// Convert to the `option` type
381     fn as_option<'a>(&'a self) -> Option<&'a T>;
382 }
383
384 impl<T: Clone> ToOption<T> for Option<T> {
385     #[inline]
386     fn to_option(&self) -> Option<T> { self.clone() }
387 }
388
389 impl<T> IntoOption<T> for Option<T> {
390     #[inline]
391     fn into_option(self) -> Option<T> { self }
392 }
393
394 impl<T> AsOption<T> for Option<T> {
395     #[inline]
396     fn as_option<'a>(&'a self) -> Option<&'a T> {
397         match *self {
398             Some(ref x) => Some(x),
399             None => None,
400         }
401     }
402 }
403
404 /////////////////////////////////////////////////////////////////////////////
405 // Trait implementations
406 /////////////////////////////////////////////////////////////////////////////
407
408 impl<T: Clone> ToResult<T, ()> for Option<T> {
409     #[inline]
410     fn to_result(&self) -> Result<T, ()> {
411         match *self {
412             Some(ref x) => Ok(x.clone()),
413             None => Err(()),
414         }
415     }
416 }
417
418 impl<T> IntoResult<T, ()> for Option<T> {
419     #[inline]
420     fn into_result(self) -> Result<T, ()> {
421         match self {
422             Some(x) => Ok(x),
423             None => Err(()),
424         }
425     }
426 }
427
428 impl<T> AsResult<T, ()> for Option<T> {
429     #[inline]
430     fn as_result<'a>(&'a self) -> Result<&'a T, &'a ()> {
431         static UNIT: () = ();
432         match *self {
433             Some(ref t) => Ok(t),
434             None => Err(&UNIT),
435         }
436     }
437 }
438
439 impl<T: fmt::Default> fmt::Default for Option<T> {
440     #[inline]
441     fn fmt(s: &Option<T>, f: &mut fmt::Formatter) {
442         match *s {
443             Some(ref t) => write!(f.buf, "Some({})", *t),
444             None        => write!(f.buf, "None")
445         }
446     }
447 }
448
449 impl<T> Default for Option<T> {
450     #[inline]
451     fn default() -> Option<T> { None }
452 }
453
454 /////////////////////////////////////////////////////////////////////////////
455 // The Option Iterator
456 /////////////////////////////////////////////////////////////////////////////
457
458 /// An iterator that yields either one or zero elements
459 #[deriving(Clone, DeepClone)]
460 pub struct OptionIterator<A> {
461     priv opt: Option<A>
462 }
463
464 impl<A> Iterator<A> for OptionIterator<A> {
465     #[inline]
466     fn next(&mut self) -> Option<A> {
467         self.opt.take()
468     }
469
470     #[inline]
471     fn size_hint(&self) -> (uint, Option<uint>) {
472         match self.opt {
473             Some(_) => (1, Some(1)),
474             None => (0, Some(0)),
475         }
476     }
477 }
478
479 impl<A> DoubleEndedIterator<A> for OptionIterator<A> {
480     #[inline]
481     fn next_back(&mut self) -> Option<A> {
482         self.opt.take()
483     }
484 }
485
486 impl<A> ExactSize<A> for OptionIterator<A> {}
487
488 /////////////////////////////////////////////////////////////////////////////
489 // Tests
490 /////////////////////////////////////////////////////////////////////////////
491
492 #[cfg(test)]
493 mod tests {
494     use super::*;
495
496     use result::{IntoResult, ToResult};
497     use result::{Ok, Err};
498     use str::StrSlice;
499     use util;
500
501     #[test]
502     fn test_get_ptr() {
503         unsafe {
504             let x = ~0;
505             let addr_x: *int = ::cast::transmute(&*x);
506             let opt = Some(x);
507             let y = opt.unwrap();
508             let addr_y: *int = ::cast::transmute(&*y);
509             assert_eq!(addr_x, addr_y);
510         }
511     }
512
513     #[test]
514     fn test_get_str() {
515         let x = ~"test";
516         let addr_x = x.as_imm_buf(|buf, _len| buf);
517         let opt = Some(x);
518         let y = opt.unwrap();
519         let addr_y = y.as_imm_buf(|buf, _len| buf);
520         assert_eq!(addr_x, addr_y);
521     }
522
523     #[test]
524     fn test_get_resource() {
525         struct R {
526            i: @mut int,
527         }
528
529         #[unsafe_destructor]
530         impl ::ops::Drop for R {
531            fn drop(&mut self) { *(self.i) += 1; }
532         }
533
534         fn R(i: @mut int) -> R {
535             R {
536                 i: i
537             }
538         }
539
540         let i = @mut 0;
541         {
542             let x = R(i);
543             let opt = Some(x);
544             let _y = opt.unwrap();
545         }
546         assert_eq!(*i, 1);
547     }
548
549     #[test]
550     fn test_option_dance() {
551         let x = Some(());
552         let mut y = Some(5);
553         let mut y2 = 0;
554         for _x in x.iter() {
555             y2 = y.take_unwrap();
556         }
557         assert_eq!(y2, 5);
558         assert!(y.is_none());
559     }
560
561     #[test] #[should_fail]
562     fn test_option_too_much_dance() {
563         let mut y = Some(util::NonCopyable);
564         let _y2 = y.take_unwrap();
565         let _y3 = y.take_unwrap();
566     }
567
568     #[test]
569     fn test_and() {
570         let x: Option<int> = Some(1);
571         assert_eq!(x.and(Some(2)), Some(2));
572         assert_eq!(x.and(None::<int>), None);
573
574         let x: Option<int> = None;
575         assert_eq!(x.and(Some(2)), None);
576         assert_eq!(x.and(None::<int>), None);
577     }
578
579     #[test]
580     fn test_and_then() {
581         let x: Option<int> = Some(1);
582         assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
583         assert_eq!(x.and_then(|_| None::<int>), None);
584
585         let x: Option<int> = None;
586         assert_eq!(x.and_then(|x| Some(x + 1)), None);
587         assert_eq!(x.and_then(|_| None::<int>), None);
588     }
589
590     #[test]
591     fn test_or() {
592         let x: Option<int> = Some(1);
593         assert_eq!(x.or(Some(2)), Some(1));
594         assert_eq!(x.or(None), Some(1));
595
596         let x: Option<int> = None;
597         assert_eq!(x.or(Some(2)), Some(2));
598         assert_eq!(x.or(None), None);
599     }
600
601     #[test]
602     fn test_or_else() {
603         let x: Option<int> = Some(1);
604         assert_eq!(x.or_else(|| Some(2)), Some(1));
605         assert_eq!(x.or_else(|| None), Some(1));
606
607         let x: Option<int> = None;
608         assert_eq!(x.or_else(|| Some(2)), Some(2));
609         assert_eq!(x.or_else(|| None), None);
610     }
611
612     #[test]
613     fn test_option_while_some() {
614         let mut i = 0;
615         Some(10).while_some(|j| {
616             i += 1;
617             if (j > 0) {
618                 Some(j-1)
619             } else {
620                 None
621             }
622         });
623         assert_eq!(i, 11);
624     }
625
626     #[test]
627     fn test_unwrap() {
628         assert_eq!(Some(1).unwrap(), 1);
629         assert_eq!(Some(~"hello").unwrap(), ~"hello");
630     }
631
632     #[test]
633     #[should_fail]
634     fn test_unwrap_fail1() {
635         let x: Option<int> = None;
636         x.unwrap();
637     }
638
639     #[test]
640     #[should_fail]
641     fn test_unwrap_fail2() {
642         let x: Option<~str> = None;
643         x.unwrap();
644     }
645
646     #[test]
647     fn test_unwrap_or() {
648         let x: Option<int> = Some(1);
649         assert_eq!(x.unwrap_or(2), 1);
650
651         let x: Option<int> = None;
652         assert_eq!(x.unwrap_or(2), 2);
653     }
654
655     #[test]
656     fn test_unwrap_or_else() {
657         let x: Option<int> = Some(1);
658         assert_eq!(x.unwrap_or_else(|| 2), 1);
659
660         let x: Option<int> = None;
661         assert_eq!(x.unwrap_or_else(|| 2), 2);
662     }
663
664     #[test]
665     fn test_filtered() {
666         let some_stuff = Some(42);
667         let modified_stuff = some_stuff.filtered(|&x| {x < 10});
668         assert_eq!(some_stuff.unwrap(), 42);
669         assert!(modified_stuff.is_none());
670     }
671
672     #[test]
673     fn test_iter() {
674         let val = 5;
675
676         let x = Some(val);
677         let mut it = x.iter();
678
679         assert_eq!(it.size_hint(), (1, Some(1)));
680         assert_eq!(it.next(), Some(&val));
681         assert_eq!(it.size_hint(), (0, Some(0)));
682         assert!(it.next().is_none());
683     }
684
685     #[test]
686     fn test_mut_iter() {
687         let val = 5;
688         let new_val = 11;
689
690         let mut x = Some(val);
691         {
692             let mut it = x.mut_iter();
693
694             assert_eq!(it.size_hint(), (1, Some(1)));
695
696             match it.next() {
697                 Some(interior) => {
698                     assert_eq!(*interior, val);
699                     *interior = new_val;
700                 }
701                 None => assert!(false),
702             }
703
704             assert_eq!(it.size_hint(), (0, Some(0)));
705             assert!(it.next().is_none());
706         }
707         assert_eq!(x, Some(new_val));
708     }
709
710     #[test]
711     fn test_ord() {
712         let small = Some(1.0);
713         let big = Some(5.0);
714         let nan = Some(0.0/0.0);
715         assert!(!(nan < big));
716         assert!(!(nan > big));
717         assert!(small < big);
718         assert!(None < big);
719         assert!(big > None);
720     }
721
722     #[test]
723     fn test_mutate() {
724         let mut x = Some(3i);
725         assert!(x.mutate(|i| i+1));
726         assert_eq!(x, Some(4i));
727         assert!(x.mutate_default(0, |i| i+1));
728         assert_eq!(x, Some(5i));
729         x = None;
730         assert!(!x.mutate(|i| i+1));
731         assert_eq!(x, None);
732         assert!(!x.mutate_default(0i, |i| i+1));
733         assert_eq!(x, Some(0i));
734     }
735
736     #[test]
737     pub fn test_to_option() {
738         let some: Option<int> = Some(100);
739         let none: Option<int> = None;
740
741         assert_eq!(some.to_option(), Some(100));
742         assert_eq!(none.to_option(), None);
743     }
744
745     #[test]
746     pub fn test_into_option() {
747         let some: Option<int> = Some(100);
748         let none: Option<int> = None;
749
750         assert_eq!(some.into_option(), Some(100));
751         assert_eq!(none.into_option(), None);
752     }
753
754     #[test]
755     pub fn test_as_option() {
756         let some: Option<int> = Some(100);
757         let none: Option<int> = None;
758
759         assert_eq!(some.as_option().unwrap(), &100);
760         assert_eq!(none.as_option(), None);
761     }
762
763     #[test]
764     pub fn test_to_result() {
765         let some: Option<int> = Some(100);
766         let none: Option<int> = None;
767
768         assert_eq!(some.to_result(), Ok(100));
769         assert_eq!(none.to_result(), Err(()));
770     }
771
772     #[test]
773     pub fn test_into_result() {
774         let some: Option<int> = Some(100);
775         let none: Option<int> = None;
776
777         assert_eq!(some.into_result(), Ok(100));
778         assert_eq!(none.into_result(), Err(()));
779     }
780 }