From 6c01c0e9b5b069ee2a61b6078058c69880a14f19 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Sun, 29 Sep 2019 11:14:59 +0200 Subject: [PATCH] Zero-initialize `vec![None; n]` for `Option<&T>`, `Option<&mut T>` and `Option>` --- src/liballoc/vec.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/liballoc/vec.rs b/src/liballoc/vec.rs index e5672f8542ff6..d5089c5e2eba9 100644 --- a/src/liballoc/vec.rs +++ b/src/liballoc/vec.rs @@ -1748,6 +1748,31 @@ unsafe impl IsZero for *mut T { } } +// `Option<&T>`, `Option<&mut T>` and `Option>` are guaranteed to represent `None` as null. +// For fat pointers, the bytes that would be the pointer metadata in the `Some` variant +// are padding in the `None` variant, so ignoring them and zero-initializing instead is ok. + +unsafe impl IsZero for Option<&T> { + #[inline] + fn is_zero(&self) -> bool { + self.is_none() + } +} + +unsafe impl IsZero for Option<&mut T> { + #[inline] + fn is_zero(&self) -> bool { + self.is_none() + } +} + +unsafe impl IsZero for Option> { + #[inline] + fn is_zero(&self) -> bool { + self.is_none() + } +} + //////////////////////////////////////////////////////////////////////////////// // Common trait implementations for Vec