Skip to content

Commit ed27e35

Browse files
committed
Use transmute in core::fmt::rt to improve perf.
This avoids creating NonZero<Usize>s, saving a bunch of queries.
1 parent 44e7fa8 commit ed27e35

File tree

1 file changed

+10
-8
lines changed
  • library/core/src/fmt

1 file changed

+10
-8
lines changed

library/core/src/fmt/rt.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
use super::*;
1010
use crate::hint::unreachable_unchecked;
1111
use crate::marker::PhantomData;
12-
use crate::num::NonZeroUsize;
12+
use crate::mem;
1313
use crate::ptr::NonNull;
1414

1515
#[lang = "format_template"]
@@ -31,17 +31,17 @@ impl<'a> Template<'a> {
3131

3232
#[inline]
3333
pub const unsafe fn new_str_len(len: usize) -> Self {
34+
let bits = len << 1 | 1;
3435
// SAFETY: We set the lowest bit, so it's nonzero.
35-
let bits = unsafe { NonZeroUsize::new_unchecked(len << 1 | 1) };
36-
Self { pieces: NonNull::without_provenance(bits), lifetime: PhantomData }
36+
Self { pieces: unsafe { mem::transmute(bits) }, lifetime: PhantomData }
3737
}
3838

3939
#[inline]
4040
pub const fn as_str_len(self) -> Option<usize> {
4141
// SAFETY: During const eval, `self.pieces` must have come from a usize, not a pointer,
4242
// because `new()` above is not const.
4343
// Outside const eval, transmuting a pointer to a usize is fine.
44-
let bits = unsafe { crate::mem::transmute::<_, usize>(self.pieces) };
44+
let bits: usize = unsafe { mem::transmute(self.pieces) };
4545
if bits & 1 == 1 { Some(bits >> 1) } else { None }
4646
}
4747

@@ -243,10 +243,12 @@ impl<'a> Arguments<'a> {
243243

244244
#[inline]
245245
pub const fn from_str(s: &'static str) -> Arguments<'a> {
246-
Arguments {
247-
// SAFETY: This is the "static str" representation of fmt::Arguments.
248-
template: unsafe { rt::Template::new_str_len(s.len()) },
249-
args: NonNull::from_ref(s).cast(),
246+
// SAFETY: This is the "static str" representation of fmt::Arguments.
247+
unsafe {
248+
Arguments {
249+
template: rt::Template::new_str_len(s.len()),
250+
args: mem::transmute(s.as_ptr()),
251+
}
250252
}
251253
}
252254

0 commit comments

Comments
 (0)