Expand description
arithmetic-nonmax provides integer types that are guaranteed to never be their maximum value (MAX).
§Main Features
- Memory Efficiency:
Option<NonMax<T>>is the same size asT. - Intuitive Arithmetic: Supports standard operators (
+,-,*,/,%) and their assign variants. - Type Safety: Prevents the use of the sentinel value (
MAX) at both compile-time and runtime. - Zero Cost: Most operations are as fast as primitive integers.
§How it works
This crate leverages Rust’s “niche optimization” using core::num::NonZero.
Internally, it transforms the value by XORing it with MAX, effectively mapping MAX to 0.
This allows Option<NonMax<T>> to use the bit pattern of MAX to represent None.
| Primitive | size_of::<T>() | size_of::<Option<T>>() | size_of::<Option<NonMax<T>>>() |
|---|---|---|---|
u32 | 4 | 8 | 4 |
i32 | 4 | 8 | 4 |
u8 | 1 | 2 | 1 |
§Panic Behavior
Arithmetic operations (+, -, etc.) will panic if:
- An overflow or underflow occurs.
- The result of the operation is the maximum value of the underlying type.
Use checked_* methods if you want to handle these cases without panicking.
§Examples
use arithmetic_nonmax::*;
// Memory optimization
assert_eq!(core::mem::size_of::<Option<NonMaxU32>>(), 4);
// Arithmetic operations
let a = non_max!(100u8);
let b = a + 50;
assert_eq!(b.get(), 150);
// Use with Option
let opt: Option<NonMaxU32> = NonMaxU32::new(core::u32::MAX);
assert!(opt.is_none());Macros§
- non_max
- Creates a
NonMaxvalue at compile-time.
Structs§
- MaxValue
Error - Error type returned when a value is the maximum for its type.
- NonMax
- A wrapper type for an integer that cannot be its maximum value.
Enums§
- Parse
NonMax Error - Error type returned when parsing a
NonMaxvalue from a string fails.
Type Aliases§
- NonMax
I8 - A signed 8-bit integer that cannot be
i8::MAX. - NonMax
I16 - A signed 16-bit integer that cannot be
i16::MAX. - NonMax
I32 - A signed 32-bit integer that cannot be
i32::MAX. - NonMax
I64 - A signed 64-bit integer that cannot be
i64::MAX. - NonMax
I128 - A signed 128-bit integer that cannot be
i128::MAX. - NonMax
Isize - A signed pointer-sized integer that cannot be
isize::MAX. - NonMax
U8 - An unsigned 8-bit integer that cannot be
u8::MAX. - NonMax
U16 - An unsigned 16-bit integer that cannot be
u16::MAX. - NonMax
U32 - An unsigned 32-bit integer that cannot be
u32::MAX. - NonMax
U64 - An unsigned 64-bit integer that cannot be
u64::MAX. - NonMax
U128 - An unsigned 128-bit integer that cannot be
u128::MAX. - NonMax
Usize - An unsigned pointer-sized integer that cannot be
usize::MAX.