From 81c4805e8ad43352d4033d3086abca4b4ac168c5 Mon Sep 17 00:00:00 2001 From: Kornel Date: Sun, 25 Aug 2024 11:20:42 +0100 Subject: [PATCH] Add str.as_str() for easy dereferencing of Box --- alloc/src/lib.rs | 1 + alloc/src/rc/tests.rs | 4 ++++ core/src/str/mod.rs | 11 +++++++++++ 3 files changed, 16 insertions(+) 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 9373d807f44e3..5b20e681c2409 100644 --- a/core/src/str/mod.rs +++ b/core/src/str/mod.rs @@ -2737,6 +2737,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")]