From 022e8d198d7bce054deee4c02ef10615d81ba1b5 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Tue, 20 Feb 2024 02:14:56 +0000 Subject: [PATCH] Add `MIN, MAX` associated constants to Lexicon integer types --- atrium-api/src/types/integer.rs | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/atrium-api/src/types/integer.rs b/atrium-api/src/types/integer.rs index 627384db..78fd85cc 100644 --- a/atrium-api/src/types/integer.rs +++ b/atrium-api/src/types/integer.rs @@ -13,6 +13,12 @@ macro_rules! uint { pub struct $lim($primitive); impl $lim { + /// The smallest value that can be represented by this limited integer type. + pub const MIN: Self = Self(<$primitive>::MIN); + + /// The largest value that can be represented by this limited integer type. + pub const MAX: Self = Self(MAX); + fn new(value: $primitive) -> Result { if value > MAX { Err(format!("value is greater than {}", MAX)) @@ -53,6 +59,14 @@ macro_rules! uint { pub struct $lim_nz($nz); impl $lim_nz { + /// The smallest value that can be represented by this limited non-zero + /// integer type. + pub const MIN: Self = Self($nz::MIN); + + /// The largest value that can be represented by this limited non-zero integer + /// type. + pub const MAX: Self = Self(unsafe { $nz::new_unchecked(MAX) }); + fn new(value: $primitive) -> Result { if value > MAX { Err(format!("value is greater than {}", MAX)) @@ -103,6 +117,12 @@ macro_rules! uint { pub struct $bounded($nz); impl $bounded { + /// The smallest value that can be represented by this bounded integer type. + pub const MIN: Self = Self(unsafe { $nz::new_unchecked(MIN) }); + + /// The largest value that can be represented by this bounded integer type. + pub const MAX: Self = Self(unsafe { $nz::new_unchecked(MAX) }); + fn new(value: $primitive) -> Result { if value < MIN { Err(format!("value is less than {}", MIN)) @@ -156,3 +176,18 @@ uint!(u8, NonZeroU8, LimitedU8, LimitedNonZeroU8, BoundedU8); uint!(u16, NonZeroU16, LimitedU16, LimitedNonZeroU16, BoundedU16); uint!(u32, NonZeroU32, LimitedU32, LimitedNonZeroU32, BoundedU32); uint!(u64, NonZeroU64, LimitedU64, LimitedNonZeroU64, BoundedU64); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn u8_min_max() { + assert_eq!(Ok(LimitedU8::<10>::MIN), 0.try_into()); + assert_eq!(Ok(LimitedU8::<10>::MAX), 10.try_into()); + assert_eq!(Ok(LimitedNonZeroU8::<10>::MIN), 1.try_into()); + assert_eq!(Ok(LimitedNonZeroU8::<10>::MAX), 10.try_into()); + assert_eq!(Ok(BoundedU8::<7, 10>::MIN), 7.try_into()); + assert_eq!(Ok(BoundedU8::<7, 10>::MAX), 10.try_into()); + } +}