Skip to content

Commit

Permalink
Unrolled build for rust-lang#136099
Browse files Browse the repository at this point in the history
Rollup merge of rust-lang#136099 - Kijewski:pr-rc-str-default, r=ibraheemdev

Optimize `Rc::<str>::default()` implementation

This PR lets `impl Default for Rc<str>` re-use the implementation for `Rc::<[u8]>::default()`. The previous version only calculted the memory layout at runtime, even though it should be known at compile time, resulting in an additional function call.

The same optimization is done for `Rc<CStr>`.

Generated byte code: <https://godbolt.org/z/dfq73jsoP>.

Resolves <rust-lang#135784>.

Cc `@Billy-Sheppard.`
  • Loading branch information
rust-timer authored Feb 8, 2025
2 parents 73bf794 + e090db8 commit b20b76c
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
5 changes: 3 additions & 2 deletions library/alloc/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -965,8 +965,9 @@ impl Default for Rc<CStr> {
/// This may or may not share an allocation with other Rcs on the same thread.
#[inline]
fn default() -> Self {
let c_str: &CStr = Default::default();
Rc::from(c_str)
let rc = Rc::<[u8]>::from(*b"\0");
// `[u8]` has the same layout as `CStr`, and it is `NUL` terminated.
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
}
}

Expand Down
4 changes: 3 additions & 1 deletion library/alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2369,7 +2369,9 @@ impl Default for Rc<str> {
/// This may or may not share an allocation with other Rcs on the same thread.
#[inline]
fn default() -> Self {
Rc::from("")
let rc = Rc::<[u8]>::default();
// `[u8]` has the same layout as `str`.
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
}
}

Expand Down

0 comments on commit b20b76c

Please sign in to comment.