Skip to content

Commit 38f4f4a

Browse files
committed
Use constant for detecting thin pointer formatting
This allows codegen to prune the unnecessary side of the `if` for each pointer type during monomorphization. LLVM optimizations can clean it up too, but it's better to not emit unnecessary code in the first place.
1 parent 5930afc commit 38f4f4a

2 files changed

Lines changed: 6 additions & 11 deletions

File tree

library/core/src/fmt/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3000,7 +3000,7 @@ impl<T: PointeeSized> Pointer for *const T {
30003000
// metadata type to reduce the amount of codegen work needed for each distinct type.
30013001
let ptr: *const T = *self;
30023002
let ptr_addr = ptr.expose_provenance();
3003-
if <<T as core::ptr::Pointee>::Metadata as core::unit::IsUnit>::is_unit() {
3003+
if <<T as core::ptr::Pointee>::Metadata as core::unit::IsUnit>::IS_UNIT {
30043004
pointer_fmt_inner(ptr_addr, f)
30053005
} else {
30063006
wide_pointer_fmt_inner(ptr_addr, &core::ptr::metadata(ptr), f)

library/core/src/unit.rs

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use crate::intrinsics::type_id;
2+
13
/// Collapses all unit items from an iterator into one.
24
///
35
/// This is more useful when combined with higher-level abstractions, like
@@ -19,17 +21,10 @@ impl FromIterator<()> for () {
1921
}
2022

2123
pub(crate) trait IsUnit {
22-
fn is_unit() -> bool;
24+
const IS_UNIT: bool;
2325
}
2426

2527
impl<T: ?Sized> IsUnit for T {
26-
default fn is_unit() -> bool {
27-
false
28-
}
29-
}
30-
31-
impl IsUnit for () {
32-
fn is_unit() -> bool {
33-
true
34-
}
28+
// `type_id` erases lifetimes, but that's OK here because "is it ()" never depends on lifetimes
29+
const IS_UNIT: bool = type_id::<Self>() == type_id::<()>();
3530
}

0 commit comments

Comments
 (0)