From 064608b370c257661d87a5a862999f9d2de6c1ee Mon Sep 17 00:00:00 2001 From: Lucien Greathouse Date: Sat, 24 Jun 2023 21:25:47 -0400 Subject: [PATCH] Add Index::DANGLING for two-phase initialization --- src/arena.rs | 9 +++++++++ src/generation.rs | 5 +++++ 2 files changed, 14 insertions(+) diff --git a/src/arena.rs b/src/arena.rs index c0ca1da..9f5eee0 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -28,6 +28,15 @@ pub struct Index { } impl Index { + /// Represents an `Index` that is unlikely to be in use. This is useful for + /// programs that want to do two-phase initialization in safe Rust. Avoid + /// using this value to represent the absence of an `Index`: prefer + /// `Option`. + pub const DANGLING: Self = Self { + slot: u32::MAX, + generation: Generation::DANGLING, + }; + /// Convert this `Index` to an equivalent `u64` representation. Mostly /// useful for passing to code outside of Rust. #[allow(clippy::integer_arithmetic)] diff --git a/src/generation.rs b/src/generation.rs index f458b37..c9b1537 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -12,6 +12,11 @@ use core::num::NonZeroU32; pub(crate) struct Generation(NonZeroU32); impl Generation { + /// Represents a generation that is unlikely to be used. This is useful for + /// programs that want to do two-phase initialization in safe Rust. + // This is safe because the maximum value of a u32 is not zero. + pub(crate) const DANGLING: Self = unsafe { Generation(NonZeroU32::new_unchecked(u32::MAX)) }; + #[must_use] pub(crate) fn first() -> Self { // This is safe because 1 is not zero.