diff options
| author | René Kijewski <rene.kijewski@fu-berlin.de> | 2025-01-26 19:12:54 +0100 |
|---|---|---|
| committer | René Kijewski <rene.kijewski@fu-berlin.de> | 2025-01-26 19:12:54 +0100 |
| commit | e090db8d226ab23f64d57ab1b56b999f6e4097fd (patch) | |
| tree | d54571a3ca27468a01fd45ff0a588b9ce1d167a4 /library/alloc/src | |
| parent | 15c6f7e1a3a0e51c9b18ce5b9a391e0c324b751c (diff) | |
| download | rust-e090db8d226ab23f64d57ab1b56b999f6e4097fd.tar.gz rust-e090db8d226ab23f64d57ab1b56b999f6e4097fd.zip | |
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 <https://github.com/rust-lang/rust/issues/135784>.
Diffstat (limited to 'library/alloc/src')
| -rw-r--r-- | library/alloc/src/ffi/c_str.rs | 5 | ||||
| -rw-r--r-- | library/alloc/src/rc.rs | 4 |
2 files changed, 6 insertions, 3 deletions
diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs index c7d6d8a55c2..07c75677d05 100644 --- a/library/alloc/src/ffi/c_str.rs +++ b/library/alloc/src/ffi/c_str.rs @@ -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) } } } diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index ae3318b839d..05e76ccf685 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -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) } } } |
