Skip to content

Commit bcb9034

Browse files
committed
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>.
1 parent 68f6b01 commit bcb9034

File tree

2 files changed

+6
-3
lines changed

2 files changed

+6
-3
lines changed

Diff for: alloc/src/ffi/c_str.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -965,8 +965,9 @@ impl Default for Rc<CStr> {
965965
/// This may or may not share an allocation with other Rcs on the same thread.
966966
#[inline]
967967
fn default() -> Self {
968-
let c_str: &CStr = Default::default();
969-
Rc::from(c_str)
968+
let rc = Rc::<[u8]>::from(*b"\0");
969+
// `[u8]` has the same layout as `CStr`, and it is `NUL` terminated.
970+
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
970971
}
971972
}
972973

Diff for: alloc/src/rc.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -2369,7 +2369,9 @@ impl Default for Rc<str> {
23692369
/// This may or may not share an allocation with other Rcs on the same thread.
23702370
#[inline]
23712371
fn default() -> Self {
2372-
Rc::from("")
2372+
let rc = Rc::<[u8]>::default();
2373+
// `[u8]` has the same layout as `str`.
2374+
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
23732375
}
23742376
}
23752377

0 commit comments

Comments
 (0)