diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs index 18bb13d847a87..da6254092382d 100644 --- a/src/liballoc/slice.rs +++ b/src/liballoc/slice.rs @@ -980,8 +980,8 @@ 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: &U) -> bool + where U: ?Sized, T: PartialEq { core_slice::SliceExt::contains(self, x) } diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs index 85d5ce304b88d..d1642b1cdc75f 100644 --- a/src/liballoc/tests/slice.rs +++ b/src/liballoc/tests/slice.rs @@ -1051,6 +1051,20 @@ fn test_shrink_to_fit() { assert_eq!(xs, (0..100).collect::>()); } +#[test] +fn test_contains() { + let numbers = [1, 2, 3]; + assert!(numbers.contains(&2)); + assert!(!numbers.contains(&4)); + + let strings = vec![String::from("AB"), String::from("CD")]; + assert!(strings.contains(&String::from("AB"))); + assert!(!strings.contains(&String::from("A"))); + assert!(strings.contains(&"AB")); + assert!(!strings.contains(&"BC")); + assert!(strings.contains("AB")); +} + #[test] fn test_starts_with() { assert!(b"foobar".starts_with(b"foo")); diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index ca5cf04b1d437..963923dbeddf9 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -192,7 +192,7 @@ 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: &U) -> bool where U: ?Sized, Self::Item: PartialEq; #[stable(feature = "core", since = "1.6.0")] fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq; @@ -618,8 +618,8 @@ impl SliceExt for [T] { } #[inline] - fn contains(&self, x: &T) -> bool where T: PartialEq { - self.iter().any(|elt| *x == *elt) + fn contains(&self, x: &U) -> bool where U: ?Sized, T: PartialEq { + self.iter().any(|e| e == x) } #[inline] diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 1ca995cae6d97..42eb1cb10bdcc 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1608,6 +1608,22 @@ mod traits { fn ne(&self, other: &str) -> bool { !(*self).eq(other) } } + #[unstable(feature = "str_str_ref_partialeq", issue = "46934")] + impl<'a> PartialEq<&'a str> for str { + #[inline] + fn eq(&self, other: &&'a str) -> bool { self == *other } + #[inline] + fn ne(&self, other: &&'a str) -> bool { self != *other } + } + + #[unstable(feature = "str_str_ref_partialeq", issue = "46934")] + impl<'a> PartialEq for &'a str { + #[inline] + fn eq(&self, other: &str) -> bool { *self == other } + #[inline] + fn ne(&self, other: &str) -> bool { *self != other } + } + #[stable(feature = "rust1", since = "1.0.0")] impl Eq for str {}