Skip to content

Commit

Permalink
Add str.as_str() for easy dereferencing of Box<str>
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Sep 16, 2024
1 parent 13b5a4e commit a023a19
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 0 deletions.
1 change: 1 addition & 0 deletions library/alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@
#![feature(slice_ptr_get)]
#![feature(slice_range)]
#![feature(std_internals)]
#![feature(str_as_str)]
#![feature(str_internals)]
#![feature(strict_provenance)]
#![feature(trusted_fused)]
Expand Down
4 changes: 4 additions & 0 deletions library/alloc/src/rc/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<str> = Rc::from(s);
assert_eq!((&r).as_str(), "foo");
assert_eq!(r.as_str(), "foo");

assert_eq!(&r[..], "foo");
}
Expand Down
11 changes: 11 additions & 0 deletions library/core/src/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2736,6 +2736,17 @@ impl str {
pub fn substr_range(&self, substr: &str) -> Option<Range<usize>> {
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<str>` or `Arc<str>`.
#[inline]
#[unstable(feature = "str_as_str", issue = "130366")]
pub fn as_str(&self) -> &str {
self
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
1 change: 1 addition & 0 deletions library/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@
#![feature(slice_ptr_get)]
#![feature(slice_range)]
#![feature(std_internals)]
#![feature(str_as_str)]
#![feature(str_internals)]
#![feature(strict_provenance)]
#![feature(strict_provenance_atomic_ptr)]
Expand Down

0 comments on commit a023a19

Please sign in to comment.