use thiserror::Error;
#[derive(Clone, Copy, Debug, Error)]
#[error("Integer must less than 2^31")]
pub struct U31Error;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct U31(u32);
impl U31 {
pub fn new(u32_: u32) -> Result<Self, U31Error> {
if u32_ < 0x80000000 {
Ok(Self(u32_))
} else {
Err(U31Error)
}
}
#[inline(always)]
pub fn into_u32(self) -> u32 {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_u31() {
assert!(U31::new(0).is_ok());
assert!(U31::new(u32::MAX).is_err());
assert!(U31::new(0x80_00_00_00).is_err());
assert!(U31::new(0x7F_FF_FF_FF).is_ok());
}
}