diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs index 88876999d765a..53898f8a444b6 100644 --- a/src/liballoc/slice.rs +++ b/src/liballoc/slice.rs @@ -973,8 +973,9 @@ impl [T] { /// assert!(!v.contains(&50)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn contains(&self, x: &T) -> bool - where T: PartialEq + pub fn contains(&self, x: &Q) -> bool + where T: Borrow, + Q: PartialEq { core_slice::SliceExt::contains(self, x) } diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs index 7fa65a2144e9b..86ad7712707db 100644 --- a/src/liballoc/tests/slice.rs +++ b/src/liballoc/tests/slice.rs @@ -367,6 +367,26 @@ fn test_binary_search() { assert_eq!([1, 2, 3, 4, 5].binary_search(&0).ok(), None); } +#[test] +fn test_contains() { + assert!([5, 4, 3, 2, 1].contains(&2)); + let empty: &[i32] = &[][..]; + assert!(!empty.contains(&1)); + + // Tests that Borrow functions. + let string_slice = [String::from("abc"), String::from("def")]; + assert!(string_slice.contains(&String::from("abc"))); + assert!(!string_slice.contains(&String::from("ab"))); + assert!(string_slice.contains("abc")); + assert!(!string_slice.contains("ab")); + + let vecu8_slice = [b"abc".to_vec(), b"def".to_vec()]; + assert!(vecu8_slice.contains(&b"abc".to_vec())); + assert!(!vecu8_slice.contains(&b"ab".to_vec())); + assert!(vecu8_slice.contains(&b"abc"[..])); + assert!(!vecu8_slice.contains(&b"ab"[..])); +} + #[test] fn test_reverse() { let mut v = vec![10, 20]; diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index ce5da9ec2d521..0641deffe0954 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -195,7 +195,9 @@ pub trait SliceExt { fn as_mut_ptr(&mut self) -> *mut Self::Item; #[stable(feature = "core", since = "1.6.0")] - fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq; + fn contains(&self, x: &Q) -> bool + where Self::Item: Borrow, + Q: PartialEq; #[stable(feature = "core", since = "1.6.0")] fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq; @@ -616,8 +618,11 @@ impl SliceExt for [T] { } #[inline] - fn contains(&self, x: &T) -> bool where T: PartialEq { - self.iter().any(|elt| *x == *elt) + fn contains(&self, x: &Q) -> bool + where T: Borrow, + Q: PartialEq + { + self.iter().any(|elt| *x == *elt.borrow()) } #[inline] diff --git a/src/librustc/ty/inhabitedness/def_id_forest.rs b/src/librustc/ty/inhabitedness/def_id_forest.rs index 6801e82fe7476..86794b26b2e6a 100644 --- a/src/librustc/ty/inhabitedness/def_id_forest.rs +++ b/src/librustc/ty/inhabitedness/def_id_forest.rs @@ -110,7 +110,7 @@ impl<'a, 'gcx, 'tcx> DefIdForest { where I: IntoIterator { let mut ret = DefIdForest::empty(); - let mut next_ret = SmallVec::new(); + let mut next_ret: SmallVec<[DefId; 1]> = SmallVec::new(); for next_forest in iter { for id in ret.root_ids.drain(..) { if !next_forest.contains(tcx, id) {