pub struct Bounded<const MIN: u64, const MAX: u64>(/* private fields */);Expand description
A value known at compile time to lie in [MIN, MAX].
The constructor is the only way in, so Bounded<MIN, MAX> is a
refinement-typed integer: the invariant cannot be broken by construction.
Both constructors, new and clamp, refuse an
empty range: when MIN > MAX no u64 satisfies MIN <= v <= MAX, so
neither can produce a value. clamp used to return MIN in that case, which
is outside [LOW, HIGH] and so broke the very invariant the type exists to
carry.
Implementations§
Source§impl<const MIN: u64, const MAX: u64> Bounded<MIN, MAX>
impl<const MIN: u64, const MAX: u64> Bounded<MIN, MAX>
Sourcepub const fn new(v: u64) -> Option<Self>
pub const fn new(v: u64) -> Option<Self>
Construct, or None when the value is outside the range.
Sourcepub const fn clamp(v: u64) -> Option<Self>
pub const fn clamp(v: u64) -> Option<Self>
Clamp an arbitrary value into the range, or None when the range is empty.
MIN > MAX is an empty range: no u64 satisfies MIN <= v <= MAX, so
there is no value to return. Returning MIN (the old behaviour) produced
a Bounded whose get() is outside its own [LOW, HIGH], which breaks
the invariant the type exists to carry – Bounded<100, 10>::clamp(50)
gave 100, and 100 <= 10 is false. new already returns
None for the same range, so the two constructors agree: an empty range
admits nothing.
Sourcepub const fn sub(self, other: Self) -> Option<Self>
pub const fn sub(self, other: Self) -> Option<Self>
Subtract, or None if the difference leaves the range.
Accepts exactly when other <= self and the difference is still
>= MIN. Both halves matter: at MIN == 10, self == 11 and
other == 10 are in range and other <= self, yet the difference 1 is
below MIN, so this returns None. The underflow gate is the other
half – without it a wrapping difference can land back in range and be
accepted. crate::prove::bounded_sub_is_total is the obligation that
proves this is exactly the condition.