ObzLib binary data
obz::endian
Explicit helpers for encoding and decoding integer fields in binary buffers.
The Clean-Code Idea
Binary formats should not depend on the host machine. This library makes byte order an explicit part of the call site, and it writes bytes one at a time so the layout is visible in the code.
template <typename T>
void write_be(std::span<std::byte> buffer, std::size_t offset, T value) {
require_supported_integer<T>();
require_range(buffer.size(), offset, sizeof(T));
using unsigned_type = std::make_unsigned_t<T>;
const auto current = static_cast<unsigned_type>(value);
for (std::size_t i = 0; i < sizeof(T); ++i) {
const auto shift = 8 * (sizeof(T) - 1 - i);
buffer[offset + i] = static_cast<std::byte>(
(current >> shift) & unsigned_type{0xff});
}
}
Why This Shape?
The API uses std::span<std::byte> because the data is raw storage, not text and not
an integer array. Bounds are checked with exceptions, so bad offsets are rejected in release builds too.
inline void require_range(std::size_t buffer_size, std::size_t offset, std::size_t width) {
if (offset > buffer_size || buffer_size - offset < width) {
throw std::out_of_range("endian operation exceeds buffer bounds");
}
}