about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2024-09-23 06:45:32 +0200
committerGitHub <noreply@github.com>2024-09-23 06:45:32 +0200
commit510fc3432eb3e61f0bae766ddca720052a99aa6a (patch)
tree4a69aeebfd71151657a7d322f77d0f685c6a0f89
parent66b0b29e65c77e5801c308e725a233c0728df300 (diff)
parent3dcb5a39622fe705647ea0764a355a10b6913832 (diff)
Rollup merge of #129550 - kornelski:boxasstr, r=joshtriplett,dtolnay
Add str.as_str() for easy Deref to string slices

Working with `Box<str>` is cumbersome, because in places like `iter.filter()` it can end up being `&Box<str>` or even `&&Box<str>`, and such type doesn't always get auto-dereferenced as expected.

Dereferencing such box to `&str` requires ugly syntax like `&**boxed_str` or `&***boxed_str`, with the exact amount of `*`s.

`Box<str>` is [not easily comparable with other string types](https://github.com/rust-lang/rust/pull/129852) via `PartialEq`. `Box<str>` won't work for lookups in types like `HashSet<String>`, because `Borrow<String>` won't take types like `&Box<str>`. OTOH `set.contains(s.as_str())` works nicely regardless of levels of indirection.

`String` has a simple solution for this: the `as_str()` method, and `Box<str>` should too.
-rw-r--r--compiler/rustc_hir_typeck/src/method/suggest.rs15
-rw-r--r--library/alloc/src/lib.rs1
-rw-r--r--library/alloc/src/rc/tests.rs4
-rw-r--r--library/core/src/str/mod.rs11
-rw-r--r--tests/ui/suggestions/remove-as_str.rs21
-rw-r--r--tests/ui/suggestions/remove-as_str.stderr27
6 files changed, 17 insertions, 62 deletions
diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs
index 805fb39480c..feb47209f5e 100644
--- a/compiler/rustc_hir_typeck/src/method/suggest.rs
+++ b/compiler/rustc_hir_typeck/src/method/suggest.rs
@@ -1721,20 +1721,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
             }
         }
 
-        if item_name.name == sym::as_str && rcvr_ty.peel_refs().is_str() {
-            let msg = "remove this method call";
-            let mut fallback_span = true;
-            if let SelfSource::MethodCall(expr) = source {
-                let call_expr = self.tcx.hir().expect_expr(self.tcx.parent_hir_id(expr.hir_id));
-                if let Some(span) = call_expr.span.trim_start(expr.span) {
-                    err.span_suggestion(span, msg, "", Applicability::MachineApplicable);
-                    fallback_span = false;
-                }
-            }
-            if fallback_span {
-                err.span_label(span, msg);
-            }
-        } else if let Some(similar_candidate) = similar_candidate {
+        if let Some(similar_candidate) = similar_candidate {
             // Don't emit a suggestion if we found an actual method
             // that had unsatisfied trait bounds
             if unsatisfied_predicates.is_empty()
diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs
index f0597f295b3..ff5ddd16e07 100644
--- a/library/alloc/src/lib.rs
+++ b/library/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/library/alloc/src/rc/tests.rs b/library/alloc/src/rc/tests.rs
index 84e8b325f71..333e1bde31c 100644
--- a/library/alloc/src/rc/tests.rs
+++ b/library/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<str> = Rc::from(s);
+    assert_eq!((&r).as_str(), "foo");
+    assert_eq!(r.as_str(), "foo");
 
     assert_eq!(&r[..], "foo");
 }
diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs
index 712bf011c27..300dde3dd43 100644
--- a/library/core/src/str/mod.rs
+++ b/library/core/src/str/mod.rs
@@ -2740,6 +2740,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")]
diff --git a/tests/ui/suggestions/remove-as_str.rs b/tests/ui/suggestions/remove-as_str.rs
deleted file mode 100644
index 289a784ba6a..00000000000
--- a/tests/ui/suggestions/remove-as_str.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-fn foo1(s: &str) {
-    s.as_str();
-    //~^ ERROR no method named `as_str` found
-}
-
-fn foo2<'a>(s: &'a str) {
-    s.as_str();
-    //~^ ERROR no method named `as_str` found
-}
-
-fn foo3(s: &mut str) {
-    s.as_str();
-    //~^ ERROR no method named `as_str` found
-}
-
-fn foo4(s: &&str) {
-    s.as_str();
-    //~^ ERROR no method named `as_str` found
-}
-
-fn main() {}
diff --git a/tests/ui/suggestions/remove-as_str.stderr b/tests/ui/suggestions/remove-as_str.stderr
deleted file mode 100644
index 534c497780a..00000000000
--- a/tests/ui/suggestions/remove-as_str.stderr
+++ /dev/null
@@ -1,27 +0,0 @@
-error[E0599]: no method named `as_str` found for reference `&str` in the current scope
-  --> $DIR/remove-as_str.rs:2:7
-   |
-LL |     s.as_str();
-   |      -^^^^^^-- help: remove this method call
-
-error[E0599]: no method named `as_str` found for reference `&'a str` in the current scope
-  --> $DIR/remove-as_str.rs:7:7
-   |
-LL |     s.as_str();
-   |      -^^^^^^-- help: remove this method call
-
-error[E0599]: no method named `as_str` found for mutable reference `&mut str` in the current scope
-  --> $DIR/remove-as_str.rs:12:7
-   |
-LL |     s.as_str();
-   |      -^^^^^^-- help: remove this method call
-
-error[E0599]: no method named `as_str` found for reference `&&str` in the current scope
-  --> $DIR/remove-as_str.rs:17:7
-   |
-LL |     s.as_str();
-   |      -^^^^^^-- help: remove this method call
-
-error: aborting due to 4 previous errors
-
-For more information about this error, try `rustc --explain E0599`.