Skip to main content

Crate arithmetic_nonmax

Crate arithmetic_nonmax 

Source
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 as T.
  • 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.

Primitivesize_of::<T>()size_of::<Option<T>>()size_of::<Option<NonMax<T>>>()
u32484
i32484
u8121

§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 NonMax value at compile-time.

Structs§

MaxValueError
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.

Type Aliases§

NonMaxI8
A signed 8-bit integer that cannot be i8::MAX.
NonMaxI16
A signed 16-bit integer that cannot be i16::MAX.
NonMaxI32
A signed 32-bit integer that cannot be i32::MAX.
NonMaxI64
A signed 64-bit integer that cannot be i64::MAX.
NonMaxI128
A signed 128-bit integer that cannot be i128::MAX.
NonMaxIsize
A signed pointer-sized integer that cannot be isize::MAX.
NonMaxU8
An unsigned 8-bit integer that cannot be u8::MAX.
NonMaxU16
An unsigned 16-bit integer that cannot be u16::MAX.
NonMaxU32
An unsigned 32-bit integer that cannot be u32::MAX.
NonMaxU64
An unsigned 64-bit integer that cannot be u64::MAX.
NonMaxU128
An unsigned 128-bit integer that cannot be u128::MAX.
NonMaxUsize
An unsigned pointer-sized integer that cannot be usize::MAX.