diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 38b1766c17440..dfe1868abfc0a 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -1553,6 +1553,42 @@ impl Clone for Box { } } +// This is the same impl as `Cow<'a, str>`, but with a newer stability attribute. +// It needs to be in this file to refer to the Box as a local struct rather than as a lang-item. +macro_rules! impl_eq { + ($lhs:ty, $rhs: ty) => { + #[stable(feature = "box_str_partial_eq", since = "CURRENT_RUSTC_VERSION")] + #[allow(unused_lifetimes)] + impl<'a, 'b> PartialEq<$rhs> for $lhs { + #[inline] + fn eq(&self, other: &$rhs) -> bool { + PartialEq::eq(&self[..], &other[..]) + } + #[inline] + fn ne(&self, other: &$rhs) -> bool { + PartialEq::ne(&self[..], &other[..]) + } + } + + #[stable(feature = "box_str_partial_eq", since = "CURRENT_RUSTC_VERSION")] + #[allow(unused_lifetimes)] + impl<'a, 'b> PartialEq<$lhs> for $rhs { + #[inline] + fn eq(&self, other: &$lhs) -> bool { + PartialEq::eq(&self[..], &other[..]) + } + #[inline] + fn ne(&self, other: &$lhs) -> bool { + PartialEq::ne(&self[..], &other[..]) + } + } + }; +} + +impl_eq! { Box, str } +impl_eq! { Box, &'a str } +impl_eq! { Box, String } + #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for Box { #[inline] @@ -1564,6 +1600,7 @@ impl PartialEq for Box { PartialEq::ne(&**self, &**other) } } + #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for Box { #[inline] diff --git a/library/alloc/tests/str.rs b/library/alloc/tests/str.rs index a6b1fe5b97945..abfedbfa46a37 100644 --- a/library/alloc/tests/str.rs +++ b/library/alloc/tests/str.rs @@ -13,6 +13,29 @@ fn test_le() { assert_ne!("foo", "bar"); } +#[test] +fn test_box_str_eq() { + let boxed: Box = Box::from("boxed"); + assert!(*"boxed" == boxed); + assert!(*"other" != boxed); + assert!(boxed == *"boxed"); + assert!(boxed != *"other"); + + assert!(&"boxed" == &boxed); + assert!(&boxed == &"boxed"); + assert!(&"BOXED" != &boxed); + assert!(&boxed != &"BOXED"); + + assert_eq!(Box::from("foo"), "foo"); + assert_eq!("bar", Box::from("bar")); + + assert_ne!(Box::from("foo"), "bar"); + assert_ne!("bar", Box::from("foo")); + + assert!("" == Box::from("")); + assert!("本" == String::from("本").into_boxed_str()); +} + #[test] fn test_find() { assert_eq!("hello".find('l'), Some(2));