Skip to content

Commit 8f2599d

Browse files
committed
Auto merge of rust-lang#102596 - scottmcm:option-bool-calloc, r=Mark-Simulacrum
Do the `calloc` optimization for `Option<bool>` Inspired by <https://old.reddit.com/r/rust/comments/xtiqj8/why_is_this_functional_version_faster_than_my_for/iqqy37b/>.
2 parents 8d2f440 + 4aa512e commit 8f2599d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

alloc/src/vec/is_zero.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,25 @@ unsafe impl<T: IsZero> IsZero for Saturating<T> {
160160
self.0.is_zero()
161161
}
162162
}
163+
164+
macro_rules! impl_for_optional_bool {
165+
($($t:ty,)+) => {$(
166+
unsafe impl IsZero for $t {
167+
#[inline]
168+
fn is_zero(&self) -> bool {
169+
// SAFETY: This is *not* a stable layout guarantee, but
170+
// inside `core` we're allowed to rely on the current rustc
171+
// behaviour that options of bools will be one byte with
172+
// no padding, so long as they're nested less than 254 deep.
173+
let raw: u8 = unsafe { core::mem::transmute(*self) };
174+
raw == 0
175+
}
176+
}
177+
)+};
178+
}
179+
impl_for_optional_bool! {
180+
Option<bool>,
181+
Option<Option<bool>>,
182+
Option<Option<Option<bool>>>,
183+
// Could go further, but not worth the metadata overhead
184+
}

0 commit comments

Comments
 (0)