macro_rules! nonmax {
( $nonmax: ident, $non_zero: ident, $primitive: ident ) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct $nonmax(std::num::$non_zero);
impl $nonmax {
#[inline]
pub fn new(value: $primitive) -> Option<Self> {
if value == $primitive::max_value() {
None
} else {
let inner = unsafe {
std::num::$non_zero::new_unchecked(value ^ $primitive::max_value())
};
Some(Self(inner))
}
}
#[inline]
pub unsafe fn new_unchecked(value: $primitive) -> Self {
let inner = std::num::$non_zero::new_unchecked(value ^ $primitive::max_value());
Self(inner)
}
#[inline]
pub fn get(&self) -> $primitive {
self.0.get() ^ $primitive::max_value()
}
}
#[cfg(test)]
mod $primitive {
use super::*;
use std::mem::size_of;
#[test]
fn construct() {
let zero = $nonmax::new(0).unwrap();
assert_eq!(zero.get(), 0);
let some = $nonmax::new(19).unwrap();
assert_eq!(some.get(), 19);
let max = $nonmax::new($primitive::max_value());
assert_eq!(max, None);
}
#[test]
fn sizes_correct() {
assert_eq!(size_of::<$primitive>(), size_of::<$nonmax>());
assert_eq!(size_of::<$nonmax>(), size_of::<Option<$nonmax>>());
}
}
};
}
nonmax!(NonMaxI8, NonZeroI8, i8);
nonmax!(NonMaxI16, NonZeroI16, i16);
nonmax!(NonMaxI32, NonZeroI32, i32);
nonmax!(NonMaxI64, NonZeroI64, i64);
nonmax!(NonMaxIsize, NonZeroIsize, isize);
nonmax!(NonMaxU8, NonZeroU8, u8);
nonmax!(NonMaxU16, NonZeroU16, u16);
nonmax!(NonMaxU32, NonZeroU32, u32);
nonmax!(NonMaxU64, NonZeroU64, u64);
nonmax!(NonMaxUsize, NonZeroUsize, usize);