Files
bitserial/bitserial_all.hpp

1156 lines
42 KiB
C++

// This file is generated by combining header files.
// Do not edit it directly; edit headers under include/bitserial instead.
#pragma once
// =============================================================================
// include/bitserial/detail/config.hpp
// =============================================================================
#if defined(_MSC_VER) && _MSC_VER < 1929
#error "bitserial requires MSVC 19.29 or newer for C++20 support."
#endif
#if defined(_MSVC_LANG)
#if _MSVC_LANG < 202002L
#error "bitserial requires C++20 or newer. Enable /std:c++20."
#endif
#elif __cplusplus < 202002L
#error "bitserial requires C++20 or newer. Enable -std=c++20."
#endif
#if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || \
defined(_M_X64)
#define BITSERIAL_DETAIL_X86 1
#endif
#if defined(BITSERIAL_DETAIL_X86)
#define BITSERIAL_DETAIL_HAS_X86_INTRINSICS 1
#endif
#if defined(BITSERIAL_DETAIL_X86) && (defined(__clang__) || defined(__GNUC__))
#define BITSERIAL_DETAIL_HAS_GNU_TARGET_INTRINSICS 1
#define BITSERIAL_DETAIL_TARGET_AVX2 [[gnu::target("avx2")]]
#define BITSERIAL_DETAIL_TARGET_AVX512BW \
[[gnu::target("avx512f,avx512bw,avx2")]]
#else
#define BITSERIAL_DETAIL_TARGET_AVX2
#define BITSERIAL_DETAIL_TARGET_AVX512BW
#endif
#if defined(__AVX2__) || defined(__AVX512BW__)
#define BITSERIAL_DETAIL_HAS_AVX2 1
#endif
#if defined(__AVX512F__) && defined(__AVX512BW__)
#define BITSERIAL_DETAIL_HAS_AVX512BW 1
#endif
#if defined(BITSERIAL_DETAIL_HAS_AVX2) || \
defined(BITSERIAL_DETAIL_HAS_GNU_TARGET_INTRINSICS)
#define BITSERIAL_DETAIL_CAN_BUILD_AVX2 1
#endif
#if defined(BITSERIAL_DETAIL_HAS_AVX512BW) || \
defined(BITSERIAL_DETAIL_HAS_GNU_TARGET_INTRINSICS)
#define BITSERIAL_DETAIL_CAN_BUILD_AVX512BW 1
#endif
// =============================================================================
// include/bitserial/bit_io.hpp
// =============================================================================
#include <cstddef>
#include <cstdint>
#include <span>
namespace bitserial {
constexpr void write_bits(
std::span<std::uint8_t> out,
std::size_t pos,
std::size_t w,
std::uint64_t v
) noexcept {
std::size_t remaining = w;
while (remaining > 0) {
const std::size_t byte_idx = pos >> 3;
const std::size_t bit_off = pos & 7u;
const std::size_t free_bits = 8u - bit_off;
const std::size_t take = (remaining < free_bits) ? remaining : free_bits;
const std::size_t src_shift = remaining - take;
const std::size_t dst_shift = free_bits - take;
const std::uint8_t chunk =
static_cast<std::uint8_t>((v >> src_shift) & ((1u << take) - 1u));
const std::uint8_t mask =
static_cast<std::uint8_t>(((1u << take) - 1u) << dst_shift);
out[byte_idx] = static_cast<std::uint8_t>(
(out[byte_idx] & ~mask) | (chunk << dst_shift)
);
pos += take;
remaining -= take;
}
}
constexpr std::uint64_t read_bits(
std::span<const std::uint8_t> in, std::size_t pos, std::size_t w
) noexcept {
std::uint64_t v = 0;
std::size_t remaining = w;
while (remaining > 0) {
const std::size_t byte_idx = pos >> 3;
const std::size_t bit_off = pos & 7u;
const std::size_t free_bits = 8u - bit_off;
const std::size_t take = (remaining < free_bits) ? remaining : free_bits;
const std::size_t dst_shift = free_bits - take;
const std::uint8_t mask = static_cast<std::uint8_t>((1u << take) - 1u);
const std::uint64_t chunk = (in[byte_idx] >> dst_shift) & mask;
v = (v << take) | chunk;
pos += take;
remaining -= take;
}
return v;
}
} // namespace bitserial
// =============================================================================
// include/bitserial/bulk.hpp
// =============================================================================
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <span>
#include <type_traits>
#if defined(BITSERIAL_DETAIL_HAS_X86_INTRINSICS)
#include <immintrin.h>
#endif
namespace bitserial {
namespace detail {
template <std::size_t Bits>
constexpr void pack_bits_scalar(
std::span<const std::uint8_t> in,
std::span<std::uint8_t>
out,
std::size_t bit_pos
) noexcept {
static_assert(Bits >= 1 && Bits <= 8);
for (std::size_t i = 0; i < in.size(); ++i) {
write_bits(out, bit_pos, Bits, in[i] & ((1u << Bits) - 1u));
bit_pos += Bits;
}
}
template <std::size_t Bits>
constexpr void unpack_bits_scalar(
std::span<const std::uint8_t> in,
std::span<std::uint8_t>
out,
std::size_t bit_pos
) noexcept {
static_assert(Bits >= 1 && Bits <= 8);
for (std::size_t i = 0; i < out.size(); ++i) {
out[i] = static_cast<std::uint8_t>(read_bits(in, bit_pos, Bits));
bit_pos += Bits;
}
}
template <std::size_t Bits>
constexpr void pack_bits_byte_aligned_scalar(
std::span<const std::uint8_t> in, std::span<std::uint8_t> out
) noexcept {
static_assert(Bits >= 1 && Bits <= 8);
std::size_t i = 0;
std::size_t o = 0;
if constexpr (Bits == 3) {
for (; i + 8 <= in.size(); i += 8, o += 3) {
const std::uint8_t a0 = in[i + 0] & 0x07;
const std::uint8_t a1 = in[i + 1] & 0x07;
const std::uint8_t a2 = in[i + 2] & 0x07;
const std::uint8_t a3 = in[i + 3] & 0x07;
const std::uint8_t a4 = in[i + 4] & 0x07;
const std::uint8_t a5 = in[i + 5] & 0x07;
const std::uint8_t a6 = in[i + 6] & 0x07;
const std::uint8_t a7 = in[i + 7] & 0x07;
out[o + 0] =
static_cast<std::uint8_t>((a0 << 5) | (a1 << 2) | (a2 >> 1));
out[o + 1] = static_cast<std::uint8_t>(
(a2 << 7) | (a3 << 4) | (a4 << 1) | (a5 >> 2)
);
out[o + 2] = static_cast<std::uint8_t>((a5 << 6) | (a6 << 3) | a7);
}
} else if constexpr (Bits == 4) {
for (; i + 2 <= in.size(); i += 2, ++o) {
out[o] = static_cast<std::uint8_t>(
((in[i] & 0x0F) << 4) | (in[i + 1] & 0x0F)
);
}
} else if constexpr (Bits == 5) {
for (; i + 8 <= in.size(); i += 8, o += 5) {
const std::uint8_t a0 = in[i + 0] & 0x1F;
const std::uint8_t a1 = in[i + 1] & 0x1F;
const std::uint8_t a2 = in[i + 2] & 0x1F;
const std::uint8_t a3 = in[i + 3] & 0x1F;
const std::uint8_t a4 = in[i + 4] & 0x1F;
const std::uint8_t a5 = in[i + 5] & 0x1F;
const std::uint8_t a6 = in[i + 6] & 0x1F;
const std::uint8_t a7 = in[i + 7] & 0x1F;
out[o + 0] = static_cast<std::uint8_t>((a0 << 3) | (a1 >> 2));
out[o + 1] =
static_cast<std::uint8_t>((a1 << 6) | (a2 << 1) | (a3 >> 4));
out[o + 2] = static_cast<std::uint8_t>((a3 << 4) | (a4 >> 1));
out[o + 3] =
static_cast<std::uint8_t>((a4 << 7) | (a5 << 2) | (a6 >> 3));
out[o + 4] = static_cast<std::uint8_t>((a6 << 5) | a7);
}
}
pack_bits_scalar<Bits>(in.subspan(i), out, i * Bits);
}
#if defined(BITSERIAL_DETAIL_CAN_BUILD_AVX2)
alignas(32) inline constexpr std::array<std::uint8_t, 32> k_baq3_shuffle = {
1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 2, 1, 2, 1, 2, 1,
1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 2, 1, 2, 1, 2, 1,
};
alignas(32) inline constexpr std::array<std::uint16_t, 16> k_baq3_mask = {
0xE000, 0x1C00, 0x0380, 0x0070, 0x000E, 0x01C0, 0x0038, 0x0007,
0xE000, 0x1C00, 0x0380, 0x0070, 0x000E, 0x01C0, 0x0038, 0x0007,
};
alignas(32) inline constexpr std::array<std::uint16_t, 16> k_baq3_mul = {
1, 8, 64, 512, 4096, 128, 1024, 8192,
1, 8, 64, 512, 4096, 128, 1024, 8192,
};
alignas(32) inline constexpr std::array<std::uint8_t, 32> k_baq5_shuffle = {
1, 0, 1, 0, 2, 1, 2, 1, 3, 2, 4, 3, 4, 3, 4, 3,
1, 0, 1, 0, 2, 1, 2, 1, 3, 2, 4, 3, 4, 3, 4, 3,
};
alignas(32) inline constexpr std::array<std::uint16_t, 16> k_baq5_mask = {
0xF800, 0x07C0, 0x3E00, 0x01F0, 0x0F80, 0x7C00, 0x03E0, 0x001F,
0xF800, 0x07C0, 0x3E00, 0x01F0, 0x0F80, 0x7C00, 0x03E0, 0x001F,
};
alignas(32) inline constexpr std::array<std::uint16_t, 16> k_baq5_mul = {
1, 32, 4, 128, 16, 2, 64, 2048, 1, 32, 4, 128, 16, 2, 64, 2048,
};
template <std::size_t Bits>
BITSERIAL_DETAIL_TARGET_AVX2 inline std::size_t
unpack_bits_avx2_aligned_prefix(
std::span<const std::uint8_t> in, std::span<std::uint8_t> out
) noexcept {
static_assert(Bits == 3 || Bits == 4 || Bits == 5);
if constexpr (Bits == 4) {
const __m256i mask_nibble = _mm256_set1_epi8(0x0F);
std::size_t i = 0;
for (; i + 64 <= out.size(); i += 64) {
const __m256i src = _mm256_loadu_si256(
reinterpret_cast<const __m256i *>(in.data() + (i >> 1))
);
const __m256i lo = _mm256_and_si256(src, mask_nibble);
const __m256i hi =
_mm256_and_si256(_mm256_srli_epi16(src, 4), mask_nibble);
const __m256i a = _mm256_unpacklo_epi8(hi, lo);
const __m256i b = _mm256_unpackhi_epi8(hi, lo);
_mm256_storeu_si256(
reinterpret_cast<__m256i *>(out.data() + i),
_mm256_permute2x128_si256(a, b, 0x20)
);
_mm256_storeu_si256(
reinterpret_cast<__m256i *>(out.data() + i + 32),
_mm256_permute2x128_si256(a, b, 0x31)
);
}
return i;
} else {
constexpr std::size_t packed_per_group = Bits;
constexpr int shift = Bits == 3 ? 13 : 11;
const auto &shuffle_table = Bits == 3 ? k_baq3_shuffle : k_baq5_shuffle;
const auto &mask_table = Bits == 3 ? k_baq3_mask : k_baq5_mask;
const auto &mul_table = Bits == 3 ? k_baq3_mul : k_baq5_mul;
const __m256i shuffle = _mm256_load_si256(
reinterpret_cast<const __m256i *>(shuffle_table.data())
);
const __m256i mask = _mm256_load_si256(
reinterpret_cast<const __m256i *>(mask_table.data())
);
const __m256i mul = _mm256_load_si256(
reinterpret_cast<const __m256i *>(mul_table.data())
);
const std::size_t full_groups = out.size() / 8;
const std::size_t safe_groups =
in.size() >= 16
? std::min(
full_groups, ((in.size() - 16) / packed_per_group) + 1
)
: 0;
std::size_t group = 0;
for (; group + 2 <= safe_groups; group += 2) {
const std::size_t in_idx = group * packed_per_group;
const std::size_t out_idx = group * 8;
__m256i x = _mm256_castsi128_si256(_mm_loadu_si128(
reinterpret_cast<const __m128i *>(in.data() + in_idx)
));
x = _mm256_inserti128_si256(
x,
_mm_loadu_si128(
reinterpret_cast<const __m128i *>(
in.data() + in_idx + packed_per_group
)
),
1
);
x = _mm256_shuffle_epi8(x, shuffle);
x = _mm256_and_si256(x, mask);
x = _mm256_mullo_epi16(x, mul);
x = _mm256_srli_epi16(x, shift);
x = _mm256_packus_epi16(x, x);
_mm_storel_epi64(
reinterpret_cast<__m128i *>(out.data() + out_idx),
_mm256_castsi256_si128(x)
);
_mm_storel_epi64(
reinterpret_cast<__m128i *>(out.data() + out_idx + 8),
_mm256_extracti128_si256(x, 1)
);
}
if (group < safe_groups) {
const std::size_t in_idx = group * packed_per_group;
const std::size_t out_idx = group * 8;
__m128i x = _mm_loadu_si128(
reinterpret_cast<const __m128i *>(in.data() + in_idx)
);
x = _mm_shuffle_epi8(x, _mm256_castsi256_si128(shuffle));
x = _mm_and_si128(x, _mm256_castsi256_si128(mask));
x = _mm_mullo_epi16(x, _mm256_castsi256_si128(mul));
x = _mm_srli_epi16(x, shift);
x = _mm_packus_epi16(x, x);
_mm_storel_epi64(
reinterpret_cast<__m128i *>(out.data() + out_idx), x
);
++group;
}
return group * 8;
}
}
#endif
#if defined(BITSERIAL_DETAIL_CAN_BUILD_AVX512BW)
template <std::size_t Bits>
BITSERIAL_DETAIL_TARGET_AVX512BW inline std::size_t
unpack_bits_avx512bw_aligned_prefix(
std::span<const std::uint8_t> in, std::span<std::uint8_t> out
) noexcept {
static_assert(Bits == 3 || Bits == 4 || Bits == 5);
if constexpr (Bits == 4) {
const __m512i mask_nibble = _mm512_set1_epi8(0x0F);
std::size_t i = 0;
for (; i + 128 <= out.size(); i += 128) {
const __m512i src = _mm512_loadu_si512(
reinterpret_cast<const void *>(in.data() + (i >> 1))
);
const __m512i lo = _mm512_and_si512(src, mask_nibble);
const __m512i hi =
_mm512_and_si512(_mm512_srli_epi16(src, 4), mask_nibble);
const __m512i a = _mm512_unpacklo_epi8(hi, lo);
const __m512i b = _mm512_unpackhi_epi8(hi, lo);
_mm_storeu_si128(
reinterpret_cast<__m128i *>(out.data() + i),
_mm512_extracti32x4_epi32(a, 0)
);
_mm_storeu_si128(
reinterpret_cast<__m128i *>(out.data() + i + 16),
_mm512_extracti32x4_epi32(b, 0)
);
_mm_storeu_si128(
reinterpret_cast<__m128i *>(out.data() + i + 32),
_mm512_extracti32x4_epi32(a, 1)
);
_mm_storeu_si128(
reinterpret_cast<__m128i *>(out.data() + i + 48),
_mm512_extracti32x4_epi32(b, 1)
);
_mm_storeu_si128(
reinterpret_cast<__m128i *>(out.data() + i + 64),
_mm512_extracti32x4_epi32(a, 2)
);
_mm_storeu_si128(
reinterpret_cast<__m128i *>(out.data() + i + 80),
_mm512_extracti32x4_epi32(b, 2)
);
_mm_storeu_si128(
reinterpret_cast<__m128i *>(out.data() + i + 96),
_mm512_extracti32x4_epi32(a, 3)
);
_mm_storeu_si128(
reinterpret_cast<__m128i *>(out.data() + i + 112),
_mm512_extracti32x4_epi32(b, 3)
);
}
return i;
} else {
constexpr std::size_t packed_per_group = Bits;
constexpr int shift = Bits == 3 ? 13 : 11;
const auto &shuffle_table = Bits == 3 ? k_baq3_shuffle : k_baq5_shuffle;
const auto &mask_table = Bits == 3 ? k_baq3_mask : k_baq5_mask;
const auto &mul_table = Bits == 3 ? k_baq3_mul : k_baq5_mul;
const __m512i shuffle = _mm512_broadcast_i32x4(_mm_load_si128(
reinterpret_cast<const __m128i *>(shuffle_table.data())
));
const __m512i mask = _mm512_broadcast_i32x4(
_mm_load_si128(reinterpret_cast<const __m128i *>(mask_table.data()))
);
const __m512i mul = _mm512_broadcast_i32x4(
_mm_load_si128(reinterpret_cast<const __m128i *>(mul_table.data()))
);
const std::size_t full_groups = out.size() / 8;
const std::size_t safe_groups =
in.size() >= 16
? std::min(
full_groups, ((in.size() - 16) / packed_per_group) + 1
)
: 0;
std::size_t group = 0;
for (; group + 4 <= safe_groups; group += 4) {
const std::size_t in_idx = group * packed_per_group;
const std::size_t out_idx = group * 8;
__m512i x = _mm512_castsi128_si512(_mm_loadu_si128(
reinterpret_cast<const __m128i *>(in.data() + in_idx)
));
x = _mm512_inserti32x4(
x,
_mm_loadu_si128(
reinterpret_cast<const __m128i *>(
in.data() + in_idx + packed_per_group
)
),
1
);
x = _mm512_inserti32x4(
x,
_mm_loadu_si128(
reinterpret_cast<const __m128i *>(
in.data() + in_idx + packed_per_group * 2
)
),
2
);
x = _mm512_inserti32x4(
x,
_mm_loadu_si128(
reinterpret_cast<const __m128i *>(
in.data() + in_idx + packed_per_group * 3
)
),
3
);
x = _mm512_shuffle_epi8(x, shuffle);
x = _mm512_and_si512(x, mask);
x = _mm512_mullo_epi16(x, mul);
x = _mm512_srli_epi16(x, shift);
x = _mm512_packus_epi16(x, x);
_mm_storel_epi64(
reinterpret_cast<__m128i *>(out.data() + out_idx),
_mm512_extracti32x4_epi32(x, 0)
);
_mm_storel_epi64(
reinterpret_cast<__m128i *>(out.data() + out_idx + 8),
_mm512_extracti32x4_epi32(x, 1)
);
_mm_storel_epi64(
reinterpret_cast<__m128i *>(out.data() + out_idx + 16),
_mm512_extracti32x4_epi32(x, 2)
);
_mm_storel_epi64(
reinterpret_cast<__m128i *>(out.data() + out_idx + 24),
_mm512_extracti32x4_epi32(x, 3)
);
}
return group * 8;
}
}
#endif
#if defined(BITSERIAL_DETAIL_CAN_BUILD_AVX2) || \
defined(BITSERIAL_DETAIL_CAN_BUILD_AVX512BW)
inline bool cpu_supports_avx2() noexcept {
#if defined(BITSERIAL_DETAIL_HAS_GNU_TARGET_INTRINSICS)
__builtin_cpu_init();
return __builtin_cpu_supports("avx2");
#elif defined(BITSERIAL_DETAIL_HAS_AVX2)
return true;
#else
return false;
#endif
}
inline bool cpu_supports_avx512bw() noexcept {
#if defined(BITSERIAL_DETAIL_HAS_GNU_TARGET_INTRINSICS)
__builtin_cpu_init();
return __builtin_cpu_supports("avx512f") &&
__builtin_cpu_supports("avx512bw") &&
__builtin_cpu_supports("avx2");
#elif defined(BITSERIAL_DETAIL_HAS_AVX512BW)
return true;
#else
return false;
#endif
}
#endif
} // namespace detail
template <std::size_t Bits>
constexpr void pack_bits(
std::span<const std::uint8_t> in,
std::span<std::uint8_t>
out,
std::size_t bit_pos = 0
) noexcept {
static_assert(Bits >= 1 && Bits <= 8, "bitserial: bit width out of range");
if (std::is_constant_evaluated() || (bit_pos & 7u) != 0) {
detail::pack_bits_scalar<Bits>(in, out, bit_pos);
return;
}
if constexpr (Bits == 8) {
std::copy(
in.begin(), in.end(),
out.begin() + static_cast<std::ptrdiff_t>(bit_pos >> 3)
);
} else if constexpr (Bits == 3 || Bits == 4 || Bits == 5) {
detail::pack_bits_byte_aligned_scalar<Bits>(
in, out.subspan(bit_pos >> 3)
);
} else {
detail::pack_bits_scalar<Bits>(in, out, bit_pos);
}
}
template <std::size_t Bits>
constexpr void unpack_bits(
std::span<const std::uint8_t> in,
std::span<std::uint8_t>
out,
std::size_t bit_pos = 0
) noexcept {
static_assert(Bits >= 1 && Bits <= 8, "bitserial: bit width out of range");
if (std::is_constant_evaluated() || (bit_pos & 7u) != 0) {
detail::unpack_bits_scalar<Bits>(in, out, bit_pos);
return;
}
if constexpr (Bits == 8) {
std::copy_n(
in.begin() + static_cast<std::ptrdiff_t>(bit_pos >> 3), out.size(),
out.begin()
);
return;
}
#if defined(BITSERIAL_DETAIL_CAN_BUILD_AVX512BW)
if constexpr (Bits == 3 || Bits == 4 || Bits == 5) {
if (detail::cpu_supports_avx512bw()) {
const std::size_t done =
detail::unpack_bits_avx512bw_aligned_prefix<Bits>(
in.subspan(bit_pos >> 3), out
);
detail::unpack_bits_scalar<Bits>(
in, out.subspan(done), bit_pos + done * Bits
);
return;
}
}
#endif
#if defined(BITSERIAL_DETAIL_CAN_BUILD_AVX2)
if constexpr (Bits == 3 || Bits == 4 || Bits == 5) {
if (detail::cpu_supports_avx2()) {
const std::size_t done = detail::unpack_bits_avx2_aligned_prefix<Bits>(
in.subspan(bit_pos >> 3), out
);
detail::unpack_bits_scalar<Bits>(
in, out.subspan(done), bit_pos + done * Bits
);
return;
}
}
#endif
detail::unpack_bits_scalar<Bits>(in, out, bit_pos);
}
} // namespace bitserial
// =============================================================================
// include/bitserial/bitserial.hpp
// =============================================================================
// =============================================================================
// bitserial.hpp — Big-endian, padding-free, zero-alloc bit-field serialization (C++20)
// Author: DawnMagnet Time: April 27, 2026 Email: axccjqh@qq.com
// -----------------------------------------------------------------------------
// Features:
// * Single declaration generates both struct and serialization schema (X-Macro style)
// * Full compile-time expansion, no runtime reflection overhead
// * Big-endian MSB-first bitstream, no padding between fields
// * Automatic support for bool, signed/unsigned integers, float32, float64
// - Bit fields are sign-extended on read (for signed integers)
// * Support for nested structures and fixed-length arrays
// * Provides three IO forms: bytes / span / hex
// * Writes to user std::span, no internal allocation
//
// Compilation requirement: C++20 (GCC 10+ / Clang 11+ / MSVC 19.29+ with /Zc:preprocessor)
// =============================================================================
#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <span>
#include <stdexcept>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
// IEEE 754 is validated once at compile time: floating-point serialization depends on standard layout
static_assert(sizeof(float) == 4, "bitserial requires 32-bit float");
static_assert(sizeof(double) == 8, "bitserial requires 64-bit double");
namespace bitserial {
// =============================================================================
// Field descriptors (auto-generated by registration macros, users typically don't construct directly)
// =============================================================================
/// Scalar field: pack member via *MemPtr using Bits bits
template <auto MemPtr, std::size_t Bits> struct Field {
static constexpr auto ptr = MemPtr;
static constexpr std::size_t bits = Bits;
static constexpr bool is_nested = false;
static constexpr bool is_array = false;
};
/// Nested struct field: recursively invoke its schema
template <auto MemPtr> struct Nested {
static constexpr auto ptr = MemPtr;
static constexpr bool is_nested = true;
static constexpr bool is_array = false;
};
/// Fixed-length array field: each element uses ElemBits bits
template <auto MemPtr, std::size_t ElemBits> struct ArrayField {
static constexpr auto ptr = MemPtr;
static constexpr std::size_t elem_bits = ElemBits;
static constexpr bool is_nested = false;
static constexpr bool is_array = true;
};
namespace detail {
/// Tail sentinel for field tuple, absorbs trailing comma from macro expansion
struct tuple_end {
static constexpr bool is_nested = false;
static constexpr bool is_array = false;
static constexpr std::size_t bits = 0;
};
// Extract member type from member pointer M C::*
template <typename> struct member_traits;
template <typename C, typename M> struct member_traits<M C::*> {
using class_type = C;
using member_type = M;
};
// Handle const-qualified member pointer (const on right of *)
template <typename C, typename M> struct member_traits<M C::*const> {
using class_type = C;
using member_type = M;
};
template <auto P>
using member_type_t = typename member_traits<decltype(P)>::member_type;
// =============================================================================
// Bidirectional scalar <-> uint64 conversion: complete handling of bool / integer / floating-point
// -----------------------------------------------------------------------------
// Rules:
// * bool → 0/1, 1 bit suffices
// * Unsigned integer → direct conversion
// * Signed integer → sign-extend according to bit field width (on read)
// * float → bit_cast<uint32_t>, pack as fixed 32-bit
// * double → bit_cast<uint64_t>, pack as fixed 64-bit
//
// Validity of bit field width (bits):
// * bool: 1
// * integer: 1..sizeof(T)*8
// * float32: must be == 32
// * float64: must be == 64
// =============================================================================
template <typename T>
inline constexpr bool is_supported_scalar_v =
std::is_same_v<T, bool> || std::is_integral_v<T> ||
std::is_same_v<T, float> || std::is_same_v<T, double>;
/// "Natural bit width" of scalar field: default value when user omits bit width
template <typename T> consteval std::size_t natural_bits() noexcept {
if constexpr (std::is_same_v<T, bool>) return 1;
else if constexpr (std::is_integral_v<T>)
return sizeof(T) * 8;
else if constexpr (std::is_same_v<T, float>)
return 32;
else if constexpr (std::is_same_v<T, double>)
return 64;
else {
static_assert(
is_supported_scalar_v<T>, "bitserial: unsupported scalar type"
);
return 0;
}
}
/// Encode scalar as uint64 for bitstream
template <typename T>
constexpr std::uint64_t encode_scalar(T v, std::size_t bits) noexcept {
static_assert(
is_supported_scalar_v<T>, "bitserial: unsupported scalar type"
);
if constexpr (std::is_same_v<T, bool>) {
return v ? 1u : 0u;
} else if constexpr (std::is_same_v<T, float>) {
(void)bits;
return std::bit_cast<std::uint32_t>(v);
} else if constexpr (std::is_same_v<T, double>) {
(void)bits;
return std::bit_cast<std::uint64_t>(v);
} else if constexpr (std::is_signed_v<T>) {
// Signed: truncate to low bits (two's complement natural representation)
using U = std::make_unsigned_t<T>;
const auto u = static_cast<U>(v);
const std::uint64_t mask =
(bits == 64) ? ~std::uint64_t{0} : ((std::uint64_t{1} << bits) - 1);
return static_cast<std::uint64_t>(u) & mask;
} else {
return static_cast<std::uint64_t>(v);
}
}
/// Decode uint64 from bitstream back to scalar
template <typename T>
constexpr T decode_scalar(std::uint64_t raw, std::size_t bits) noexcept {
static_assert(
is_supported_scalar_v<T>, "bitserial: unsupported scalar type"
);
if constexpr (std::is_same_v<T, bool>) {
return raw != 0;
} else if constexpr (std::is_same_v<T, float>) {
return std::bit_cast<float>(static_cast<std::uint32_t>(raw));
} else if constexpr (std::is_same_v<T, double>) {
return std::bit_cast<double>(raw);
} else if constexpr (std::is_signed_v<T>) {
// Sign-extend: if MSB (bits-1) is 1, fill high bits with 1
if (bits < 64) {
const std::uint64_t sign_bit = std::uint64_t{1} << (bits - 1);
if (raw & sign_bit) {
const std::uint64_t ext = ~((std::uint64_t{1} << bits) - 1);
raw |= ext;
}
}
return static_cast<T>(
static_cast<std::make_signed_t<std::uint64_t>>(raw)
);
} else {
return static_cast<T>(raw);
}
}
/// Validate bit width validity (compile-time)
template <typename T, std::size_t Bits>
consteval void validate_bits() noexcept {
static_assert(
is_supported_scalar_v<T>, "bitserial: unsupported scalar type"
);
if constexpr (std::is_same_v<T, bool>) {
static_assert(
Bits >= 1 && Bits <= 8, "bitserial: bool field must use 1..8 bits"
);
} else if constexpr (std::is_same_v<T, float>) {
static_assert(Bits == 32, "bitserial: float must be exactly 32 bits");
} else if constexpr (std::is_same_v<T, double>) {
static_assert(Bits == 64, "bitserial: double must be exactly 64 bits");
} else { // integral
static_assert(
Bits >= 1 && Bits <= sizeof(T) * 8,
"bitserial: integer bit width out of range"
);
}
}
} // namespace detail
// =============================================================================
// Main schema template: user registration macros explicitly specialize this
// =============================================================================
template <typename T> struct schema_of;
template <typename T, typename = void> struct has_schema : std::false_type {};
template <typename T>
struct has_schema<T, std::void_t<decltype(schema_of<T>::fields)>> :
std::true_type {};
template <typename T>
inline constexpr bool has_schema_v = has_schema<T>::value;
// =============================================================================
// Compile-time bit width calculation
// =============================================================================
template <typename T> consteval std::size_t bit_size() noexcept;
template <typename F> consteval std::size_t field_bits() noexcept {
if constexpr (std::is_same_v<F, detail::tuple_end>) {
return 0;
} else if constexpr (F::is_nested) {
return bit_size<detail::member_type_t<F::ptr>>();
} else if constexpr (F::is_array) {
using Arr = detail::member_type_t<F::ptr>;
return std::extent_v<Arr> * F::elem_bits;
} else {
return F::bits;
}
}
template <typename T> consteval std::size_t bit_size() noexcept {
static_assert(
has_schema_v<T>,
"bitserial: type has no schema; use BITSERIAL_DEFINE / "
"BITSERIAL_BEGIN/END to register it."
);
std::size_t n = 0;
std::apply(
[&](auto... fs) {
((n += field_bits<decltype(fs)>()), ...);
},
schema_of<T>::fields
);
return n;
}
template <typename T> inline constexpr std::size_t bit_size_v = bit_size<T>();
template <typename T>
inline constexpr std::size_t byte_size_v = (bit_size_v<T> + 7) / 8;
// =============================================================================
// Field read/write
// =============================================================================
template <typename T>
constexpr void to_bytes_impl(
const T &obj, std::span<std::uint8_t> out, std::size_t &pos
);
template <typename T>
constexpr void from_bytes_impl(
T &obj, std::span<const std::uint8_t> in, std::size_t &pos
);
template <typename F, typename T>
constexpr void
write_field(const T &obj, std::span<std::uint8_t> out, std::size_t &pos) {
if constexpr (std::is_same_v<F, detail::tuple_end>) {
return;
} else if constexpr (F::is_nested) {
to_bytes_impl(obj.*F::ptr, out, pos);
} else if constexpr (F::is_array) {
using Arr = detail::member_type_t<F::ptr>;
using Elem = std::remove_extent_t<Arr>;
detail::validate_bits<Elem, F::elem_bits>();
const auto &arr = obj.*F::ptr;
constexpr std::size_t N = std::extent_v<Arr>;
if constexpr (std::is_same_v<Elem, std::uint8_t>) {
pack_bits<F::elem_bits>(
std::span<const std::uint8_t, N>(arr), out, pos
);
pos += N * F::elem_bits;
} else {
for (std::size_t i = 0; i < N; ++i) {
write_bits(
out, pos, F::elem_bits,
detail::encode_scalar<Elem>(arr[i], F::elem_bits)
);
pos += F::elem_bits;
}
}
} else {
using M = detail::member_type_t<F::ptr>;
detail::validate_bits<M, F::bits>();
write_bits(
out, pos, F::bits, detail::encode_scalar<M>(obj.*F::ptr, F::bits)
);
pos += F::bits;
}
}
template <typename F, typename T>
constexpr void
read_field(T &obj, std::span<const std::uint8_t> in, std::size_t &pos) {
if constexpr (std::is_same_v<F, detail::tuple_end>) {
return;
} else if constexpr (F::is_nested) {
from_bytes_impl(obj.*F::ptr, in, pos);
} else if constexpr (F::is_array) {
using Arr = detail::member_type_t<F::ptr>;
using Elem = std::remove_extent_t<Arr>;
detail::validate_bits<Elem, F::elem_bits>();
auto &arr = obj.*F::ptr;
constexpr std::size_t N = std::extent_v<Arr>;
if constexpr (std::is_same_v<Elem, std::uint8_t>) {
unpack_bits<F::elem_bits>(in, std::span<std::uint8_t, N>(arr), pos);
pos += N * F::elem_bits;
} else {
for (std::size_t i = 0; i < N; ++i) {
arr[i] = detail::decode_scalar<Elem>(
read_bits(in, pos, F::elem_bits), F::elem_bits
);
pos += F::elem_bits;
}
}
} else {
using M = detail::member_type_t<F::ptr>;
detail::validate_bits<M, F::bits>();
obj.*F::ptr =
detail::decode_scalar<M>(read_bits(in, pos, F::bits), F::bits);
pos += F::bits;
}
}
template <typename T>
constexpr void to_bytes_impl(
const T &obj, std::span<std::uint8_t> out, std::size_t &pos
) {
static_assert(has_schema_v<T>, "bitserial: missing schema");
std::apply(
[&](auto... fs) {
(write_field<decltype(fs)>(obj, out, pos), ...);
},
schema_of<T>::fields
);
}
template <typename T>
constexpr void from_bytes_impl(
T &obj, std::span<const std::uint8_t> in, std::size_t &pos
) {
static_assert(has_schema_v<T>, "bitserial: missing schema");
std::apply(
[&](auto... fs) {
(read_field<decltype(fs)>(obj, in, pos), ...);
},
schema_of<T>::fields
);
}
// =============================================================================
// Public API
// =============================================================================
/// Write to user buffer (zero-alloc), out needs at least byte_size_v<T> bytes
template <typename T>
constexpr void to_bytes(const T &obj, std::span<std::uint8_t> out) {
if (out.size() < byte_size_v<T>)
throw std::out_of_range("bitserial::to_bytes: buffer too small");
std::size_t pos = 0;
to_bytes_impl(obj, out, pos);
}
/// Serialize to fixed-size std::array
template <typename T>
[[nodiscard]] constexpr std::array<std::uint8_t, byte_size_v<T>>
to_bytes(const T &obj) {
std::array<std::uint8_t, byte_size_v<T>> buf{};
std::size_t pos = 0;
to_bytes_impl(obj, std::span<std::uint8_t>(buf), pos);
return buf;
}
/// Deserialize
template <typename T>
[[nodiscard]] constexpr T from_bytes(std::span<const std::uint8_t> in) {
if (in.size() < byte_size_v<T>)
throw std::out_of_range("bitserial::from_bytes: buffer too small");
T obj{};
std::size_t pos = 0;
from_bytes_impl(obj, in, pos);
return obj;
}
// ---- HEX ----
[[nodiscard]] inline std::string
bytes_to_hex(std::span<const std::uint8_t> b, bool upper = true) {
static constexpr char kLower[] = "0123456789abcdef";
static constexpr char kUpper[] = "0123456789ABCDEF";
const char *tbl = upper ? kUpper : kLower;
std::string s(b.size() * 2, '\0');
for (std::size_t i = 0; i < b.size(); ++i) {
s[2 * i] = tbl[b[i] >> 4];
s[2 * i + 1] = tbl[b[i] & 0x0F];
}
return s;
}
namespace detail {
constexpr std::uint8_t hex_nibble(char c) {
if (c >= '0' && c <= '9') return static_cast<std::uint8_t>(c - '0');
if (c >= 'a' && c <= 'f') return static_cast<std::uint8_t>(c - 'a' + 10);
if (c >= 'A' && c <= 'F') return static_cast<std::uint8_t>(c - 'A' + 10);
throw std::invalid_argument("bitserial: invalid hex character");
}
} // namespace detail
inline void hex_to_bytes(std::string_view h, std::span<std::uint8_t> out) {
if (h.size() != out.size() * 2)
throw std::invalid_argument("bitserial: hex length mismatch");
for (std::size_t i = 0; i < out.size(); ++i) {
out[i] = static_cast<std::uint8_t>(
(detail::hex_nibble(h[2 * i]) << 4) | detail::hex_nibble(h[2 * i + 1])
);
}
}
template <typename T>
[[nodiscard]] std::string to_hex(const T &obj, bool upper = true) {
auto buf = to_bytes(obj);
return bytes_to_hex(std::span<const std::uint8_t>(buf), upper);
}
template <typename T> [[nodiscard]] T from_hex(std::string_view h) {
std::array<std::uint8_t, byte_size_v<T>> buf{};
hex_to_bytes(h, std::span<std::uint8_t>(buf));
return from_bytes<T>(std::span<const std::uint8_t>(buf));
}
} // namespace bitserial
// =============================================================================
// Registration macro section
// -----------------------------------------------------------------------------
// Can use in field table:
// BSF##_F (TYPE, NAME) -> bit width = natural bit width (int/float/...)
// BSF##_F (TYPE, NAME, BITS) -> bit width = BITS (only int/bool customizable)
// BSF##_NEST(TYPE, NAME)
// BSF##_ARR (TYPE, NAME, LEN) -> element bit width = natural bit width
// BSF##_ARR (TYPE, NAME, LEN, EBITS)
// =============================================================================
// ---- Basic utilities ---------------------------------------------------------------
#define BSF_DETAIL_NTH_3(_1, _2, _3, N, ...) N
#define BSF_DETAIL_NTH_4(_1, _2, _3, _4, N, ...) N
// ---- First pass: generate struct members -----------------------------------------------
#define BSF_DETAIL_MEMBER_F_2(TYPE, NAME) TYPE NAME;
#define BSF_DETAIL_MEMBER_F_3(TYPE, NAME, BITS) TYPE NAME;
#define BSF_DETAIL_MEMBER_ARR_3(TYPE, NAME, LEN) TYPE NAME[LEN];
#define BSF_DETAIL_MEMBER_ARR_4(TYPE, NAME, LEN, EBITS) TYPE NAME[LEN];
#define BSF_DETAIL_MEMBER_NEST(TYPE, NAME) TYPE NAME;
#define BSF_DETAIL_MEMBER_F(...) \
BSF_DETAIL_NTH_3(__VA_ARGS__, BSF_DETAIL_MEMBER_F_3, BSF_DETAIL_MEMBER_F_2, _ERR)( \
__VA_ARGS__ \
)
#define BSF_DETAIL_MEMBER_ARR(...) \
BSF_DETAIL_NTH_4(__VA_ARGS__, BSF_DETAIL_MEMBER_ARR_4, BSF_DETAIL_MEMBER_ARR_3, _ERR, _ERR)( \
__VA_ARGS__ \
)
// ---- Second pass: generate schema tuple elements -------------------------------------------
#define BSF_DETAIL_SCHEMA_F_2(TYPE, NAME) \
::bitserial::Field< \
&BitserialSelf::NAME, ::bitserial::detail::natural_bits<TYPE>()>{},
#define BSF_DETAIL_SCHEMA_F_3(TYPE, NAME, BITS) \
::bitserial::Field<&BitserialSelf::NAME, (BITS)>{},
#define BSF_DETAIL_SCHEMA_ARR_3(TYPE, NAME, LEN) \
::bitserial::ArrayField< \
&BitserialSelf::NAME, ::bitserial::detail::natural_bits<TYPE>()>{},
#define BSF_DETAIL_SCHEMA_ARR_4(TYPE, NAME, LEN, EBITS) \
::bitserial::ArrayField<&BitserialSelf::NAME, (EBITS)>{},
#define BSF_DETAIL_SCHEMA_NEST(TYPE, NAME) \
::bitserial::Nested<&BitserialSelf::NAME>{},
#define BSF_DETAIL_SCHEMA_F(...) \
BSF_DETAIL_NTH_3(__VA_ARGS__, BSF_DETAIL_SCHEMA_F_3, BSF_DETAIL_SCHEMA_F_2, _ERR)( \
__VA_ARGS__ \
)
#define BSF_DETAIL_SCHEMA_ARR(...) \
BSF_DETAIL_NTH_4(__VA_ARGS__, BSF_DETAIL_SCHEMA_ARR_4, BSF_DETAIL_SCHEMA_ARR_3, _ERR, _ERR)( \
__VA_ARGS__ \
)
// ---- User API ---------------------------------------------------------------
#define BITSERIAL_EMIT_MEMBERS(FIELDS_MACRO) FIELDS_MACRO(BSF_DETAIL_MEMBER)
#define BITSERIAL_EMIT_SCHEMA(FIELDS_MACRO) FIELDS_MACRO(BSF_DETAIL_SCHEMA)
/**
* @brief Single-line declaration: simultaneously generate struct and schema_of specialization.
*
* Usage:
*
* #define MY_FIELDS(BSF) \
* BSF##_F (std::uint8_t, ver, 4) \
* BSF##_F (std::int16_t, temp) \
* BSF##_F (float, vbat) \
* BSF##_F (bool, ok) \
* BSF##_NEST(Inner, body) \
* BSF##_ARR (std::uint8_t, mac, 6)
*
* BITSERIAL_DEFINE(MyPkt, MY_FIELDS);
*/
#define BITSERIAL_DEFINE(TYPE, FIELDS_MACRO) \
struct TYPE { \
BITSERIAL_EMIT_MEMBERS(FIELDS_MACRO) \
}; \
template <> struct bitserial::schema_of<TYPE> { \
using BitserialSelf = TYPE; \
static constexpr auto fields = std::make_tuple( \
BITSERIAL_EMIT_SCHEMA(FIELDS_MACRO)::bitserial::detail::tuple_end{} \
); \
}
/// Split version: BEGIN starts struct (can add members/methods in between), END closes and generates schema
#define BITSERIAL_BEGIN(TYPE, FIELDS_MACRO) \
struct TYPE { \
BITSERIAL_EMIT_MEMBERS(FIELDS_MACRO)
#define BITSERIAL_END(TYPE, FIELDS_MACRO) \
} \
; \
template <> struct bitserial::schema_of<TYPE> { \
using BitserialSelf = TYPE; \
static constexpr auto fields = std::make_tuple( \
BITSERIAL_EMIT_SCHEMA(FIELDS_MACRO)::bitserial::detail::tuple_end{} \
); \
}