o3 0.62.0

shared-nothing primitives
Documentation
use std::num::{self, NonZero};

use crate::base::num::bounded;

/// A `u32` proven to lie in the inclusive `MIN..=MAX` bounds.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct U32<const MIN: u32, const MAX: u32>(pub(super) u32);

impl<const MIN: u32, const MAX: u32> U32<MIN, MAX> {
    /// # Safety
    /// `value` satisfies the inclusive `MIN..=MAX` bounds.
    pub const unsafe fn from_proven(value: u32) -> Self {
        Self(value)
    }

    const NONEMPTY: () = assert!(MIN <= MAX, "bounded U32 clamp requires MIN <= MAX");

    pub const fn new(value: u32) -> Option<Self> {
        Self::from_usize(value as usize)
    }

    /// Constructs the bound from a compile-time value within its range.
    pub const fn exact<const VALUE: u32>() -> Self {
        const { assert!(MIN <= VALUE && VALUE <= MAX, "bounds") };
        Self(VALUE)
    }

    pub const fn from_usize(value: usize) -> Option<Self> {
        if value >= MIN as usize && value <= MAX as usize {
            Some(Self(value as u32))
        } else {
            None
        }
    }

    /// Clamps to the inclusive bounds.
    pub const fn clamp(value: usize) -> Self {
        let () = Self::NONEMPTY;
        if value < MIN as usize {
            Self(MIN)
        } else if value > MAX as usize {
            Self(MAX)
        } else {
            Self(value as u32)
        }
    }

    pub const fn get(self) -> u32 {
        self.0
    }

    /// Retains the range of the difference between two admitted values.
    pub const fn abs_diff(self, other: Self) -> U32<0, MAX> {
        U32(self.0.abs_diff(other.0))
    }

    pub const fn into_usize(self) -> usize {
        self.get() as usize
    }

    /// Widens the retained range without checking its value again.
    pub const fn widen<const LOW: u32, const HIGH: u32>(self) -> U32<LOW, HIGH> {
        const { assert!(LOW <= MIN && MAX <= HIGH, "widen") };
        U32(self.0)
    }
}

impl<const MAX: u32> U32<0, MAX> {
    /// Selects a count no greater than the retained limit.
    pub const fn prefix(value: usize, limit: Self) -> Self {
        if value > limit.0 as usize {
            limit
        } else {
            Self(value as u32)
        }
    }

    pub const fn try_usize(value: usize) -> Result<Self, bounded::Overflow<MAX>> {
        match NonZero::<usize>::new(value.saturating_sub(MAX as usize)) {
            Some(excess) => Err(bounded::Overflow::new(excess)),
            None => Ok(Self(value as u32)),
        }
    }
}

/// A `u32` proven to lie in the inclusive `MIN..=MAX` range of a nonzero value.
///
/// The field is nonzero, so `Option` keeps the niche that a plain bounded value
/// loses: `Option<NonZeroU32<MIN, MAX>>` stays one word wide.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NonZeroU32<const MIN: u32, const MAX: u32>(pub(super) NonZero<u32>);

impl<const MIN: u32, const MAX: u32> NonZeroU32<MIN, MAX> {
    /// # Safety
    /// `MIN..=MAX` is a nonempty nonzero range containing `value`.
    pub const unsafe fn from_proven(value: NonZero<u32>) -> Self {
        let () = Self::RANGE;
        Self(value)
    }

    const RANGE: () = assert!(
        1 <= MIN && MIN <= MAX,
        "nonzero bound requires 1 <= MIN <= MAX"
    );

    pub const fn new(value: u32) -> Option<Self> {
        let () = Self::RANGE;
        match NonZero::new(value) {
            Some(value) if value.get() >= MIN && value.get() <= MAX => Some(Self(value)),
            _ => None,
        }
    }

    /// Constructs the bound from a compile-time value within its range.
    pub const fn exact<const VALUE: u32>() -> Self {
        const { assert!(1 <= MIN && MIN <= VALUE && VALUE <= MAX, "nonzero bounds") };
        Self(NonZero::<u32>::MIN.saturating_add(VALUE - 1))
    }

    pub const fn from_usize(value: usize) -> Option<Self> {
        if value <= u32::MAX as usize {
            Self::new(value as u32)
        } else {
            None
        }
    }

    pub const fn get(self) -> u32 {
        self.0.get()
    }

    pub const fn nonzero(self) -> NonZero<u32> {
        self.0
    }

    /// Widens this bound to the same range without a plain bounded value.
    pub const fn into_u32(self) -> U32<MIN, MAX> {
        U32(self.get())
    }

    /// Converts a one-based position without rechecking its retained range.
    pub const fn into_index<const END: u32>(self) -> U32<0, END> {
        const { assert!(MAX != 0 && MAX - 1 <= END, "bounds") };
        U32(self.get() - 1)
    }

    pub const fn into_usize(self) -> usize {
        self.get() as usize
    }
}

impl U32<0, { u32::MAX - 1 }> {
    /// Converts a nonzero one-based position to its zero-based index.
    pub const fn from_one(position: NonZero<u32>) -> Self {
        Self(position.get() - 1)
    }
}

/// Retains an already-proven nonzero count within its exact upper bound.
///
/// # Safety
/// `value` satisfies `1..=MAX`.
pub(crate) const unsafe fn nonzero_usize<const MAX: usize>(
    value: usize,
) -> super::NonZeroUsize<1, MAX> {
    let () = super::NonZeroUsize::<1, MAX>::RANGE;
    // SAFETY: the caller proves value is nonzero and no greater than MAX.
    super::NonZeroUsize(unsafe { num::NonZero::new_unchecked(value) })
}