Files
Library/include/Void/Core/CheckedBits.hpp
T

88 lines
2.8 KiB
C++

#pragma once
#include <bit>
#include <concepts>
#include <expected>
#include <limits>
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<T>::digits`.
template <std::unsigned_integral T>
[[nodiscard]] constexpr std::expected<T, BitError>
checked_extract(T value, unsigned offset, unsigned count) noexcept
{
constexpr unsigned width = std::numeric_limits<T>::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<T>(value >> offset);
const T mask = static_cast<T>((T{1} << count) - T{1});
return static_cast<T>(shifted & mask);
}
/// Safely deposit the low `count` bits of `val` into `dest` starting at `offset`.
template <std::unsigned_integral T>
[[nodiscard]] constexpr std::expected<T, BitError>
checked_deposit(T dest, T val, unsigned offset, unsigned count) noexcept
{
constexpr unsigned width = std::numeric_limits<T>::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>((T{1} << count) - T{1});
const T shifted_mask = static_cast<T>(field_mask << offset);
return static_cast<T>((dest & ~shifted_mask) |
static_cast<T>((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 <std::unsigned_integral T>
[[nodiscard]] constexpr std::expected<T, BitError>
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<T>(alignment - T{1});
if (value > std::numeric_limits<T>::max() - mask) {
return std::unexpected{BitError::overflow};
}
return static_cast<T>((value + mask) & ~mask);
}
/// Safely round `value` down to a power-of-two `alignment`.
template <std::unsigned_integral T>
[[nodiscard]] constexpr std::expected<T, BitError>
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<T>(value & ~static_cast<T>(alignment - T{1}));
}
} // namespace Void::Bits