Skip to content

Commit 81c4805

Browse files
committed
Add str.as_str() for easy dereferencing of Box<str>
1 parent 03ff0df commit 81c4805

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

alloc/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
// tidy-alphabetical-start
9494
#![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))]
9595
#![cfg_attr(not(no_global_oom_handling), feature(const_btree_len))]
96+
#![cfg_attr(test, feature(str_as_str))]
9697
#![feature(alloc_layout_extra)]
9798
#![feature(allocator_api)]
9899
#![feature(array_chunks)]

alloc/src/rc/tests.rs

+4
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,11 @@ fn test_from_box_str() {
448448
use std::string::String;
449449

450450
let s = String::from("foo").into_boxed_str();
451+
assert_eq!((&&&s).as_str(), "foo");
452+
451453
let r: Rc<str> = Rc::from(s);
454+
assert_eq!((&r).as_str(), "foo");
455+
assert_eq!(r.as_str(), "foo");
452456

453457
assert_eq!(&r[..], "foo");
454458
}

core/src/str/mod.rs

+11
Original file line numberDiff line numberDiff line change
@@ -2737,6 +2737,17 @@ impl str {
27372737
pub fn substr_range(&self, substr: &str) -> Option<Range<usize>> {
27382738
self.as_bytes().subslice_range(substr.as_bytes())
27392739
}
2740+
2741+
/// Returns the same string as a string slice `&str`.
2742+
///
2743+
/// This method is redundant when used directly on `&str`, but
2744+
/// it helps dereferencing other string-like types to string slices,
2745+
/// for example references to `Box<str>` or `Arc<str>`.
2746+
#[inline]
2747+
#[unstable(feature = "str_as_str", issue = "130366")]
2748+
pub fn as_str(&self) -> &str {
2749+
self
2750+
}
27402751
}
27412752

27422753
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)