diff --git a/alloc/src/lib.rs b/alloc/src/lib.rs index f0597f295b3f0..ff5ddd16e07e3 100644 --- a/alloc/src/lib.rs +++ b/alloc/src/lib.rs @@ -93,6 +93,7 @@ // tidy-alphabetical-start #![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))] #![cfg_attr(not(no_global_oom_handling), feature(const_btree_len))] +#![cfg_attr(test, feature(str_as_str))] #![feature(alloc_layout_extra)] #![feature(allocator_api)] #![feature(array_chunks)] diff --git a/alloc/src/rc/tests.rs b/alloc/src/rc/tests.rs index 84e8b325f71fc..333e1bde31c1e 100644 --- a/alloc/src/rc/tests.rs +++ b/alloc/src/rc/tests.rs @@ -448,7 +448,11 @@ fn test_from_box_str() { use std::string::String; let s = String::from("foo").into_boxed_str(); + assert_eq!((&&&s).as_str(), "foo"); + let r: Rc = Rc::from(s); + assert_eq!((&r).as_str(), "foo"); + assert_eq!(r.as_str(), "foo"); assert_eq!(&r[..], "foo"); } diff --git a/core/src/str/mod.rs b/core/src/str/mod.rs index 712bf011c273e..300dde3dd4396 100644 --- a/core/src/str/mod.rs +++ b/core/src/str/mod.rs @@ -2740,6 +2740,17 @@ impl str { pub fn substr_range(&self, substr: &str) -> Option> { self.as_bytes().subslice_range(substr.as_bytes()) } + + /// Returns the same string as a string slice `&str`. + /// + /// This method is redundant when used directly on `&str`, but + /// it helps dereferencing other string-like types to string slices, + /// for example references to `Box` or `Arc`. + #[inline] + #[unstable(feature = "str_as_str", issue = "130366")] + pub fn as_str(&self) -> &str { + self + } } #[stable(feature = "rust1", since = "1.0.0")]