Unsigned Integer Types
Overview
The library provides safe unsigned integer types that detect overflow, underflow, and other undefined behavior at runtime. These types are drop-in replacements for the standard unsigned integer types with added safety guarantees.
Available Types
The following types are provided in the boost::safe_numbers namespace:
namespace boost::safe_numbers {
using u8 = detail::unsigned_integer_basis<std::uint8_t>;
using u16 = detail::unsigned_integer_basis<std::uint16_t>;
using u32 = detail::unsigned_integer_basis<std::uint32_t>;
using u64 = detail::unsigned_integer_basis<std::uint64_t>;
using u128 = detail::unsigned_integer_basis<int128::uint128_t>;
} // namespace boost::safe_numbers
Each type exposes a basis_type member type alias that refers to the underlying integer type, allowing conversion back to built-in types when needed.
Comparison Operators
Full three-way comparison is supported via operator<⇒, which returns std::strong_ordering. All comparison operators (<, ⇐, >, >=, ==, !=) are available.
Arithmetic Operators
All arithmetic operators perform runtime checks and throw exceptions when undefined behavior would occur.
Addition (operator+, operator+=)
Throws std::overflow_error if the result would exceed the maximum representable value.
Subtraction (operator-, operator-=)
Throws std::underflow_error if the result would be negative (wrap around).
Mixed-Width Operations are Prohibited
Operations between different width safe integer types are compile-time errors. To perform operations between different widths, explicitly convert to the same type first.
Exception Summary
| Operation | Exception Type | Condition |
|---|---|---|
|
|
Result exceeds maximum value |
|
|
Result would be negative |
|
|
Result exceeds maximum value |
|
|
Division by zero |
|
|
Modulo by zero |
|
|
Value is at maximum |
|
|
Value is zero |