Skip to content

Commit

Permalink
impl Add<Output = String> for &str
Browse files Browse the repository at this point in the history
  • Loading branch information
jyn514 committed Feb 9, 2022
1 parent b7cd0f7 commit 0fa56d7
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions compiler/rustc_hir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ language_item_table! {
Slice, sym::slice, slice_impl, Target::Impl, GenericRequirement::None;
SliceU8, sym::slice_u8, slice_u8_impl, Target::Impl, GenericRequirement::None;
StrAlloc, sym::str_alloc, str_alloc_impl, Target::Impl, GenericRequirement::None;
StrAllocAdd, sym::str_alloc_add, str_alloc_add_impl, Target::Impl, GenericRequirement::None;
SliceAlloc, sym::slice_alloc, slice_alloc_impl, Target::Impl, GenericRequirement::None;
SliceU8Alloc, sym::slice_u8_alloc, slice_u8_alloc_impl, Target::Impl, GenericRequirement::None;
ConstPtr, sym::const_ptr, const_ptr_impl, Target::Impl, GenericRequirement::None;
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,7 @@ symbols! {
store,
str,
str_alloc,
str_alloc_add,
stringify,
stringify_macro,
struct_field_attributes,
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_trait_selection/src/traits/coherence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,11 @@ pub enum OrphanCheckErr<'tcx> {
pub fn orphan_check(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Result<(), OrphanCheckErr<'_>> {
debug!("orphan_check({:?})", impl_def_id);

// `alloc` breaks coherence so it can define `&str + &str = String`
if Some(impl_def_id) == tcx.lang_items().str_alloc_add_impl() {
return Ok(());
}

// We only except this routine to be invoked on implementations
// of a trait, not inherent implementations.
let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
Expand Down
17 changes: 17 additions & 0 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2215,6 +2215,23 @@ impl AddAssign<&str> for String {
}
}

#[cfg(not(no_global_oom_handling))]
#[cfg(not(bootstrap))]
#[lang = "str_alloc_add"]
#[stable(feature = "stradd", since = "1.60.0")]
/// # Examples
/// ```
/// let hello: String = "hello, " + "world!";
/// println!("{}", hello);
/// ```
impl core::ops::Add<&str> for &str {
type Output = String;

fn add(self, other: &str) -> String {
String::from(self) + other
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::Range<usize>> for String {
type Output = str;
Expand Down

0 comments on commit 0fa56d7

Please sign in to comment.