use core::fmt;
use core::num::NonZeroU32;

/// Tracks the generation of an entry in an arena. Encapsulates NonZeroU32 to
/// reduce the number of redundant checks needed, as well as enforcing checked
/// arithmetic on advancing a generation.
///
/// Uses NonZeroU32 to help `Index` stay the same size when put inside an
/// `Option`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
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 = Generation(NonZeroU32::MAX);

    #[must_use]
    pub(crate) const fn first() -> Self {
        Self(NonZeroU32::MIN)
    }

    #[must_use]
    pub(crate) fn next(self) -> Self {
        Self(self.0.checked_add(1).unwrap_or(NonZeroU32::MIN))
    }

    pub(crate) const fn to_non_zero_u32(self) -> NonZeroU32 {
        self.0
    }

    pub(crate) const fn from_non_zero_u32(generation: NonZeroU32) -> Self {
        Self(generation)
    }

    pub(crate) const fn from_u32(generation: u32) -> Option<Self> {
        // match like this since `map` is not constant
        match NonZeroU32::new(generation) {
            Some(v) => Some(Self(v)),
            None => None,
        }
    }
}

impl fmt::Debug for Generation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Generation({})", self.to_non_zero_u32())
    }
}

#[cfg(test)]
mod test {
    use super::Generation;

    use core::num::NonZeroU32;

    #[test]
    fn first_and_next() {
        let first = Generation::first();
        assert_eq!(first.0.get(), 1);

        let second = first.next();
        assert_eq!(second.0.get(), 2);
    }

    #[test]
    fn wrap_on_overflow() {
        let max = Generation(NonZeroU32::new(core::u32::MAX).unwrap());
        assert_eq!(max.0.get(), core::u32::MAX);

        let next = max.next();
        assert_eq!(next.0.get(), 1);
    }
}
