#pragma once #include #include #include #include namespace Void::Bits { enum class BitError { invalid_range, invalid_alignment, overflow }; /// Safely extract `count` bits starting at `offset` from `value`. /// Returns `BitError::invalid_range` when `offset + count` overflows or /// exceeds `std::numeric_limits::digits`. template [[nodiscard]] constexpr std::expected checked_extract(T value, unsigned offset, unsigned count) noexcept { constexpr unsigned width = std::numeric_limits::digits; if (offset > width || count > width - offset) { return std::unexpected{BitError::invalid_range}; } if (count == 0) { return T{0}; } if (count == width) { return value; } const T shifted = static_cast(value >> offset); const T mask = static_cast((T{1} << count) - T{1}); return static_cast(shifted & mask); } /// Safely deposit the low `count` bits of `val` into `dest` starting at `offset`. template [[nodiscard]] constexpr std::expected checked_deposit(T dest, T val, unsigned offset, unsigned count) noexcept { constexpr unsigned width = std::numeric_limits::digits; if (offset > width || count > width - offset) { return std::unexpected{BitError::invalid_range}; } if (count == 0) { return dest; } if (count == width) { return val; } const T field_mask = static_cast((T{1} << count) - T{1}); const T shifted_mask = static_cast(field_mask << offset); return static_cast((dest & ~shifted_mask) | static_cast((val & field_mask) << offset)); } /// Safely round `value` up to a power-of-two `alignment`, rejecting zero/non-pow2 /// alignment and integer overflow before arithmetic. template [[nodiscard]] constexpr std::expected checked_align_up(T value, T alignment) noexcept { if (alignment == T{0} || !std::has_single_bit(alignment)) { return std::unexpected{BitError::invalid_alignment}; } const T mask = static_cast(alignment - T{1}); if (value > std::numeric_limits::max() - mask) { return std::unexpected{BitError::overflow}; } return static_cast((value + mask) & ~mask); } /// Safely round `value` down to a power-of-two `alignment`. template [[nodiscard]] constexpr std::expected checked_align_down(T value, T alignment) noexcept { if (alignment == T{0} || !std::has_single_bit(alignment)) { return std::unexpected{BitError::invalid_alignment}; } return static_cast(value & ~static_cast(alignment - T{1})); } } // namespace Void::Bits