Skip to content

Commit 9702fb9

Browse files
committed
make cloned generic over deref... and have its tests actually run
1 parent f092793 commit 9702fb9

File tree

2 files changed

+29
-12
lines changed

2 files changed

+29
-12
lines changed

src/libcore/option.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ use result::{Result, Ok, Err};
153153
use slice;
154154
use slice::AsSlice;
155155
use clone::Clone;
156+
use ops::Deref;
156157

157158
// Note that this is not a lang item per se, but it has a hidden dependency on
158159
// `Iterator`, which is one. The compiler assumes that the `next` method of
@@ -694,11 +695,12 @@ impl<T> Option<T> {
694695
}
695696
}
696697

697-
impl<'a, T: Clone> Option<&'a T> {
698-
/// Maps an Option<&T> to an Option<T> by cloning the contents of the Option<&T>.
698+
impl<'a, T: Clone, D: Deref<T>> Option<D> {
699+
/// Maps an Option<D> to an Option<T> by dereffing and cloning the contents of the Option.
700+
/// Useful for converting an Option<&T> to an Option<T>.
699701
#[unstable = "recently added as part of collections reform"]
700702
pub fn cloned(self) -> Option<T> {
701-
self.map(|t| t.clone())
703+
self.map(|t| t.deref().clone())
702704
}
703705
}
704706

src/libcoretest/option.rs

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -241,14 +241,29 @@ fn test_collect() {
241241
assert!(v == None);
242242
}
243243

244+
#[test]
244245
fn test_cloned() {
245-
let s = 1u32;
246-
let n: Option<&'static u32> = None;
247-
let o = Some(&s);
248-
249-
assert_eq!(o.clone(), Some(&s));
250-
assert_eq!(o.cloned(), Some(1u32));
251-
252-
assert_eq!(n.clone(), None);
253-
assert_eq!(n.cloned(), None);
246+
let val1 = 1u32;
247+
let mut val2 = 2u32;
248+
let val1_ref = &val1;
249+
let opt_none: Option<&'static u32> = None;
250+
let opt_ref = Some(&val1);
251+
let opt_ref_ref = Some(&val1_ref);
252+
let opt_mut_ref = Some(&mut val2);
253+
254+
// None works
255+
assert_eq!(opt_none.clone(), None);
256+
assert_eq!(opt_none.cloned(), None);
257+
258+
// Mutable refs work
259+
assert_eq!(opt_mut_ref.cloned(), Some(2u32));
260+
261+
// Immutable ref works
262+
assert_eq!(opt_ref.clone(), Some(&val1));
263+
assert_eq!(opt_ref.cloned(), Some(1u32));
264+
265+
// Double Immutable ref works
266+
assert_eq!(opt_ref_ref.clone(), Some(&val1_ref));
267+
assert_eq!(opt_ref_ref.clone().cloned(), Some(&val1));
268+
assert_eq!(opt_ref_ref.cloned().cloned(), Some(1u32));
254269
}

0 commit comments

Comments
 (0)