diff options
| author | Alexis Beingessner <a.beingessner@gmail.com> | 2014-11-17 20:59:46 -0500 |
|---|---|---|
| committer | Alexis Beingessner <a.beingessner@gmail.com> | 2014-11-18 08:34:42 -0500 |
| commit | 9702fb9c7b8d1b58e6b26b3c730c69c520dcd588 (patch) | |
| tree | 7ab8428e0687fa77eeb55ee8a35ba1cf35a0461e | |
| parent | f09279395b6ca40f1398277971586197f949738a (diff) | |
| download | rust-9702fb9c7b8d1b58e6b26b3c730c69c520dcd588.tar.gz rust-9702fb9c7b8d1b58e6b26b3c730c69c520dcd588.zip | |
make cloned generic over deref... and have its tests actually run
| -rw-r--r-- | src/libcore/option.rs | 8 | ||||
| -rw-r--r-- | src/libcoretest/option.rs | 33 |
2 files changed, 29 insertions, 12 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 5b1590518f8..19938973037 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -153,6 +153,7 @@ use result::{Result, Ok, Err}; use slice; use slice::AsSlice; use clone::Clone; +use ops::Deref; // Note that this is not a lang item per se, but it has a hidden dependency on // `Iterator`, which is one. The compiler assumes that the `next` method of @@ -694,11 +695,12 @@ impl<T> Option<T> { } } -impl<'a, T: Clone> Option<&'a T> { - /// Maps an Option<&T> to an Option<T> by cloning the contents of the Option<&T>. +impl<'a, T: Clone, D: Deref<T>> Option<D> { + /// Maps an Option<D> to an Option<T> by dereffing and cloning the contents of the Option. + /// Useful for converting an Option<&T> to an Option<T>. #[unstable = "recently added as part of collections reform"] pub fn cloned(self) -> Option<T> { - self.map(|t| t.clone()) + self.map(|t| t.deref().clone()) } } diff --git a/src/libcoretest/option.rs b/src/libcoretest/option.rs index 6138986e1d1..a5927d47eb0 100644 --- a/src/libcoretest/option.rs +++ b/src/libcoretest/option.rs @@ -241,14 +241,29 @@ fn test_collect() { assert!(v == None); } +#[test] fn test_cloned() { - let s = 1u32; - let n: Option<&'static u32> = None; - let o = Some(&s); - - assert_eq!(o.clone(), Some(&s)); - assert_eq!(o.cloned(), Some(1u32)); - - assert_eq!(n.clone(), None); - assert_eq!(n.cloned(), None); + let val1 = 1u32; + let mut val2 = 2u32; + let val1_ref = &val1; + let opt_none: Option<&'static u32> = None; + let opt_ref = Some(&val1); + let opt_ref_ref = Some(&val1_ref); + let opt_mut_ref = Some(&mut val2); + + // None works + assert_eq!(opt_none.clone(), None); + assert_eq!(opt_none.cloned(), None); + + // Mutable refs work + assert_eq!(opt_mut_ref.cloned(), Some(2u32)); + + // Immutable ref works + assert_eq!(opt_ref.clone(), Some(&val1)); + assert_eq!(opt_ref.cloned(), Some(1u32)); + + // Double Immutable ref works + assert_eq!(opt_ref_ref.clone(), Some(&val1_ref)); + assert_eq!(opt_ref_ref.clone().cloned(), Some(&val1)); + assert_eq!(opt_ref_ref.cloned().cloned(), Some(1u32)); } \ No newline at end of file |
