diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..2f3cf31 --- /dev/null +++ b/.clang-format @@ -0,0 +1,279 @@ +--- +# 语言: None, Cpp, Java, JavaScript, ObjC, Proto, TableGen, TextProto +Language: Cpp +BasedOnStyle: LLVM +# 访问说明符(public、private等)的偏移 +AccessModifierOffset: -2 +# 开括号(开圆括号、开尖括号、开方括号)后的对齐: Align, DontAlign, AlwaysBreak(总是在开括号后换行) +AlignAfterOpenBracket: BlockIndent +# 对齐数组列 +AlignArrayOfStructures: None +# 连续赋值时,对齐所有等号 +AlignConsecutiveAssignments: None +# 对齐连续位字段 +AlignConsecutiveBitFields: None +# 连续声明时,对齐所有声明的变量名 +AlignConsecutiveDeclarations: None +# 对齐连续宏定义 +AlignConsecutiveMacros: AcrossComments +# 逃脱换行(使用反斜杠换行)的反斜杠 +AlignEscapedNewlines: Left +# 操作数对齐方式 +AlignOperands: Align +# 尾随的注释对齐 +AlignTrailingComments: true +# 允许函数参数在一行 +AllowAllArgumentsOnNextLine: true +# 允许函数声明的所有参数在放在一行 +AllowAllParametersOfDeclarationOnNextLine: true +# 允许短的块放在同一行 +AllowShortBlocksOnASingleLine: Always +# 允许短的case标签放在同一行 +AllowShortCaseLabelsOnASingleLine: false +# 允许短的枚举放在同一行 +AllowShortEnumsOnASingleLine: true +# 允许短的函数放在同一行 +AllowShortFunctionsOnASingleLine: All +# 允许短的if语句保持在同一行 +AllowShortIfStatementsOnASingleLine: Always +# 允许短的匿名函数lamda表达式放在同一行 +AllowShortLambdasOnASingleLine: Empty +# 允许短的循环while保持在同一行 +AllowShortLoopsOnASingleLine: false +# 总是在返回类型后换行 +AlwaysBreakAfterReturnType: None +# 总是在多行string字面量前换行 +AlwaysBreakBeforeMultilineStrings: false +# 总是在template声明后换行 +AlwaysBreakTemplateDeclarations: MultiLine +# 宏属性 +AttributeMacros: ['__capability', '__output', '__ununsed'] +# 表示函数实参要么都在同一行,要么都各自一行 +BinPackArguments: true +# false表示所有形参要么都在同一行,要么都各自一行 +BinPackParameters: true +# 位域冒号对齐方式 +BitFieldColonSpacing : Both +# 大括号换行,只有当BreakBeforeBraces设置为Custom时才有效,设置其他配置则下面不生效 +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +# 在java字段的注释后换行 +BreakAfterJavaFieldAnnotations: false +# 在二元运算符前换行 +BreakBeforeBinaryOperators: None +# 在大括号前换行 +BreakBeforeBraces: Custom +# 在concept前换行 +# BreakBeforeConceptDeclarations: Never +# 在三元运算符前换行 +BreakBeforeTernaryOperators: true +# 构造函数初始值设定项换行样式 +BreakConstructorInitializers: BeforeColon +# 继承列表样式 +BreakInheritanceList: AfterColon +# 字符串换行样式 +BreakStringLiterals: false +# 每行字符的限制,0表示没有限制 +ColumnLimit: 80 +# 描述具有特殊意义的注释的正则表达式,它不应该被分割为多行或以其它方式改变 +CommentPragmas: '^ IWYU pragma:' +# 在新行上声明每个命名空间 +CompactNamespaces: false +# 构造函数的初始化列表的缩进宽度 +ConstructorInitializerIndentWidth: 4 +# 延续的行的缩进宽度 +ContinuationIndentWidth: 4 +# 去除C++11的列表初始化的大括号{后和}前的空格 +Cpp11BracedListStyle: true +# 继承最常用的换行方式 +DeriveLineEnding: true +# 继承最常用的指针和引用的对齐方式 +DerivePointerAlignment: false +# 关闭格式化 +DisableFormat: false +# 删除访问修饰符后的所有空行 +EmptyLineAfterAccessModifier: Never +# 仅当访问修饰符开始一个新的逻辑块时才添加空行 +EmptyLineBeforeAccessModifier: Never +# 自动检测函数的调用和定义是否被格式为每行一个参数(Experimental) +ExperimentalAutoDetectBinPacking: true +# 自动补充namespace注释 +FixNamespaceComments: false +# 需要被解读为foreach循环而不是函数调用的宏 +ForEachMacros: ['RANGES_FOR', 'FOREACH', 'REP'] +IfMacros: ['IF'] +# 多个#include块合并在一起并排序为一个 +IncludeBlocks: Merge +# 可以定义负数优先级从而保证某些#include永远在最前面 +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +# 缩进访问修饰符 +IndentAccessModifiers: false +# 缩进case标签 +IndentCaseLabels: false +# case 标签后面的块使用与 case 标签相同的缩进级别 +IndentCaseBlocks: false +# 向后兼容缩进外部块 +IndentExternBlock: AfterExternBlock +# 缩进goto标签。 +IndentGotoLabels: false +# 缩进预处理器指令 +IndentPPDirectives: BeforeHash +# 缩进模板中的requires子句 +IndentRequires: false +# 缩进宽度 +IndentWidth: 2 +# 函数返回类型换行时,缩进函数声明或函数定义的函数名 +IndentWrappedFunctionNames: true +#InsertBraces: true +# 插入尾随逗号 +InsertTrailingCommas: None +# 保留JavaScript字符串引号 +JavaScriptQuotes: Leave +# 包装 JavaScript 导入/导出语句 +JavaScriptWrapImports: true +# 保留在块开始处的空行 +KeepEmptyLinesAtTheStartOfBlocks: false +# 相对于 lambda 签名对齐 lambda 主体 +LambdaBodyIndentation: Signature +# 开始一个块的宏的正则表达式 +MacroBlockBegin: '' +# 结束一个块的宏的正则表达式 +MacroBlockEnd: '' +# 连续空行的最大数量 +MaxEmptyLinesToKeep: 1 +# 命名空间的缩进 +NamespaceIndentation: All +ObjCBinPackProtocolList: Auto +# 使用ObjC块时缩进宽度 +ObjCBlockIndentWidth: 4 +ObjCBreakBeforeNestedBlockParam: true +# 在ObjC的@property后添加一个空格 +ObjCSpaceAfterProperty: false +# 在ObjC的protocol列表前添加一个空格 +ObjCSpaceBeforeProtocolList: true +# 缩进预处理器语句的列数 +PPIndentWidth: -1 +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PenaltyIndentedWhitespace: 0 +# 指针的对齐: Left, Right, Middle +PointerAlignment: Right +# 引用的对齐 +ReferenceAlignment: Pointer +# 允许重新排版注释 +ReflowComments: false +#RemoveBracesLLVM: false +# 短命名空间跨越的最大展开行数 +ShortNamespaceLines: 1 +# 允许排序#include +SortIncludes: CaseSensitive +# java静态导入放在非静态导入之前 +SortJavaStaticImport: Before +# 对using声明排序 +SortUsingDeclarations: true +# 在C风格类型转换后添加空格 +SpaceAfterCStyleCast: false +# 在!后添加空格 +SpaceAfterLogicalNot: false +# 在Template关键字后添加空格 +SpaceAfterTemplateKeyword: true +# 不要确保指针限定符周围有空格 +SpaceAroundPointerQualifiers: Default +# 在赋值运算符之前添加空格 +SpaceBeforeAssignmentOperators: true +# 不在case冒号之前添加空格 +SpaceBeforeCaseColon: false +# 不在C++11大括号列表之前添加空格 +SpaceBeforeCpp11BracedList: false +# 在构造函数初始化器冒号之前添加空格 +SpaceBeforeCtorInitializerColon: true +# 在继承冒号前添加空格 +SpaceBeforeInheritanceColon: true +# 开圆括号之前添加一个空格 +SpaceBeforeParens: ControlStatements +# 在基于范围的for循环冒号之前添加空格 +SpaceBeforeRangeBasedForLoopColon: true +# 中括号前空格 +SpaceBeforeSquareBrackets: false +# {}中间空格 +SpaceInEmptyBlock: false +# 在空的圆括号中添加空格 +SpaceInEmptyParentheses: false +# 在尾随的评论前添加的空格数(只适用于//) +SpacesBeforeTrailingComments: 3 +# 在尖括号的<后和>前添加空格 +SpacesInAngles: Never +# 在C风格类型转换的括号中添加空格 +SpacesInCStyleCastParentheses: false +# 不在if/for/switch/while条件周围插入空格 +SpacesInConditionalStatement: false +# 在容器(ObjC和JavaScript的数组和字典等)字面量中添加空格 +SpacesInContainerLiterals: true +# 行注释开头允许有多少个空格。要禁用最大值,请将其设置为-1,除此之外,最大值优先于最小值 +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +# 在圆括号的(后和)前添加空格 +SpacesInParentheses: false +# 在方括号的[后和]前添加空格,lamda表达式和未指明大小的数组的声明不受影响 +SpacesInSquareBrackets: false +# 标准 +Standard: Auto +# 在语句前面被忽略的宏定义,就好像它们是一个属性一样 +StatementAttributeLikeMacros: + - Q_EMIT +# 应该被解释为完整语句的宏定义 +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +# tab宽度 +TabWidth: 2 +# 使用\r\n换行替代\n +UseCRLF: false +# 使用tab字符:ForIndentation——仅将制表符用于缩进 +UseTab: Never +# 对空格敏感的宏定义 +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME + diff --git a/.gitignore b/.gitignore index 6735fc3..3963534 100644 --- a/.gitignore +++ b/.gitignore @@ -1,46 +1,48 @@ -# Build directories +# Build directories build/ +build-win*/ _build/ cmake-build-*/ out/ - -# CMake generated files -CMakeCache.txt -CMakeFiles/ -cmake_install.cmake -install_manifest.txt + +# CMake generated files +CMakeCache.txt +CMakeFiles/ +cmake_install.cmake +install_manifest.txt *.cmake Makefile - -# Compilation database -compile_commands.json - -# C++ object files & binaries -*.o -*.obj -*.a -*.lib -*.so -*.so.* -*.dylib -*.dll -*.exe -*.out - -# IDE & editor -.vscode/ -.idea/ -*.swp -*.swo -*~ -.DS_Store - -# Cache -.cache/ -.clangd/ -.ccls-cache/ - -# Test artifacts -catch_amalgamated.* - -.vs \ No newline at end of file +!/Makefile + +# Compilation database +compile_commands.json + +# C++ object files & binaries +*.o +*.obj +*.a +*.lib +*.so +*.so.* +*.dylib +*.dll +*.exe +*.out + +# IDE & editor +.vscode/ +.idea/ +*.swp +*.swo +*~ +.DS_Store + +# Cache +.cache/ +.clangd/ +.ccls-cache/ + +# Test artifacts +catch_amalgamated.* + +.vs diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..91cdabb --- /dev/null +++ b/Makefile @@ -0,0 +1,121 @@ +.PHONY: help configure cb build test bench \ + wconfigure-cl wconfigure-gcc wconfigure-clang \ + wcb wcb-cl wcb-gcc wcb-clang wbuild \ + wtest wtest-cl wtest-gcc wtest-clang \ + wbench wbench-cl wbench-gcc wbench-clang \ + fmt fmt-check clean distclean + +CMAKE ?= cmake +CTEST ?= ctest +CLANG_FORMAT ?= clang-format + +BUILD_DIR ?= build +WIN_CL_BUILD_DIR ?= build-win-cl +WIN_GCC_BUILD_DIR ?= build-win-gcc +WIN_CLANG_BUILD_DIR ?= build-win-clang +BUILD_TYPE ?= Release + +CMAKE_FLAGS ?= -DBITSERIAL_BUILD_TESTS=ON -DBITSERIAL_BUILD_BENCHMARKS=ON +WIN_CMAKE_FLAGS ?= $(CMAKE_FLAGS) +WIN_CL_CXX ?= cl +WIN_GCC_CXX ?= g++ +WIN_CLANG_CXX ?= clang++ + +FORMAT_FILES := \ + bitserial.hpp \ + include/bitserial/bit_io.hpp \ + include/bitserial/bitserial.hpp \ + include/bitserial/bulk.hpp \ + include/bitserial/detail/config.hpp \ + tests/bitserial_tests.cpp \ + benchmarks/baq_bulk_benchmarks.cpp + +help: + @printf '%s\n' \ + 'Targets:' \ + ' make cb Configure and build native Release tree' \ + ' make test Build and run tests' \ + ' make bench Build and run Catch2 benchmarks' \ + ' make wcb Alias for wcb-cl' \ + ' make wcb-cl Configure and build Ninja tree with cl' \ + ' make wcb-gcc Configure and build Ninja tree with g++' \ + ' make wcb-clang Configure and build Ninja tree with clang++' \ + ' make wtest Alias for wtest-cl' \ + ' make wbench Alias for wbench-cl' \ + ' make fmt Format C++ sources with clang-format' \ + ' make fmt-check Check formatting without writing files' \ + ' make clean Clean configured build trees' \ + ' make distclean Remove build directories' + +configure: + $(CMAKE) -S . -B $(BUILD_DIR) -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) $(CMAKE_FLAGS) + +cb: configure + $(CMAKE) --build $(BUILD_DIR) --config $(BUILD_TYPE) + +build: cb + +test: cb + $(CTEST) --test-dir $(BUILD_DIR) -C $(BUILD_TYPE) --output-on-failure + +bench: configure + $(CMAKE) --build $(BUILD_DIR) --config $(BUILD_TYPE) --target run_bitserial_benchmarks + +wconfigure-cl: + $(CMAKE) -S . -B $(WIN_CL_BUILD_DIR) -G Ninja -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DCMAKE_CXX_COMPILER=$(WIN_CL_CXX) $(WIN_CMAKE_FLAGS) + +wconfigure-gcc: + $(CMAKE) -S . -B $(WIN_GCC_BUILD_DIR) -G Ninja -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DCMAKE_CXX_COMPILER=$(WIN_GCC_CXX) $(WIN_CMAKE_FLAGS) + +wconfigure-clang: + $(CMAKE) -S . -B $(WIN_CLANG_BUILD_DIR) -G Ninja -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DCMAKE_CXX_COMPILER=$(WIN_CLANG_CXX) $(WIN_CMAKE_FLAGS) + +wcb: wcb-cl + +wcb-cl: wconfigure-cl + $(CMAKE) --build $(WIN_CL_BUILD_DIR) --config $(BUILD_TYPE) + +wcb-gcc: wconfigure-gcc + $(CMAKE) --build $(WIN_GCC_BUILD_DIR) --config $(BUILD_TYPE) + +wcb-clang: wconfigure-clang + $(CMAKE) --build $(WIN_CLANG_BUILD_DIR) --config $(BUILD_TYPE) + +wbuild: wcb + +wtest: wtest-cl + +wtest-cl: wcb-cl + $(CTEST) --test-dir $(WIN_CL_BUILD_DIR) -C $(BUILD_TYPE) --output-on-failure + +wtest-gcc: wcb-gcc + $(CTEST) --test-dir $(WIN_GCC_BUILD_DIR) -C $(BUILD_TYPE) --output-on-failure + +wtest-clang: wcb-clang + $(CTEST) --test-dir $(WIN_CLANG_BUILD_DIR) -C $(BUILD_TYPE) --output-on-failure + +wbench: wbench-cl + +wbench-cl: wconfigure-cl + $(CMAKE) --build $(WIN_CL_BUILD_DIR) --config $(BUILD_TYPE) --target run_bitserial_benchmarks + +wbench-gcc: wconfigure-gcc + $(CMAKE) --build $(WIN_GCC_BUILD_DIR) --config $(BUILD_TYPE) --target run_bitserial_benchmarks + +wbench-clang: wconfigure-clang + $(CMAKE) --build $(WIN_CLANG_BUILD_DIR) --config $(BUILD_TYPE) --target run_bitserial_benchmarks + +fmt: + $(CLANG_FORMAT) -i $(FORMAT_FILES) + +fmt-check: + $(CLANG_FORMAT) --dry-run --Werror $(FORMAT_FILES) + +clean: + -$(CMAKE) --build $(BUILD_DIR) --config $(BUILD_TYPE) --target clean + -$(CMAKE) --build $(WIN_CL_BUILD_DIR) --config $(BUILD_TYPE) --target clean + -$(CMAKE) --build $(WIN_GCC_BUILD_DIR) --config $(BUILD_TYPE) --target clean + -$(CMAKE) --build $(WIN_CLANG_BUILD_DIR) --config $(BUILD_TYPE) --target clean + +distclean: + rm -rf $(BUILD_DIR) $(WIN_CL_BUILD_DIR) $(WIN_GCC_BUILD_DIR) $(WIN_CLANG_BUILD_DIR) diff --git a/README.cn.md b/README.cn.md index 56eb907..ce39713 100644 --- a/README.cn.md +++ b/README.cn.md @@ -1,82 +1,82 @@ -# bitserial - -适用于 C++20 的大端、无填充、零分配位域序列化框架 - -## 特性 - -- **单次声明生成 Schema**:同时定义结构体与序列化模式(X-Macro 风格) +# bitserial + +适用于 C++20 的大端、无填充、零分配位域序列化框架 + +## 特性 + +- **单次声明生成 Schema**:同时定义结构体与序列化模式(X-Macro 风格) - **全编译期展开**:无运行时反射开销 - **大端 MSB-first 位流**:字段间无任何填充,逐位精确打包 - **BAQ 批量路径**:提供 `pack_bits` / `unpack_bits` 固定位宽字节数组接口 - 可用时对 3/4/5-bit 数组读取启用 AVX512BW 和 AVX2 intrinsic 后端 - **丰富类型支持**:`bool`、有符号/无符号整数、`float32`、`float64` - - 读取时自动对有符号整数进行符号位扩展 -- **可组合**:嵌套结构体、定长数组 -- **多种 IO 格式**:字节数组、span、十六进制字符串 -- **零分配**:直接写入用户提供的 `std::span` - -## 编译要求 - -- C++20 编译器 - - GCC 10+、Clang 11+、MSVC 19.29+(需加 `/Zc:preprocessor`) - -## 快速开始 - + - 读取时自动对有符号整数进行符号位扩展 +- **可组合**:嵌套结构体、定长数组 +- **多种 IO 格式**:字节数组、span、十六进制字符串 +- **零分配**:直接写入用户提供的 `std::span` + +## 编译要求 + +- C++20 编译器 + - GCC 10+、Clang 11+、MSVC 19.29+(需加 `/Zc:preprocessor`) + +## 快速开始 + ```cpp #include - -// 1. 定义数据包 Schema -#define MY_PACKET_FIELDS(BSF) \ - BSF##_F (std::uint8_t, 版本, 4) \ - BSF##_F (std::uint8_t, 标志位, 4) \ - BSF##_F (std::int16_t, 温度) \ - BSF##_F (bool, 正常) \ - BSF##_F (float, 电压) \ - BSF##_ARR(std::uint8_t, MAC地址, 6) - -BITSERIAL_DEFINE(我的数据包, MY_PACKET_FIELDS); - -// 2. 序列化 -我的数据包 pkt{ - .版本 = 0xA, - .标志位 = 0x5, - .温度 = -42, - .正常 = true, - .电压 = 3.7f, - .MAC地址 = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}, -}; - -auto bytes = bitserial::to_bytes(pkt); -auto hex = bitserial::to_hex(pkt); // "A5..." - -// 3. 反序列化 -auto pkt2 = bitserial::from_bytes<我的数据包>(bytes); + +// 1. 定义数据包 Schema +#define MY_PACKET_FIELDS(BSF) \ + BSF##_F (std::uint8_t, 版本, 4) \ + BSF##_F (std::uint8_t, 标志位, 4) \ + BSF##_F (std::int16_t, 温度) \ + BSF##_F (bool, 正常) \ + BSF##_F (float, 电压) \ + BSF##_ARR(std::uint8_t, MAC地址, 6) + +BITSERIAL_DEFINE(我的数据包, MY_PACKET_FIELDS); + +// 2. 序列化 +我的数据包 pkt{ + .版本 = 0xA, + .标志位 = 0x5, + .温度 = -42, + .正常 = true, + .电压 = 3.7f, + .MAC地址 = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}, +}; + +auto bytes = bitserial::to_bytes(pkt); +auto hex = bitserial::to_hex(pkt); // "A5..." + +// 3. 反序列化 +auto pkt2 = bitserial::from_bytes<我的数据包>(bytes); auto pkt3 = bitserial::from_hex<我的数据包>(hex); ``` 兼容头 `#include "bitserial.hpp"` 仍然保留,会转发到新的公开头。 - -## 字段类型 - -| 宏 | 说明 | 示例 | -|-----|------|------| -| `BSF_F(T, 名称)` | 使用自然位宽的标量字段 | `BSF_F(std::uint16_t, x)` → 16 位 | -| `BSF_F(T, 名称, 位宽)` | 使用自定义位宽的标量字段 | `BSF_F(std::uint8_t, x, 4)` → 4 位 | -| `BSF_NEST(T, 名称)` | 嵌套结构体 | `BSF_NEST(头部, hdr)` | -| `BSF_ARR(T, 名称, 长度)` | 自然位宽元素的定长数组 | `BSF_ARR(std::uint8_t, mac, 6)` | -| `BSF_ARR(T, 名称, 长度, 元素位宽)` | 自定义位宽元素的定长数组 | `BSF_ARR(std::int16_t, d, 4, 10)` | - -## 编译期尺寸计算 - -```cpp -static_assert(bitserial::bit_size_v<我的数据包> == 124); -static_assert(bitserial::byte_size_v<我的数据包> == 16); // (124 + 7) / 8 -``` - -## 用户提供缓冲区(零分配) - -```cpp -std::vector buf(bitserial::byte_size_v<我的数据包>); + +## 字段类型 + +| 宏 | 说明 | 示例 | +|-----|------|------| +| `BSF_F(T, 名称)` | 使用自然位宽的标量字段 | `BSF_F(std::uint16_t, x)` → 16 位 | +| `BSF_F(T, 名称, 位宽)` | 使用自定义位宽的标量字段 | `BSF_F(std::uint8_t, x, 4)` → 4 位 | +| `BSF_NEST(T, 名称)` | 嵌套结构体 | `BSF_NEST(头部, hdr)` | +| `BSF_ARR(T, 名称, 长度)` | 自然位宽元素的定长数组 | `BSF_ARR(std::uint8_t, mac, 6)` | +| `BSF_ARR(T, 名称, 长度, 元素位宽)` | 自定义位宽元素的定长数组 | `BSF_ARR(std::int16_t, d, 4, 10)` | + +## 编译期尺寸计算 + +```cpp +static_assert(bitserial::bit_size_v<我的数据包> == 124); +static_assert(bitserial::byte_size_v<我的数据包> == 16); // (124 + 7) / 8 +``` + +## 用户提供缓冲区(零分配) + +```cpp +std::vector buf(bitserial::byte_size_v<我的数据包>); bitserial::to_bytes(pkt, std::span(buf)); ``` @@ -122,46 +122,46 @@ Ninja Multi-Config 这类多配置生成器需要在 build 和 ctest 时额外 或 `-C Release`。 测试和 benchmark 都由 Catch2 组织。benchmark 使用 `[!benchmark]` 标签,因此普通 CTest 不会误跑性能测试。 - -## 错误处理 - -```cpp -// 缓冲区过小抛出 std::out_of_range -// 非法十六进制字符抛出 std::invalid_argument -``` - -## 真实协议示例:IPv4 头部 - -```cpp -#define IPV4_FIELDS(BSF) \ - BSF##_F(std::uint8_t, version, 4) \ - BSF##_F(std::uint8_t, ihl, 4) \ - BSF##_F(std::uint8_t, tos) \ - BSF##_F(std::uint16_t, total_len) \ - BSF##_F(std::uint16_t, id) \ - BSF##_F(std::uint8_t, flags, 3) \ - BSF##_F(std::uint16_t, frag_off, 13) \ - BSF##_F(std::uint8_t, ttl) \ - BSF##_F(std::uint8_t, proto) \ - BSF##_F(std::uint16_t, checksum) - -BITSERIAL_DEFINE(IPv4Head, IPV4_FIELDS); - -static_assert(bitserial::byte_size_v == 12); -``` - -## 拆分定义(追加成员方法) - -```cpp -#define SENSOR_FIELDS(BSF) \ - BSF##_F(std::uint16_t, id) \ - BSF##_F(std::int32_t, value) - -BITSERIAL_BEGIN(传感器数据, SENSOR_FIELDS) - bool 是否有效() const { return value != 0; } -BITSERIAL_END(传感器数据, SENSOR_FIELDS); -``` - -## 许可证 - -MIT + +## 错误处理 + +```cpp +// 缓冲区过小抛出 std::out_of_range +// 非法十六进制字符抛出 std::invalid_argument +``` + +## 真实协议示例:IPv4 头部 + +```cpp +#define IPV4_FIELDS(BSF) \ + BSF##_F(std::uint8_t, version, 4) \ + BSF##_F(std::uint8_t, ihl, 4) \ + BSF##_F(std::uint8_t, tos) \ + BSF##_F(std::uint16_t, total_len) \ + BSF##_F(std::uint16_t, id) \ + BSF##_F(std::uint8_t, flags, 3) \ + BSF##_F(std::uint16_t, frag_off, 13) \ + BSF##_F(std::uint8_t, ttl) \ + BSF##_F(std::uint8_t, proto) \ + BSF##_F(std::uint16_t, checksum) + +BITSERIAL_DEFINE(IPv4Head, IPV4_FIELDS); + +static_assert(bitserial::byte_size_v == 12); +``` + +## 拆分定义(追加成员方法) + +```cpp +#define SENSOR_FIELDS(BSF) \ + BSF##_F(std::uint16_t, id) \ + BSF##_F(std::int32_t, value) + +BITSERIAL_BEGIN(传感器数据, SENSOR_FIELDS) + bool 是否有效() const { return value != 0; } +BITSERIAL_END(传感器数据, SENSOR_FIELDS); +``` + +## 许可证 + +MIT diff --git a/README.md b/README.md index db8a207..9cb1ac4 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -# bitserial - -Big-endian, zero-padding, zero-allocation bit-field serialization framework for C++20 - +# bitserial + +Big-endian, zero-padding, zero-allocation bit-field serialization framework for C++20 + ## Features - **Single-declaration schema**: Define struct and serialization schema simultaneously (X-Macro style) @@ -10,73 +10,73 @@ Big-endian, zero-padding, zero-allocation bit-field serialization framework for - **Bulk BAQ paths**: `pack_bits` / `unpack_bits` for fixed-width byte arrays - Optimized AVX512BW and AVX2 unpack backends for 3/4/5-bit arrays when available - **Rich type support**: `bool`, signed/unsigned integers, `float32`, `float64` - - Automatic sign-extension for signed integers when reading -- **Composable**: Nested structs, fixed-length arrays -- **Multiple IO formats**: Bytes, span, hex -- **Zero-allocation**: Writes directly to user-provided `std::span` - -## Requirements - -- C++20 compiler - - GCC 10+, Clang 11+, MSVC 19.29+ (with `/Zc:preprocessor`) - + - Automatic sign-extension for signed integers when reading +- **Composable**: Nested structs, fixed-length arrays +- **Multiple IO formats**: Bytes, span, hex +- **Zero-allocation**: Writes directly to user-provided `std::span` + +## Requirements + +- C++20 compiler + - GCC 10+, Clang 11+, MSVC 19.29+ (with `/Zc:preprocessor`) + ## Quick Start ```cpp #include - -// 1. Define packet schema -#define MY_PACKET_FIELDS(BSF) \ - BSF##_F (std::uint8_t, version, 4) \ - BSF##_F (std::uint8_t, flags, 4) \ - BSF##_F (std::int16_t, temp) \ - BSF##_F (bool, ok) \ - BSF##_F (float, voltage) \ - BSF##_ARR(std::uint8_t, mac, 6) - -BITSERIAL_DEFINE(MyPacket, MY_PACKET_FIELDS); - -// 2. Serialize -MyPacket pkt{ - .version = 0xA, - .flags = 0x5, - .temp = -42, - .ok = true, - .voltage = 3.7f, - .mac = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}, -}; - -auto bytes = bitserial::to_bytes(pkt); -auto hex = bitserial::to_hex(pkt); // "A5..." - -// 3. Deserialize -auto pkt2 = bitserial::from_bytes(bytes); + +// 1. Define packet schema +#define MY_PACKET_FIELDS(BSF) \ + BSF##_F (std::uint8_t, version, 4) \ + BSF##_F (std::uint8_t, flags, 4) \ + BSF##_F (std::int16_t, temp) \ + BSF##_F (bool, ok) \ + BSF##_F (float, voltage) \ + BSF##_ARR(std::uint8_t, mac, 6) + +BITSERIAL_DEFINE(MyPacket, MY_PACKET_FIELDS); + +// 2. Serialize +MyPacket pkt{ + .version = 0xA, + .flags = 0x5, + .temp = -42, + .ok = true, + .voltage = 3.7f, + .mac = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}, +}; + +auto bytes = bitserial::to_bytes(pkt); +auto hex = bitserial::to_hex(pkt); // "A5..." + +// 3. Deserialize +auto pkt2 = bitserial::from_bytes(bytes); auto pkt3 = bitserial::from_hex(hex); ``` The legacy include `#include "bitserial.hpp"` is kept as a forwarding header. - -## Field Types - -| Macro | Description | Example | -|-------|-------------|---------| -| `BSF_F(T, name)` | Scalar with natural bit width | `BSF_F(std::uint16_t, x)` → 16 bits | -| `BSF_F(T, name, bits)` | Scalar with custom bit width | `BSF_F(std::uint8_t, x, 4)` → 4 bits | -| `BSF_NEST(T, name)` | Nested struct | `BSF_NEST(Header, hdr)` | -| `BSF_ARR(T, name, len)` | Fixed array with natural element width | `BSF_ARR(std::uint8_t, mac, 6)` | -| `BSF_ARR(T, name, len, ebits)` | Fixed array with custom element bits | `BSF_ARR(std::int16_t, d, 4, 10)` | - -## Compile-time Size Computation - -```cpp -static_assert(bitserial::bit_size_v == 124); -static_assert(bitserial::byte_size_v == 16); // (124 + 7) / 8 -``` - + +## Field Types + +| Macro | Description | Example | +|-------|-------------|---------| +| `BSF_F(T, name)` | Scalar with natural bit width | `BSF_F(std::uint16_t, x)` → 16 bits | +| `BSF_F(T, name, bits)` | Scalar with custom bit width | `BSF_F(std::uint8_t, x, 4)` → 4 bits | +| `BSF_NEST(T, name)` | Nested struct | `BSF_NEST(Header, hdr)` | +| `BSF_ARR(T, name, len)` | Fixed array with natural element width | `BSF_ARR(std::uint8_t, mac, 6)` | +| `BSF_ARR(T, name, len, ebits)` | Fixed array with custom element bits | `BSF_ARR(std::int16_t, d, 4, 10)` | + +## Compile-time Size Computation + +```cpp +static_assert(bitserial::bit_size_v == 124); +static_assert(bitserial::byte_size_v == 16); // (124 + 7) / 8 +``` + ## User-provided Buffer (Zero-allocation) - -```cpp -std::vector buf(bitserial::byte_size_v); + +```cpp +std::vector buf(bitserial::byte_size_v); bitserial::to_bytes(pkt, std::span(buf)); ``` @@ -124,46 +124,46 @@ Multi-config generators such as Visual Studio and Ninja Multi-Config need Both tests and benchmarks are organized through Catch2. The benchmark executable uses the `[!benchmark]` tag, so benchmarks do not run during normal CTest runs. - -## Error Handling - -```cpp -// Throws std::out_of_range if buffer is too small -// Throws std::invalid_argument for invalid hex characters -``` - -## Real-world Example: IPv4 Header - -```cpp -#define IPV4_FIELDS(BSF) \ - BSF##_F(std::uint8_t, version, 4) \ - BSF##_F(std::uint8_t, ihl, 4) \ - BSF##_F(std::uint8_t, tos) \ - BSF##_F(std::uint16_t, total_len) \ - BSF##_F(std::uint16_t, id) \ - BSF##_F(std::uint8_t, flags, 3) \ - BSF##_F(std::uint16_t, frag_off, 13) \ - BSF##_F(std::uint8_t, ttl) \ - BSF##_F(std::uint8_t, proto) \ - BSF##_F(std::uint16_t, checksum) - -BITSERIAL_DEFINE(IPv4Head, IPV4_FIELDS); - -static_assert(bitserial::byte_size_v == 12); -``` - -## Split Definition (Add Methods) - -```cpp -#define SENSOR_FIELDS(BSF) \ - BSF##_F(std::uint16_t, id) \ - BSF##_F(std::int32_t, value) - -BITSERIAL_BEGIN(SensorData, SENSOR_FIELDS) - bool is_valid() const { return value != 0; } -BITSERIAL_END(SensorData, SENSOR_FIELDS); -``` - -## License - -MIT + +## Error Handling + +```cpp +// Throws std::out_of_range if buffer is too small +// Throws std::invalid_argument for invalid hex characters +``` + +## Real-world Example: IPv4 Header + +```cpp +#define IPV4_FIELDS(BSF) \ + BSF##_F(std::uint8_t, version, 4) \ + BSF##_F(std::uint8_t, ihl, 4) \ + BSF##_F(std::uint8_t, tos) \ + BSF##_F(std::uint16_t, total_len) \ + BSF##_F(std::uint16_t, id) \ + BSF##_F(std::uint8_t, flags, 3) \ + BSF##_F(std::uint16_t, frag_off, 13) \ + BSF##_F(std::uint8_t, ttl) \ + BSF##_F(std::uint8_t, proto) \ + BSF##_F(std::uint16_t, checksum) + +BITSERIAL_DEFINE(IPv4Head, IPV4_FIELDS); + +static_assert(bitserial::byte_size_v == 12); +``` + +## Split Definition (Add Methods) + +```cpp +#define SENSOR_FIELDS(BSF) \ + BSF##_F(std::uint16_t, id) \ + BSF##_F(std::int32_t, value) + +BITSERIAL_BEGIN(SensorData, SENSOR_FIELDS) + bool is_valid() const { return value != 0; } +BITSERIAL_END(SensorData, SENSOR_FIELDS); +``` + +## License + +MIT diff --git a/benchmarks/baq_bulk_benchmarks.cpp b/benchmarks/baq_bulk_benchmarks.cpp index 2c983a5..df77772 100644 --- a/benchmarks/baq_bulk_benchmarks.cpp +++ b/benchmarks/baq_bulk_benchmarks.cpp @@ -1,12 +1,11 @@ #include "catch_amalgamated.hpp" - -#include - #include +#include #include #include #include #include +#include #include #include #include @@ -14,191 +13,225 @@ namespace { -constexpr std::size_t kElementCount = 1024 * 1024; + constexpr std::size_t kElementCount = 1024 * 1024; -struct BandwidthBenchmark { - std::string name; - std::size_t bytes_per_operation; -}; + template struct BaqSchemaPacket { + std::uint8_t data[kElementCount]; + }; -std::vector &bandwidth_benchmarks() { - static std::vector benchmarks; - return benchmarks; -} +} // namespace -void record_bandwidth_benchmark( - std::string const &name, - std::size_t bytes_per_operation -) { - auto &benchmarks = bandwidth_benchmarks(); - auto it = std::ranges::find(benchmarks, name, &BandwidthBenchmark::name); - if (it == benchmarks.end()) { - benchmarks.push_back({name, bytes_per_operation}); - } else { - it->bytes_per_operation = bytes_per_operation; - } -} +namespace bitserial { -std::size_t bytes_per_operation_for(std::string const &name) { - auto const &benchmarks = bandwidth_benchmarks(); - auto it = std::ranges::find(benchmarks, name, &BandwidthBenchmark::name); - return it == benchmarks.end() ? 0 : it->bytes_per_operation; -} + template struct schema_of> { + using BitserialSelf = BaqSchemaPacket; + static constexpr auto fields = std::make_tuple( + ::bitserial::ArrayField<&BitserialSelf::data, Bits>{}, + ::bitserial::detail::tuple_end{} + ); + }; -struct ScaledBandwidth { - double value; - char const *unit; -}; +} // namespace bitserial -ScaledBandwidth scale_bandwidth(double bytes_per_second) { - char const *units[] = {"B/s", "KB/s", "MB/s", "GB/s", "TB/s"}; - std::size_t unit_index = 0; - while (bytes_per_second >= 1000.0 && unit_index + 1 < std::size(units)) { - bytes_per_second /= 1000.0; - ++unit_index; - } - return {bytes_per_second, units[unit_index]}; -} +namespace { -int bandwidth_precision(double value) { - if (value >= 100.0) { - return 1; - } - if (value >= 10.0) { - return 2; - } - return 3; -} + struct BandwidthBenchmark { + std::string name; + std::size_t bytes_per_operation; + }; -class BandwidthReporter : public Catch::EventListenerBase { -public: - using Catch::EventListenerBase::EventListenerBase; - - void benchmarkEnded(Catch::BenchmarkStats<> const &stats) override { - auto const bytes_per_operation = bytes_per_operation_for(stats.info.name); - auto const seconds_per_operation = stats.mean.point.count() * 1e-9; - if (bytes_per_operation == 0 || seconds_per_operation <= 0.0) { - return; - } - - auto const bandwidth = - scale_bandwidth(static_cast(bytes_per_operation) / - seconds_per_operation); - auto const old_flags = std::cout.flags(); - auto const old_precision = std::cout.precision(); - std::cout << "\n bandwidth: " << std::fixed - << std::setprecision(bandwidth_precision(bandwidth.value)) - << bandwidth.value << ' ' << bandwidth.unit << " (" - << bytes_per_operation << " bytes/op)\n"; - std::cout.flags(old_flags); - std::cout.precision(old_precision); - } -}; - -CATCH_REGISTER_LISTENER(BandwidthReporter); - -template -struct BaqFixture { - static constexpr std::uint8_t max_value = - static_cast((1u << Bits) - 1u); - - std::vector src; - std::vector packed_ref; - std::vector packed_bulk; - std::vector unpacked_ref; - std::vector unpacked_bulk; - - explicit BaqFixture(std::size_t n = kElementCount) : - src(n), - packed_ref((n * Bits + 7) / 8, 0), - packed_bulk((n * Bits + 7) / 8, 0), - unpacked_ref(n), - unpacked_bulk(n) { - std::mt19937 gen(0xB17u + static_cast(Bits)); - std::uniform_int_distribution dist(0, max_value); - for (std::uint8_t &x : src) { - x = static_cast(dist(gen)); - } - - pack_reference(src, packed_ref); - bitserial::pack_bits(src, packed_bulk); - REQUIRE(packed_bulk == packed_ref); - - unpack_reference(packed_ref, unpacked_ref); - bitserial::unpack_bits(packed_ref, unpacked_bulk); - REQUIRE(unpacked_bulk == unpacked_ref); + std::vector &bandwidth_benchmarks() { + static std::vector benchmarks; + return benchmarks; } - static void pack_reference( - std::span in, - std::span out - ) noexcept { - std::size_t bit_pos = 0; - for (const std::uint8_t x : in) { - bitserial::write_bits(out, bit_pos, Bits, x & max_value); - bit_pos += Bits; + void record_bandwidth_benchmark( + std::string const &name, std::size_t bytes_per_operation + ) { + auto &benchmarks = bandwidth_benchmarks(); + auto it = std::ranges::find(benchmarks, name, &BandwidthBenchmark::name); + if (it == benchmarks.end()) { + benchmarks.push_back({name, bytes_per_operation}); + } else { + it->bytes_per_operation = bytes_per_operation; } } - static void unpack_reference( - std::span in, - std::span out - ) noexcept { - std::size_t bit_pos = 0; - for (std::uint8_t &x : out) { - x = static_cast(bitserial::read_bits(in, bit_pos, Bits)); - bit_pos += Bits; + std::size_t bytes_per_operation_for(std::string const &name) { + auto const &benchmarks = bandwidth_benchmarks(); + auto it = std::ranges::find(benchmarks, name, &BandwidthBenchmark::name); + return it == benchmarks.end() ? 0 : it->bytes_per_operation; + } + + struct ScaledBandwidth { + double value; + char const *unit; + }; + + ScaledBandwidth scale_bandwidth(double bytes_per_second) { + char const *units[] = {"B/s", "KB/s", "MB/s", "GB/s", "TB/s"}; + std::size_t unit_index = 0; + while (bytes_per_second >= 1000.0 && unit_index + 1 < std::size(units)) { + bytes_per_second /= 1000.0; + ++unit_index; + } + return {bytes_per_second, units[unit_index]}; + } + + int bandwidth_precision(double value) { + if (value >= 100.0) { return 1; } + if (value >= 10.0) { return 2; } + return 3; + } + + class BandwidthReporter : public Catch::EventListenerBase { + public: + using Catch::EventListenerBase::EventListenerBase; + + void benchmarkEnded(Catch::BenchmarkStats<> const &stats) override { + auto const bytes_per_operation = bytes_per_operation_for(stats.info.name); + auto const seconds_per_operation = stats.mean.point.count() * 1e-9; + if (bytes_per_operation == 0 || seconds_per_operation <= 0.0) { return; } + + auto const bandwidth = scale_bandwidth( + static_cast(bytes_per_operation) / seconds_per_operation + ); + auto const old_flags = std::cout.flags(); + auto const old_precision = std::cout.precision(); + std::cout << "\n bandwidth: " << std::fixed + << std::setprecision(bandwidth_precision(bandwidth.value)) + << bandwidth.value << ' ' << bandwidth.unit << " (" + << bytes_per_operation << " bytes/op)\n"; + std::cout.flags(old_flags); + std::cout.precision(old_precision); + } + }; + + CATCH_REGISTER_LISTENER(BandwidthReporter); + + template struct BaqFixture { + static constexpr std::uint8_t max_value = + static_cast((1u << Bits) - 1u); + + std::vector src; + std::vector packed_ref; + std::vector packed_bulk; + std::vector packed_schema; + std::vector unpacked_ref; + std::vector unpacked_bulk; + std::unique_ptr> schema_src; + + explicit BaqFixture(std::size_t n = kElementCount) + : src(n), packed_ref((n * Bits + 7) / 8, 0), + packed_bulk((n * Bits + 7) / 8, 0), + packed_schema(bitserial::byte_size_v>, 0), + unpacked_ref(n), unpacked_bulk(n), + schema_src(std::make_unique>()) { + std::mt19937 gen(0xB17u + static_cast(Bits)); + std::uniform_int_distribution dist(0, max_value); + for (std::uint8_t &x : src) { + x = static_cast(dist(gen)); + } + std::ranges::copy(src, schema_src->data); + + pack_reference(src, packed_ref); + bitserial::pack_bits(src, packed_bulk); + REQUIRE(packed_bulk == packed_ref); + + unpack_reference(packed_ref, unpacked_ref); + bitserial::unpack_bits(packed_ref, unpacked_bulk); + REQUIRE(unpacked_bulk == unpacked_ref); + + if (n == kElementCount) { + bitserial::to_bytes(*schema_src, packed_schema); + REQUIRE(packed_schema == packed_ref); + auto schema_unpacked = + bitserial::from_bytes>(packed_ref); + REQUIRE(std::ranges::equal(unpacked_ref, schema_unpacked.data)); + } + } + + static void pack_reference( + std::span in, std::span out + ) noexcept { + std::size_t bit_pos = 0; + for (const std::uint8_t x : in) { + bitserial::write_bits(out, bit_pos, Bits, x & max_value); + bit_pos += Bits; + } + } + + static void unpack_reference( + std::span in, std::span out + ) noexcept { + std::size_t bit_pos = 0; + for (std::uint8_t &x : out) { + x = static_cast(bitserial::read_bits(in, bit_pos, Bits)); + bit_pos += Bits; + } + } + }; + + template void check_edges() { + for (std::size_t n = 0; n <= 257; ++n) { + BaqFixture f(n); + CAPTURE(Bits, n); + CHECK(f.packed_bulk == f.packed_ref); + CHECK(f.unpacked_bulk == f.unpacked_ref); } } -}; -template -void check_edges() { - for (std::size_t n = 0; n <= 257; ++n) { - BaqFixture f(n); - CAPTURE(Bits, n); - CHECK(f.packed_bulk == f.packed_ref); - CHECK(f.unpacked_bulk == f.unpacked_ref); + template void run_benchmarks(char const *label) { + BaqFixture f; + CAPTURE(label, Bits, f.src.size(), f.packed_ref.size()); + auto const bytes_per_operation = f.src.size() + f.packed_ref.size(); + + auto const pack_reference_name = + std::string(label) + " pack read/write_bits loop"; + auto const pack_bulk_name = std::string(label) + " pack bitserial bulk"; + auto const pack_schema_name = std::string(label) + " pack schema to_bytes"; + auto const unpack_reference_name = + std::string(label) + " unpack read_bits loop"; + auto const unpack_bulk_name = std::string(label) + " unpack bitserial bulk"; + auto const unpack_schema_name = + std::string(label) + " unpack schema from_bytes"; + + record_bandwidth_benchmark(pack_reference_name, bytes_per_operation); + BENCHMARK(std::string(pack_reference_name)) { + BaqFixture::pack_reference(f.src, f.packed_ref); + return f.packed_ref.front(); + }; + + record_bandwidth_benchmark(pack_bulk_name, bytes_per_operation); + BENCHMARK(std::string(pack_bulk_name)) { + bitserial::pack_bits(f.src, f.packed_bulk); + return f.packed_bulk.front(); + }; + + record_bandwidth_benchmark(pack_schema_name, bytes_per_operation); + BENCHMARK(std::string(pack_schema_name)) { + bitserial::to_bytes(*f.schema_src, f.packed_schema); + return f.packed_schema.front(); + }; + + record_bandwidth_benchmark(unpack_reference_name, bytes_per_operation); + BENCHMARK(std::string(unpack_reference_name)) { + BaqFixture::unpack_reference(f.packed_ref, f.unpacked_ref); + return f.unpacked_ref.front(); + }; + + record_bandwidth_benchmark(unpack_bulk_name, bytes_per_operation); + BENCHMARK(std::string(unpack_bulk_name)) { + bitserial::unpack_bits(f.packed_ref, f.unpacked_bulk); + return f.unpacked_bulk.front(); + }; + + record_bandwidth_benchmark(unpack_schema_name, bytes_per_operation); + BENCHMARK(std::string(unpack_schema_name)) { + auto packet = bitserial::from_bytes>(f.packed_ref); + return packet.data[0]; + }; } -} - -template -void run_benchmarks(char const *label) { - BaqFixture f; - CAPTURE(label, Bits, f.src.size(), f.packed_ref.size()); - auto const bytes_per_operation = f.src.size() + f.packed_ref.size(); - - auto const pack_reference_name = - std::string(label) + " pack read/write_bits loop"; - auto const pack_bulk_name = std::string(label) + " pack bitserial bulk"; - auto const unpack_reference_name = - std::string(label) + " unpack read_bits loop"; - auto const unpack_bulk_name = std::string(label) + " unpack bitserial bulk"; - - record_bandwidth_benchmark(pack_reference_name, bytes_per_operation); - BENCHMARK(std::string(pack_reference_name)) { - BaqFixture::pack_reference(f.src, f.packed_ref); - return f.packed_ref.front(); - }; - - record_bandwidth_benchmark(pack_bulk_name, bytes_per_operation); - BENCHMARK(std::string(pack_bulk_name)) { - bitserial::pack_bits(f.src, f.packed_bulk); - return f.packed_bulk.front(); - }; - - record_bandwidth_benchmark(unpack_reference_name, bytes_per_operation); - BENCHMARK(std::string(unpack_reference_name)) { - BaqFixture::unpack_reference(f.packed_ref, f.unpacked_ref); - return f.unpacked_ref.front(); - }; - - record_bandwidth_benchmark(unpack_bulk_name, bytes_per_operation); - BENCHMARK(std::string(unpack_bulk_name)) { - bitserial::unpack_bits(f.packed_ref, f.unpacked_bulk); - return f.unpacked_bulk.front(); - }; -} } // namespace diff --git a/include/bitserial/bit_io.hpp b/include/bitserial/bit_io.hpp index 8098a84..7645e3f 100644 --- a/include/bitserial/bit_io.hpp +++ b/include/bitserial/bit_io.hpp @@ -1,7 +1,6 @@ #pragma once #include - #include #include #include diff --git a/include/bitserial/bitserial.hpp b/include/bitserial/bitserial.hpp index ecff666..c22f009 100644 --- a/include/bitserial/bitserial.hpp +++ b/include/bitserial/bitserial.hpp @@ -1,551 +1,552 @@ -// ============================================================================= -// bitserial.hpp — 大端、无填充、零分配的位域序列化框架(C++20) -// 作者:DawnMagnet 时间:2026年4月27日 邮箱:axccjqh@qq.com -// ----------------------------------------------------------------------------- -// 特性: -// * 单次声明同时生成 struct 与序列化 schema(X-Macro 风格) -// * 全编译期展开,无运行时反射开销 -// * 大端 MSB-first 位流,字段间无任何填充 -// * 自动支持 bool、有符号/无符号整数、float32、float64 -// - 位字段读出时按符号位扩展(符号整数) -// * 支持嵌套结构体、定长数组 -// * 提供 bytes / span / hex 三种 IO 形式 -// * 写入用户 std::span,不做内部分配 -// -// 编译要求:C++20(GCC 10+ / Clang 11+ / MSVC 19.29+ 且加 /Zc:preprocessor) -// ============================================================================= -#pragma once - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// IEEE 754 仅在编译期校验一次:浮点序列化依赖标准布局 -static_assert(sizeof(float) == 4, "bitserial requires 32-bit float"); -static_assert(sizeof(double) == 8, "bitserial requires 64-bit double"); - -namespace bitserial { - - // ============================================================================= - // 字段描述符(由注册宏自动生成,用户一般不直接构造) - // ============================================================================= - - /// 标量字段:以 Bits 位打包成员 *MemPtr - template 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; - }; - - /// 嵌套结构体字段:递归调用其 schema - template struct Nested { - static constexpr auto ptr = MemPtr; - static constexpr bool is_nested = true; - static constexpr bool is_array = false; - }; - - /// 定长数组字段:每个元素占 ElemBits 位 - template 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 { - - /// 字段元组的尾哨兵,吸收宏展开末尾的逗号 - struct tuple_end { - static constexpr bool is_nested = false; - static constexpr bool is_array = false; - static constexpr std::size_t bits = 0; - }; - - // 从成员指针 M C::* 萃取成员类型 - template struct member_traits; - template struct member_traits { - using class_type = C; - using member_type = M; - }; - // 处理 const 修饰的成员指针(const 在 * 右侧) - template struct member_traits { - using class_type = C; - using member_type = M; - }; - template - using member_type_t = typename member_traits::member_type; - - // ============================================================================= - // 标量 <-> uint64 双向转换:完整处理 bool / 整数 / 浮点 - // ----------------------------------------------------------------------------- - // 规则: - // * bool → 0/1,1 bit 即可 - // * 无符号整型 → 直接转换 - // * 有符号整型 → 按位字段宽度做符号位扩展(read 时) - // * float → bit_cast,按 32 位定长打包 - // * double → bit_cast,按 64 位定长打包 - // - // 位字段宽度 (bits) 的合法性: - // * bool: 1 - // * 整数: 1..sizeof(T)*8 - // * float32: 必须 == 32 - // * float64: 必须 == 64 - // ============================================================================= - - template - inline constexpr bool is_supported_scalar_v = - std::is_same_v || std::is_integral_v || - std::is_same_v || std::is_same_v; - - /// 标量字段的「自然位宽」:用于用户省略位宽时的默认值 - template consteval std::size_t natural_bits() noexcept { - if constexpr (std::is_same_v) return 1; - else if constexpr (std::is_integral_v) - return sizeof(T) * 8; - else if constexpr (std::is_same_v) - return 32; - else if constexpr (std::is_same_v) - return 64; - else { - static_assert( - is_supported_scalar_v, "bitserial: unsupported scalar type" - ); - return 0; - } - } - - /// 把标量编码为用于位流的 uint64 - template - constexpr std::uint64_t encode_scalar(T v, std::size_t bits) noexcept { - static_assert( - is_supported_scalar_v, "bitserial: unsupported scalar type" - ); - if constexpr (std::is_same_v) { - return v ? 1u : 0u; - } else if constexpr (std::is_same_v) { - (void)bits; - return std::bit_cast(v); - } else if constexpr (std::is_same_v) { - (void)bits; - return std::bit_cast(v); - } else if constexpr (std::is_signed_v) { - // 有符号:截取低 bits 位(补码自然表示) - using U = std::make_unsigned_t; - const auto u = static_cast(v); - const std::uint64_t mask = - (bits == 64) ? ~std::uint64_t{0} : ((std::uint64_t{1} << bits) - 1); - return static_cast(u) & mask; - } else { - return static_cast(v); - } - } - - /// 把位流读出的 uint64 解码回标量 - template - constexpr T decode_scalar(std::uint64_t raw, std::size_t bits) noexcept { - static_assert( - is_supported_scalar_v, "bitserial: unsupported scalar type" - ); - if constexpr (std::is_same_v) { - return raw != 0; - } else if constexpr (std::is_same_v) { - return std::bit_cast(static_cast(raw)); - } else if constexpr (std::is_same_v) { - return std::bit_cast(raw); - } else if constexpr (std::is_signed_v) { - // 符号扩展:若最高位(bits-1)为 1,则把高位补 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( - static_cast>(raw) - ); - } else { - return static_cast(raw); - } - } - - /// 校验位宽合法性(编译期) - template - consteval void validate_bits() noexcept { - static_assert( - is_supported_scalar_v, "bitserial: unsupported scalar type" - ); - if constexpr (std::is_same_v) { - static_assert( - Bits >= 1 && Bits <= 8, "bitserial: bool field must use 1..8 bits" - ); - } else if constexpr (std::is_same_v) { - static_assert(Bits == 32, "bitserial: float must be exactly 32 bits"); - } else if constexpr (std::is_same_v) { - 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 - - // ============================================================================= - // Schema 主模板:用户的注册宏会显式特化此模板 - // ============================================================================= - - template struct schema_of; - - template struct has_schema : std::false_type {}; - template - struct has_schema::fields)>> : - std::true_type {}; - template - inline constexpr bool has_schema_v = has_schema::value; - - // ============================================================================= - // 编译期位宽计算 - // ============================================================================= - - template consteval std::size_t bit_size() noexcept; - - template consteval std::size_t field_bits() noexcept { - if constexpr (std::is_same_v) { - return 0; - } else if constexpr (F::is_nested) { - return bit_size>(); - } else if constexpr (F::is_array) { - using Arr = detail::member_type_t; - return std::extent_v * F::elem_bits; - } else { - return F::bits; - } - } - - template consteval std::size_t bit_size() noexcept { - static_assert( - has_schema_v, - "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()), ...); - }, - schema_of::fields - ); - return n; - } - - template inline constexpr std::size_t bit_size_v = bit_size(); - template - inline constexpr std::size_t byte_size_v = (bit_size_v + 7) / 8; - - // ============================================================================= - // 字段读写 - // ============================================================================= - - template - constexpr void to_bytes_impl( - const T &obj, std::span out, std::size_t &pos - ); - - template - constexpr void from_bytes_impl( - T &obj, std::span in, std::size_t &pos - ); - - template - constexpr void - write_field(const T &obj, std::span out, std::size_t &pos) { - if constexpr (std::is_same_v) { - 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; - using Elem = std::remove_extent_t; - detail::validate_bits(); - const auto &arr = obj.*F::ptr; - constexpr std::size_t N = std::extent_v; - if constexpr (std::is_same_v) { - pack_bits(std::span(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(arr[i], F::elem_bits) - ); - pos += F::elem_bits; - } - } - } else { - using M = detail::member_type_t; - detail::validate_bits(); - write_bits( - out, pos, F::bits, detail::encode_scalar(obj.*F::ptr, F::bits) - ); - pos += F::bits; - } - } - - template - constexpr void - read_field(T &obj, std::span in, std::size_t &pos) { - if constexpr (std::is_same_v) { - 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; - using Elem = std::remove_extent_t; - detail::validate_bits(); - auto &arr = obj.*F::ptr; - constexpr std::size_t N = std::extent_v; - if constexpr (std::is_same_v) { - unpack_bits(in, std::span(arr), pos); - pos += N * F::elem_bits; - } else { - for (std::size_t i = 0; i < N; ++i) { - arr[i] = detail::decode_scalar( - read_bits(in, pos, F::elem_bits), F::elem_bits - ); - pos += F::elem_bits; - } - } - } else { - using M = detail::member_type_t; - detail::validate_bits(); - obj.*F::ptr = - detail::decode_scalar(read_bits(in, pos, F::bits), F::bits); - pos += F::bits; - } - } - - template - constexpr void to_bytes_impl( - const T &obj, std::span out, std::size_t &pos - ) { - static_assert(has_schema_v, "bitserial: missing schema"); - std::apply( - [&](auto... fs) { - (write_field(obj, out, pos), ...); - }, - schema_of::fields - ); - } - - template - constexpr void from_bytes_impl( - T &obj, std::span in, std::size_t &pos - ) { - static_assert(has_schema_v, "bitserial: missing schema"); - std::apply( - [&](auto... fs) { - (read_field(obj, in, pos), ...); - }, - schema_of::fields - ); - } - - // ============================================================================= - // 对外 API - // ============================================================================= - - /// 写入用户缓冲(零分配),out 至少需要 byte_size_v 字节 - template - constexpr void to_bytes(const T &obj, std::span out) { - if (out.size() < byte_size_v) - throw std::out_of_range("bitserial::to_bytes: buffer too small"); - std::size_t pos = 0; - to_bytes_impl(obj, out, pos); - } - - /// 序列化为定长 std::array - template - [[nodiscard]] constexpr std::array> - to_bytes(const T &obj) { - std::array> buf{}; - std::size_t pos = 0; - to_bytes_impl(obj, std::span(buf), pos); - return buf; - } - - /// 反序列化 - template - [[nodiscard]] constexpr T from_bytes(std::span in) { - if (in.size() < byte_size_v) - 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 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(c - '0'); - if (c >= 'a' && c <= 'f') return static_cast(c - 'a' + 10); - if (c >= 'A' && c <= 'F') return static_cast(c - 'A' + 10); - throw std::invalid_argument("bitserial: invalid hex character"); - } - } // namespace detail - - inline void hex_to_bytes(std::string_view h, std::span 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( - (detail::hex_nibble(h[2 * i]) << 4) | detail::hex_nibble(h[2 * i + 1]) - ); - } - } - - template - [[nodiscard]] std::string to_hex(const T &obj, bool upper = true) { - auto buf = to_bytes(obj); - return bytes_to_hex(std::span(buf), upper); - } - - template [[nodiscard]] T from_hex(std::string_view h) { - std::array> buf{}; - hex_to_bytes(h, std::span(buf)); - return from_bytes(std::span(buf)); - } - -} // namespace bitserial - -// ============================================================================= -// 注册宏部分 -// ----------------------------------------------------------------------------- -// 字段表中可使用: -// BSF##_F (TYPE, NAME) -> 位宽 = 自然位宽(int/float/...) -// BSF##_F (TYPE, NAME, BITS) -> 位宽 = BITS(仅整型/bool 可定制) -// BSF##_NEST(TYPE, NAME) -// BSF##_ARR (TYPE, NAME, LEN) -> 元素位宽 = 自然位宽 -// BSF##_ARR (TYPE, NAME, LEN, EBITS) -// ============================================================================= - -// ---- 基础工具 --------------------------------------------------------------- - -#define BSF_DETAIL_NTH_3(_1, _2, _3, N, ...) N -#define BSF_DETAIL_NTH_4(_1, _2, _3, _4, N, ...) N - -// ---- 第一遍:生成 struct 成员 ----------------------------------------------- - -#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__ \ - ) - -// ---- 第二遍:生成 schema 元组元素 ------------------------------------------- - -#define BSF_DETAIL_SCHEMA_F_2(TYPE, NAME) \ - ::bitserial::Field< \ - &BitserialSelf::NAME, ::bitserial::detail::natural_bits()>{}, -#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()>{}, -#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__ \ - ) - -// ---- 用户 API --------------------------------------------------------------- - -#define BITSERIAL_EMIT_MEMBERS(FIELDS_MACRO) FIELDS_MACRO(BSF_DETAIL_MEMBER) -#define BITSERIAL_EMIT_SCHEMA(FIELDS_MACRO) FIELDS_MACRO(BSF_DETAIL_SCHEMA) - -/** - * @brief 一行声明:同时生成 struct 与 schema_of 特化。 - * - * 用法: - * - * #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 { \ - using BitserialSelf = TYPE; \ - static constexpr auto fields = std::make_tuple( \ - BITSERIAL_EMIT_SCHEMA(FIELDS_MACRO)::bitserial::detail::tuple_end{} \ - ); \ - } - -/// 拆分版:BEGIN 开启结构体(可在中间追加成员/方法),END 闭合并生成 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 { \ - using BitserialSelf = TYPE; \ - static constexpr auto fields = std::make_tuple( \ - BITSERIAL_EMIT_SCHEMA(FIELDS_MACRO)::bitserial::detail::tuple_end{} \ - ); \ - } +// ============================================================================= +// bitserial.hpp — 大端、无填充、零分配的位域序列化框架(C++20) +// 作者:DawnMagnet 时间:2026年4月27日 邮箱:axccjqh@qq.com +// ----------------------------------------------------------------------------- +// 特性: +// * 单次声明同时生成 struct 与序列化 schema(X-Macro 风格) +// * 全编译期展开,无运行时反射开销 +// * 大端 MSB-first 位流,字段间无任何填充 +// * 自动支持 bool、有符号/无符号整数、float32、float64 +// - 位字段读出时按符号位扩展(符号整数) +// * 支持嵌套结构体、定长数组 +// * 提供 bytes / span / hex 三种 IO 形式 +// * 写入用户 std::span,不做内部分配 +// +// 编译要求:C++20(GCC 10+ / Clang 11+ / MSVC 19.29+ 且加 /Zc:preprocessor) +// ============================================================================= +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// IEEE 754 仅在编译期校验一次:浮点序列化依赖标准布局 +static_assert(sizeof(float) == 4, "bitserial requires 32-bit float"); +static_assert(sizeof(double) == 8, "bitserial requires 64-bit double"); + +namespace bitserial { + + // ============================================================================= + // 字段描述符(由注册宏自动生成,用户一般不直接构造) + // ============================================================================= + + /// 标量字段:以 Bits 位打包成员 *MemPtr + template 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; + }; + + /// 嵌套结构体字段:递归调用其 schema + template struct Nested { + static constexpr auto ptr = MemPtr; + static constexpr bool is_nested = true; + static constexpr bool is_array = false; + }; + + /// 定长数组字段:每个元素占 ElemBits 位 + template 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 { + + /// 字段元组的尾哨兵,吸收宏展开末尾的逗号 + struct tuple_end { + static constexpr bool is_nested = false; + static constexpr bool is_array = false; + static constexpr std::size_t bits = 0; + }; + + // 从成员指针 M C::* 萃取成员类型 + template struct member_traits; + template struct member_traits { + using class_type = C; + using member_type = M; + }; + // 处理 const 修饰的成员指针(const 在 * 右侧) + template struct member_traits { + using class_type = C; + using member_type = M; + }; + template + using member_type_t = typename member_traits::member_type; + + // ============================================================================= + // 标量 <-> uint64 双向转换:完整处理 bool / 整数 / 浮点 + // ----------------------------------------------------------------------------- + // 规则: + // * bool → 0/1,1 bit 即可 + // * 无符号整型 → 直接转换 + // * 有符号整型 → 按位字段宽度做符号位扩展(read 时) + // * float → bit_cast,按 32 位定长打包 + // * double → bit_cast,按 64 位定长打包 + // + // 位字段宽度 (bits) 的合法性: + // * bool: 1 + // * 整数: 1..sizeof(T)*8 + // * float32: 必须 == 32 + // * float64: 必须 == 64 + // ============================================================================= + + template + inline constexpr bool is_supported_scalar_v = + std::is_same_v || std::is_integral_v || + std::is_same_v || std::is_same_v; + + /// 标量字段的「自然位宽」:用于用户省略位宽时的默认值 + template consteval std::size_t natural_bits() noexcept { + if constexpr (std::is_same_v) return 1; + else if constexpr (std::is_integral_v) + return sizeof(T) * 8; + else if constexpr (std::is_same_v) + return 32; + else if constexpr (std::is_same_v) + return 64; + else { + static_assert( + is_supported_scalar_v, "bitserial: unsupported scalar type" + ); + return 0; + } + } + + /// 把标量编码为用于位流的 uint64 + template + constexpr std::uint64_t encode_scalar(T v, std::size_t bits) noexcept { + static_assert( + is_supported_scalar_v, "bitserial: unsupported scalar type" + ); + if constexpr (std::is_same_v) { + return v ? 1u : 0u; + } else if constexpr (std::is_same_v) { + (void)bits; + return std::bit_cast(v); + } else if constexpr (std::is_same_v) { + (void)bits; + return std::bit_cast(v); + } else if constexpr (std::is_signed_v) { + // 有符号:截取低 bits 位(补码自然表示) + using U = std::make_unsigned_t; + const auto u = static_cast(v); + const std::uint64_t mask = + (bits == 64) ? ~std::uint64_t{0} : ((std::uint64_t{1} << bits) - 1); + return static_cast(u) & mask; + } else { + return static_cast(v); + } + } + + /// 把位流读出的 uint64 解码回标量 + template + constexpr T decode_scalar(std::uint64_t raw, std::size_t bits) noexcept { + static_assert( + is_supported_scalar_v, "bitserial: unsupported scalar type" + ); + if constexpr (std::is_same_v) { + return raw != 0; + } else if constexpr (std::is_same_v) { + return std::bit_cast(static_cast(raw)); + } else if constexpr (std::is_same_v) { + return std::bit_cast(raw); + } else if constexpr (std::is_signed_v) { + // 符号扩展:若最高位(bits-1)为 1,则把高位补 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( + static_cast>(raw) + ); + } else { + return static_cast(raw); + } + } + + /// 校验位宽合法性(编译期) + template + consteval void validate_bits() noexcept { + static_assert( + is_supported_scalar_v, "bitserial: unsupported scalar type" + ); + if constexpr (std::is_same_v) { + static_assert( + Bits >= 1 && Bits <= 8, "bitserial: bool field must use 1..8 bits" + ); + } else if constexpr (std::is_same_v) { + static_assert(Bits == 32, "bitserial: float must be exactly 32 bits"); + } else if constexpr (std::is_same_v) { + 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 + + // ============================================================================= + // Schema 主模板:用户的注册宏会显式特化此模板 + // ============================================================================= + + template struct schema_of; + + template struct has_schema : std::false_type {}; + template + struct has_schema::fields)>> : + std::true_type {}; + template + inline constexpr bool has_schema_v = has_schema::value; + + // ============================================================================= + // 编译期位宽计算 + // ============================================================================= + + template consteval std::size_t bit_size() noexcept; + + template consteval std::size_t field_bits() noexcept { + if constexpr (std::is_same_v) { + return 0; + } else if constexpr (F::is_nested) { + return bit_size>(); + } else if constexpr (F::is_array) { + using Arr = detail::member_type_t; + return std::extent_v * F::elem_bits; + } else { + return F::bits; + } + } + + template consteval std::size_t bit_size() noexcept { + static_assert( + has_schema_v, + "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()), ...); + }, + schema_of::fields + ); + return n; + } + + template inline constexpr std::size_t bit_size_v = bit_size(); + template + inline constexpr std::size_t byte_size_v = (bit_size_v + 7) / 8; + + // ============================================================================= + // 字段读写 + // ============================================================================= + + template + constexpr void to_bytes_impl( + const T &obj, std::span out, std::size_t &pos + ); + + template + constexpr void from_bytes_impl( + T &obj, std::span in, std::size_t &pos + ); + + template + constexpr void + write_field(const T &obj, std::span out, std::size_t &pos) { + if constexpr (std::is_same_v) { + 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; + using Elem = std::remove_extent_t; + detail::validate_bits(); + const auto &arr = obj.*F::ptr; + constexpr std::size_t N = std::extent_v; + if constexpr (std::is_same_v) { + pack_bits( + std::span(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(arr[i], F::elem_bits) + ); + pos += F::elem_bits; + } + } + } else { + using M = detail::member_type_t; + detail::validate_bits(); + write_bits( + out, pos, F::bits, detail::encode_scalar(obj.*F::ptr, F::bits) + ); + pos += F::bits; + } + } + + template + constexpr void + read_field(T &obj, std::span in, std::size_t &pos) { + if constexpr (std::is_same_v) { + 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; + using Elem = std::remove_extent_t; + detail::validate_bits(); + auto &arr = obj.*F::ptr; + constexpr std::size_t N = std::extent_v; + if constexpr (std::is_same_v) { + unpack_bits(in, std::span(arr), pos); + pos += N * F::elem_bits; + } else { + for (std::size_t i = 0; i < N; ++i) { + arr[i] = detail::decode_scalar( + read_bits(in, pos, F::elem_bits), F::elem_bits + ); + pos += F::elem_bits; + } + } + } else { + using M = detail::member_type_t; + detail::validate_bits(); + obj.*F::ptr = + detail::decode_scalar(read_bits(in, pos, F::bits), F::bits); + pos += F::bits; + } + } + + template + constexpr void to_bytes_impl( + const T &obj, std::span out, std::size_t &pos + ) { + static_assert(has_schema_v, "bitserial: missing schema"); + std::apply( + [&](auto... fs) { + (write_field(obj, out, pos), ...); + }, + schema_of::fields + ); + } + + template + constexpr void from_bytes_impl( + T &obj, std::span in, std::size_t &pos + ) { + static_assert(has_schema_v, "bitserial: missing schema"); + std::apply( + [&](auto... fs) { + (read_field(obj, in, pos), ...); + }, + schema_of::fields + ); + } + + // ============================================================================= + // 对外 API + // ============================================================================= + + /// 写入用户缓冲(零分配),out 至少需要 byte_size_v 字节 + template + constexpr void to_bytes(const T &obj, std::span out) { + if (out.size() < byte_size_v) + throw std::out_of_range("bitserial::to_bytes: buffer too small"); + std::size_t pos = 0; + to_bytes_impl(obj, out, pos); + } + + /// 序列化为定长 std::array + template + [[nodiscard]] constexpr std::array> + to_bytes(const T &obj) { + std::array> buf{}; + std::size_t pos = 0; + to_bytes_impl(obj, std::span(buf), pos); + return buf; + } + + /// 反序列化 + template + [[nodiscard]] constexpr T from_bytes(std::span in) { + if (in.size() < byte_size_v) + 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 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(c - '0'); + if (c >= 'a' && c <= 'f') return static_cast(c - 'a' + 10); + if (c >= 'A' && c <= 'F') return static_cast(c - 'A' + 10); + throw std::invalid_argument("bitserial: invalid hex character"); + } + } // namespace detail + + inline void hex_to_bytes(std::string_view h, std::span 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( + (detail::hex_nibble(h[2 * i]) << 4) | detail::hex_nibble(h[2 * i + 1]) + ); + } + } + + template + [[nodiscard]] std::string to_hex(const T &obj, bool upper = true) { + auto buf = to_bytes(obj); + return bytes_to_hex(std::span(buf), upper); + } + + template [[nodiscard]] T from_hex(std::string_view h) { + std::array> buf{}; + hex_to_bytes(h, std::span(buf)); + return from_bytes(std::span(buf)); + } + +} // namespace bitserial + +// ============================================================================= +// 注册宏部分 +// ----------------------------------------------------------------------------- +// 字段表中可使用: +// BSF##_F (TYPE, NAME) -> 位宽 = 自然位宽(int/float/...) +// BSF##_F (TYPE, NAME, BITS) -> 位宽 = BITS(仅整型/bool 可定制) +// BSF##_NEST(TYPE, NAME) +// BSF##_ARR (TYPE, NAME, LEN) -> 元素位宽 = 自然位宽 +// BSF##_ARR (TYPE, NAME, LEN, EBITS) +// ============================================================================= + +// ---- 基础工具 --------------------------------------------------------------- + +#define BSF_DETAIL_NTH_3(_1, _2, _3, N, ...) N +#define BSF_DETAIL_NTH_4(_1, _2, _3, _4, N, ...) N + +// ---- 第一遍:生成 struct 成员 ----------------------------------------------- + +#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__ \ + ) + +// ---- 第二遍:生成 schema 元组元素 ------------------------------------------- + +#define BSF_DETAIL_SCHEMA_F_2(TYPE, NAME) \ + ::bitserial::Field< \ + &BitserialSelf::NAME, ::bitserial::detail::natural_bits()>{}, +#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()>{}, +#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__ \ + ) + +// ---- 用户 API --------------------------------------------------------------- + +#define BITSERIAL_EMIT_MEMBERS(FIELDS_MACRO) FIELDS_MACRO(BSF_DETAIL_MEMBER) +#define BITSERIAL_EMIT_SCHEMA(FIELDS_MACRO) FIELDS_MACRO(BSF_DETAIL_SCHEMA) + +/** + * @brief 一行声明:同时生成 struct 与 schema_of 特化。 + * + * 用法: + * + * #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 { \ + using BitserialSelf = TYPE; \ + static constexpr auto fields = std::make_tuple( \ + BITSERIAL_EMIT_SCHEMA(FIELDS_MACRO)::bitserial::detail::tuple_end{} \ + ); \ + } + +/// 拆分版:BEGIN 开启结构体(可在中间追加成员/方法),END 闭合并生成 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 { \ + using BitserialSelf = TYPE; \ + static constexpr auto fields = std::make_tuple( \ + BITSERIAL_EMIT_SCHEMA(FIELDS_MACRO)::bitserial::detail::tuple_end{} \ + ); \ + } diff --git a/include/bitserial/bulk.hpp b/include/bitserial/bulk.hpp index 90a52f4..89feb30 100644 --- a/include/bitserial/bulk.hpp +++ b/include/bitserial/bulk.hpp @@ -1,16 +1,15 @@ #pragma once -#include - #include #include +#include #include #include #include #include #if defined(BITSERIAL_DETAIL_HAS_X86_INTRINSICS) -# include + #include #endif namespace bitserial { @@ -20,7 +19,8 @@ namespace bitserial { template constexpr void pack_bits_scalar( std::span in, - std::span out, + std::span + out, std::size_t bit_pos ) noexcept { static_assert(Bits >= 1 && Bits <= 8); @@ -33,7 +33,8 @@ namespace bitserial { template constexpr void unpack_bits_scalar( std::span in, - std::span out, + std::span + out, std::size_t bit_pos ) noexcept { static_assert(Bits >= 1 && Bits <= 8); @@ -45,8 +46,7 @@ namespace bitserial { template constexpr void pack_bits_byte_aligned_scalar( - std::span in, - std::span out + std::span in, std::span out ) noexcept { static_assert(Bits >= 1 && Bits <= 8); std::size_t i = 0; @@ -62,13 +62,18 @@ namespace bitserial { 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((a0 << 5) | (a1 << 2) | (a2 >> 1)); - out[o + 1] = static_cast((a2 << 7) | (a3 << 4) | (a4 << 1) | (a5 >> 2)); + out[o + 0] = + static_cast((a0 << 5) | (a1 << 2) | (a2 >> 1)); + out[o + 1] = static_cast( + (a2 << 7) | (a3 << 4) | (a4 << 1) | (a5 >> 2) + ); out[o + 2] = static_cast((a5 << 6) | (a6 << 3) | a7); } } else if constexpr (Bits == 4) { for (; i + 2 <= in.size(); i += 2, ++o) { - out[o] = static_cast(((in[i] & 0x0F) << 4) | (in[i + 1] & 0x0F)); + out[o] = static_cast( + ((in[i] & 0x0F) << 4) | (in[i + 1] & 0x0F) + ); } } else if constexpr (Bits == 5) { for (; i + 8 <= in.size(); i += 8, o += 5) { @@ -81,9 +86,11 @@ namespace bitserial { const std::uint8_t a6 = in[i + 6] & 0x1F; const std::uint8_t a7 = in[i + 7] & 0x1F; out[o + 0] = static_cast((a0 << 3) | (a1 >> 2)); - out[o + 1] = static_cast((a1 << 6) | (a2 << 1) | (a3 >> 4)); + out[o + 1] = + static_cast((a1 << 6) | (a2 << 1) | (a3 >> 4)); out[o + 2] = static_cast((a3 << 4) | (a4 >> 1)); - out[o + 3] = static_cast((a4 << 7) | (a5 << 2) | (a6 >> 3)); + out[o + 3] = + static_cast((a4 << 7) | (a5 << 2) | (a6 >> 3)); out[o + 4] = static_cast((a6 << 5) | a7); } } @@ -114,16 +121,14 @@ namespace bitserial { 0xF800, 0x07C0, 0x3E00, 0x01F0, 0x0F80, 0x7C00, 0x03E0, 0x001F, }; alignas(32) inline constexpr std::array k_baq5_mul = { - 1, 32, 4, 128, 16, 2, 64, 2048, - 1, 32, 4, 128, 16, 2, 64, 2048, + 1, 32, 4, 128, 16, 2, 64, 2048, 1, 32, 4, 128, 16, 2, 64, 2048, }; template - BITSERIAL_DETAIL_TARGET_AVX2 - inline std::size_t unpack_bits_avx2_aligned_prefix( - std::span in, - std::span out - ) noexcept { + BITSERIAL_DETAIL_TARGET_AVX2 inline std::size_t + unpack_bits_avx2_aligned_prefix( + std::span in, std::span out + ) noexcept { static_assert(Bits == 3 || Bits == 4 || Bits == 5); if constexpr (Bits == 4) { @@ -131,7 +136,8 @@ namespace bitserial { std::size_t i = 0; for (; i + 64 <= out.size(); i += 64) { const __m256i src = _mm256_loadu_si256( - reinterpret_cast(in.data() + (i >> 1))); + reinterpret_cast(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); @@ -139,30 +145,36 @@ namespace bitserial { const __m256i b = _mm256_unpackhi_epi8(hi, lo); _mm256_storeu_si256( reinterpret_cast<__m256i *>(out.data() + i), - _mm256_permute2x128_si256(a, b, 0x20)); + _mm256_permute2x128_si256(a, b, 0x20) + ); _mm256_storeu_si256( reinterpret_cast<__m256i *>(out.data() + i + 32), - _mm256_permute2x128_si256(a, b, 0x31)); + _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 &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(shuffle_table.data())); + reinterpret_cast(shuffle_table.data()) + ); const __m256i mask = _mm256_load_si256( - reinterpret_cast(mask_table.data())); + reinterpret_cast(mask_table.data()) + ); const __m256i mul = _mm256_load_si256( - reinterpret_cast(mul_table.data())); + reinterpret_cast(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) + ? std::min( + full_groups, ((in.size() - 16) / packed_per_group) + 1 + ) : 0; std::size_t group = 0; @@ -170,12 +182,17 @@ namespace bitserial { 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(in.data() + in_idx))); + reinterpret_cast(in.data() + in_idx) + )); x = _mm256_inserti128_si256( x, - _mm_loadu_si128(reinterpret_cast( - in.data() + in_idx + packed_per_group)), - 1); + _mm_loadu_si128( + reinterpret_cast( + 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); @@ -183,23 +200,28 @@ namespace bitserial { x = _mm256_packus_epi16(x, x); _mm_storel_epi64( reinterpret_cast<__m128i *>(out.data() + out_idx), - _mm256_castsi256_si128(x)); + _mm256_castsi256_si128(x) + ); _mm_storel_epi64( reinterpret_cast<__m128i *>(out.data() + out_idx + 8), - _mm256_extracti128_si256(x, 1)); + _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(in.data() + in_idx)); + reinterpret_cast(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); + _mm_storel_epi64( + reinterpret_cast<__m128i *>(out.data() + out_idx), x + ); ++group; } @@ -210,11 +232,10 @@ namespace bitserial { #if defined(BITSERIAL_DETAIL_CAN_BUILD_AVX512BW) template - BITSERIAL_DETAIL_TARGET_AVX512BW - inline std::size_t unpack_bits_avx512bw_aligned_prefix( - std::span in, - std::span out - ) noexcept { + BITSERIAL_DETAIL_TARGET_AVX512BW inline std::size_t + unpack_bits_avx512bw_aligned_prefix( + std::span in, std::span out + ) noexcept { static_assert(Bits == 3 || Bits == 4 || Bits == 5); if constexpr (Bits == 4) { @@ -222,7 +243,8 @@ namespace bitserial { std::size_t i = 0; for (; i + 128 <= out.size(); i += 128) { const __m512i src = _mm512_loadu_si512( - reinterpret_cast(in.data() + (i >> 1))); + reinterpret_cast(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); @@ -231,48 +253,60 @@ namespace bitserial { _mm_storeu_si128( reinterpret_cast<__m128i *>(out.data() + i), - _mm512_extracti32x4_epi32(a, 0)); + _mm512_extracti32x4_epi32(a, 0) + ); _mm_storeu_si128( reinterpret_cast<__m128i *>(out.data() + i + 16), - _mm512_extracti32x4_epi32(b, 0)); + _mm512_extracti32x4_epi32(b, 0) + ); _mm_storeu_si128( reinterpret_cast<__m128i *>(out.data() + i + 32), - _mm512_extracti32x4_epi32(a, 1)); + _mm512_extracti32x4_epi32(a, 1) + ); _mm_storeu_si128( reinterpret_cast<__m128i *>(out.data() + i + 48), - _mm512_extracti32x4_epi32(b, 1)); + _mm512_extracti32x4_epi32(b, 1) + ); _mm_storeu_si128( reinterpret_cast<__m128i *>(out.data() + i + 64), - _mm512_extracti32x4_epi32(a, 2)); + _mm512_extracti32x4_epi32(a, 2) + ); _mm_storeu_si128( reinterpret_cast<__m128i *>(out.data() + i + 80), - _mm512_extracti32x4_epi32(b, 2)); + _mm512_extracti32x4_epi32(b, 2) + ); _mm_storeu_si128( reinterpret_cast<__m128i *>(out.data() + i + 96), - _mm512_extracti32x4_epi32(a, 3)); + _mm512_extracti32x4_epi32(a, 3) + ); _mm_storeu_si128( reinterpret_cast<__m128i *>(out.data() + i + 112), - _mm512_extracti32x4_epi32(b, 3)); + _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 &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(shuffle_table.data()))); - const __m512i mask = _mm512_broadcast_i32x4(_mm_load_si128( - reinterpret_cast(mask_table.data()))); - const __m512i mul = _mm512_broadcast_i32x4(_mm_load_si128( - reinterpret_cast(mul_table.data()))); + reinterpret_cast(shuffle_table.data()) + )); + const __m512i mask = _mm512_broadcast_i32x4( + _mm_load_si128(reinterpret_cast(mask_table.data())) + ); + const __m512i mul = _mm512_broadcast_i32x4( + _mm_load_si128(reinterpret_cast(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) + ? std::min( + full_groups, ((in.size() - 16) / packed_per_group) + 1 + ) : 0; std::size_t group = 0; @@ -280,22 +314,35 @@ namespace bitserial { 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(in.data() + in_idx))); + reinterpret_cast(in.data() + in_idx) + )); x = _mm512_inserti32x4( x, - _mm_loadu_si128(reinterpret_cast( - in.data() + in_idx + packed_per_group)), - 1); + _mm_loadu_si128( + reinterpret_cast( + in.data() + in_idx + packed_per_group + ) + ), + 1 + ); x = _mm512_inserti32x4( x, - _mm_loadu_si128(reinterpret_cast( - in.data() + in_idx + packed_per_group * 2)), - 2); + _mm_loadu_si128( + reinterpret_cast( + in.data() + in_idx + packed_per_group * 2 + ) + ), + 2 + ); x = _mm512_inserti32x4( x, - _mm_loadu_si128(reinterpret_cast( - in.data() + in_idx + packed_per_group * 3)), - 3); + _mm_loadu_si128( + reinterpret_cast( + 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); @@ -304,16 +351,20 @@ namespace bitserial { _mm_storel_epi64( reinterpret_cast<__m128i *>(out.data() + out_idx), - _mm512_extracti32x4_epi32(x, 0)); + _mm512_extracti32x4_epi32(x, 0) + ); _mm_storel_epi64( reinterpret_cast<__m128i *>(out.data() + out_idx + 8), - _mm512_extracti32x4_epi32(x, 1)); + _mm512_extracti32x4_epi32(x, 1) + ); _mm_storel_epi64( reinterpret_cast<__m128i *>(out.data() + out_idx + 16), - _mm512_extracti32x4_epi32(x, 2)); + _mm512_extracti32x4_epi32(x, 2) + ); _mm_storel_epi64( reinterpret_cast<__m128i *>(out.data() + out_idx + 24), - _mm512_extracti32x4_epi32(x, 3)); + _mm512_extracti32x4_epi32(x, 3) + ); } return group * 8; @@ -321,29 +372,30 @@ namespace bitserial { } #endif -#if defined(BITSERIAL_DETAIL_CAN_BUILD_AVX2) || defined(BITSERIAL_DETAIL_CAN_BUILD_AVX512BW) +#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) + #if defined(BITSERIAL_DETAIL_HAS_GNU_TARGET_INTRINSICS) __builtin_cpu_init(); return __builtin_cpu_supports("avx2"); -# elif defined(BITSERIAL_DETAIL_HAS_AVX2) + #elif defined(BITSERIAL_DETAIL_HAS_AVX2) return true; -# else + #else return false; -# endif + #endif } inline bool cpu_supports_avx512bw() noexcept { -# if defined(BITSERIAL_DETAIL_HAS_GNU_TARGET_INTRINSICS) + #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) + #elif defined(BITSERIAL_DETAIL_HAS_AVX512BW) return true; -# else + #else return false; -# endif + #endif } #endif @@ -352,7 +404,8 @@ namespace bitserial { template constexpr void pack_bits( std::span in, - std::span out, + std::span + out, std::size_t bit_pos = 0 ) noexcept { static_assert(Bits >= 1 && Bits <= 8, "bitserial: bit width out of range"); @@ -363,7 +416,10 @@ namespace bitserial { } if constexpr (Bits == 8) { - std::copy(in.begin(), in.end(), out.begin() + static_cast(bit_pos >> 3)); + std::copy( + in.begin(), in.end(), + out.begin() + static_cast(bit_pos >> 3) + ); } else if constexpr (Bits == 3 || Bits == 4 || Bits == 5) { detail::pack_bits_byte_aligned_scalar( in, out.subspan(bit_pos >> 3) @@ -376,7 +432,8 @@ namespace bitserial { template constexpr void unpack_bits( std::span in, - std::span out, + std::span + out, std::size_t bit_pos = 0 ) noexcept { static_assert(Bits >= 1 && Bits <= 8, "bitserial: bit width out of range"); @@ -387,16 +444,20 @@ namespace bitserial { } if constexpr (Bits == 8) { - std::copy_n(in.begin() + static_cast(bit_pos >> 3), out.size(), out.begin()); + std::copy_n( + in.begin() + static_cast(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( - in.subspan(bit_pos >> 3), out - ); + const std::size_t done = + detail::unpack_bits_avx512bw_aligned_prefix( + in.subspan(bit_pos >> 3), out + ); detail::unpack_bits_scalar( in, out.subspan(done), bit_pos + done * Bits ); diff --git a/include/bitserial/detail/config.hpp b/include/bitserial/detail/config.hpp index 5e1373f..52c8b30 100644 --- a/include/bitserial/detail/config.hpp +++ b/include/bitserial/detail/config.hpp @@ -1,46 +1,50 @@ #pragma once #if defined(_MSC_VER) && _MSC_VER < 1929 -# error "bitserial requires MSVC 19.29 or newer for C++20 support." + #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 + #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." + #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 +#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 + #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")]] + #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 + #define BITSERIAL_DETAIL_TARGET_AVX2 + #define BITSERIAL_DETAIL_TARGET_AVX512BW #endif #if defined(__AVX2__) || defined(__AVX512BW__) -# define BITSERIAL_DETAIL_HAS_AVX2 1 + #define BITSERIAL_DETAIL_HAS_AVX2 1 #endif #if defined(__AVX512F__) && defined(__AVX512BW__) -# define BITSERIAL_DETAIL_HAS_AVX512BW 1 + #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 +#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 +#if defined(BITSERIAL_DETAIL_HAS_AVX512BW) || \ + defined(BITSERIAL_DETAIL_HAS_GNU_TARGET_INTRINSICS) + #define BITSERIAL_DETAIL_CAN_BUILD_AVX512BW 1 #endif diff --git a/tests/bitserial_tests.cpp b/tests/bitserial_tests.cpp index 2335b97..704ce24 100644 --- a/tests/bitserial_tests.cpp +++ b/tests/bitserial_tests.cpp @@ -1,618 +1,624 @@ -#include "catch_amalgamated.hpp" -#include -#include -#include -#include -#include -#include -#include - -// ============================================================================= -// 1) 无符号整数 + 跨字节位宽 -// ============================================================================= - -#define UINT_FIELDS(BSF) \ - BSF##_F(std::uint8_t, a, 4) BSF##_F(std::uint8_t, b, 4) \ - BSF##_F(std::uint16_t, c, 12) BSF##_F(std::uint32_t, d, 20) \ - BSF##_F(std::uint64_t, e, 40) - -BITSERIAL_DEFINE(UnsignedPkt, UINT_FIELDS); - -TEST_CASE("unsigned integers with cross-byte bit widths") { - static_assert(bitserial::bit_size_v == 4 + 4 + 12 + 20 + 40); - static_assert( - bitserial::byte_size_v == (4 + 4 + 12 + 20 + 40 + 7) / 8 - ); - - UnsignedPkt x{ - .a = 0xA, .b = 0x5, .c = 0xABC, .d = 0xFEDCB, .e = 0x1122334455ull - }; - - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - - CHECK(y.a == 0xA); - CHECK(y.b == 0x5); - CHECK(y.c == 0xABC); - CHECK(y.d == 0xFEDCB); - CHECK(y.e == 0x1122334455ull); - - UnsignedPkt overflow{ - .a = 0xFF, // truncated to 0xF - .b = 0xFF, // 0xF - .c = 0xFFFF, // 0xFFF - .d = 0xFFFFFFFFu, // 0xFFFFF - .e = ~0ull, - }; - auto y2 = bitserial::from_bytes(bitserial::to_bytes(overflow)); - CHECK(y2.a == 0xF); - CHECK(y2.b == 0xF); - CHECK(y2.c == 0xFFF); - CHECK(y2.d == 0xFFFFFu); - CHECK(y2.e == (std::uint64_t{1} << 40) - 1); -} - -// ============================================================================= -// 2) 有符号整数:正、负、边界、位宽截取与符号扩展 -// ============================================================================= - -#define INT_FIELDS(BSF) \ - BSF##_F(std::int8_t, i8) BSF##_F(std::int16_t, i16) \ - BSF##_F(std::int32_t, i32) BSF##_F(std::int64_t, i64) \ - BSF##_F(std::int16_t, small, 10) /* -512..511 */ \ - BSF##_F(std::int32_t, mid, 20) /* -524288..524287 */ \ - BSF##_F(std::int64_t, big, 33) /* crosses 4 bytes */ - -BITSERIAL_DEFINE(SignedPkt, INT_FIELDS); - -TEST_CASE("signed integers: positive values") { - SignedPkt x{ - .i8 = 0x12, - .i16 = 0x1234, - .i32 = 0x12345678, - .i64 = 0x1122334455667788ll, - .small = 100, - .mid = 12345, - .big = 123456789ll, - }; - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - CHECK(y.i8 == 0x12); - CHECK(y.i16 == 0x1234); - CHECK(y.i32 == 0x12345678); - CHECK(y.i64 == 0x1122334455667788ll); - CHECK(y.small == 100); - CHECK(y.mid == 12345); - CHECK(y.big == 123456789ll); -} - -TEST_CASE("signed integers: negative values") { - SignedPkt x{ - .i8 = -1, - .i16 = -2, - .i32 = -3, - .i64 = -4, - .small = -1, - .mid = -1, - .big = -1, - }; - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - CHECK(y.i8 == -1); - CHECK(y.i16 == -2); - CHECK(y.i32 == -3); - CHECK(y.i64 == -4); - CHECK(y.small == -1); - CHECK(y.mid == -1); - CHECK(y.big == -1); -} - -TEST_CASE("signed integers: boundary values") { - using L8 = std::numeric_limits; - using L16 = std::numeric_limits; - using L32 = std::numeric_limits; - using L64 = std::numeric_limits; - - SignedPkt x_min{ - .i8 = L8::min(), - .i16 = L16::min(), - .i32 = L32::min(), - .i64 = L64::min(), - .small = -512, - .mid = -524288, - .big = -(1ll << 32), - }; - auto y = bitserial::from_bytes(bitserial::to_bytes(x_min)); - CHECK(y.i8 == L8::min()); - CHECK(y.i16 == L16::min()); - CHECK(y.i32 == L32::min()); - CHECK(y.i64 == L64::min()); - CHECK(y.small == -512); - CHECK(y.mid == -524288); - CHECK(y.big == -(1ll << 32)); - - SignedPkt x_max{ - .i8 = L8::max(), - .i16 = L16::max(), - .i32 = L32::max(), - .i64 = L64::max(), - .small = 511, - .mid = 524287, - .big = (1ll << 32) - 1, - }; - auto y2 = bitserial::from_bytes(bitserial::to_bytes(x_max)); - CHECK(y2.i8 == L8::max()); - CHECK(y2.i16 == L16::max()); - CHECK(y2.i32 == L32::max()); - CHECK(y2.i64 == L64::max()); - CHECK(y2.small == 511); - CHECK(y2.mid == 524287); - CHECK(y2.big == (1ll << 32) - 1); -} - -// ============================================================================= -// 3) bool:单 bit 与多 bit -// ============================================================================= - -#define BOOL_FIELDS(BSF) \ - BSF##_F(bool, a) \ - BSF##_F(bool, b) \ - BSF##_F(bool, c, 4) \ - BSF##_F(bool, d, 8) \ - BSF##_F(std::uint8_t, pad, 2) - -BITSERIAL_DEFINE(BoolPkt, BOOL_FIELDS); - -TEST_CASE("bool fields: single and multi-bit") { - static_assert(bitserial::byte_size_v == 2); - - BoolPkt x{.a = true, .b = false, .c = true, .d = true, .pad = 3}; - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - CHECK(y.a == true); - CHECK(y.b == false); - CHECK(y.c == true); - CHECK(y.d == true); - CHECK(y.pad == 3); - - BoolPkt z{.a = false, .b = false, .c = false, .d = false, .pad = 0}; - auto z2 = bitserial::from_bytes(bitserial::to_bytes(z)); - CHECK(z2.a == false); - CHECK(z2.d == false); -} - -// ============================================================================= -// 4) float / double:含特殊值 -// ============================================================================= - -#define FLOAT_FIELDS(BSF) \ - BSF##_F(float, f1) BSF##_F(float, f2) BSF##_F(double, d1) BSF##_F(double, d2) - -BITSERIAL_DEFINE(FloatPkt, FLOAT_FIELDS); - -TEST_CASE("float and double: basic roundtrip") { - static_assert(bitserial::byte_size_v == 4 + 4 + 8 + 8); - - FloatPkt x{ - .f1 = 3.14159265f, - .f2 = -2.71828f, - .d1 = 1.41421356237309504, - .d2 = -1e-300, - }; - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - CHECK(std::bit_cast(y.f1) == - std::bit_cast(x.f1)); - CHECK(std::bit_cast(y.f2) == - std::bit_cast(x.f2)); - CHECK(std::bit_cast(y.d1) == - std::bit_cast(x.d1)); - CHECK(std::bit_cast(y.d2) == - std::bit_cast(x.d2)); -} - -TEST_CASE("float and double: special values (inf, nan, -0, subnormal)") { - const float pinf = std::numeric_limits::infinity(); - const float ninf = -pinf; - const float qnan = std::numeric_limits::quiet_NaN(); - const double pinfd = std::numeric_limits::infinity(); - const double mzero = -0.0; - const float sub = std::numeric_limits::denorm_min(); - - FloatPkt x{.f1 = pinf, .f2 = ninf, .d1 = pinfd, .d2 = mzero}; - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - CHECK((std::isinf(y.f1) && y.f1 > 0)); - CHECK((std::isinf(y.f2) && y.f2 < 0)); - CHECK(std::isinf(y.d1)); - CHECK(std::bit_cast(y.d2) == - std::bit_cast(mzero)); - - FloatPkt z{.f1 = qnan, .f2 = sub, .d1 = 0.0, .d2 = 0.0}; - auto z2 = bitserial::from_bytes(bitserial::to_bytes(z)); - CHECK(std::isnan(z2.f1)); - CHECK(std::bit_cast(z2.f2) == - std::bit_cast(sub)); -} - -// ============================================================================= -// 5) 嵌套结构体 -// ============================================================================= - -#define INNER_FIELDS(BSF) \ - BSF##_F(std::uint8_t, tag, 4) BSF##_F(std::uint16_t, val, 12) - -BITSERIAL_DEFINE(Inner, INNER_FIELDS); - -#define OUTER_FIELDS(BSF) \ - BSF##_F(std::uint8_t, hdr) BSF##_NEST(Inner, a) BSF##_NEST(Inner, b) \ - BSF##_F(std::uint8_t, ftr) - -BITSERIAL_DEFINE(Outer, OUTER_FIELDS); - -TEST_CASE("nested structs") { - static_assert(bitserial::bit_size_v == 16); - static_assert(bitserial::bit_size_v == 8 + 16 + 16 + 8); - - Outer x{ - .hdr = 0xAB, - .a = {.tag = 0x3, .val = 0x123}, - .b = {.tag = 0xC, .val = 0xDEF}, - .ftr = 0xCD, - }; - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - CHECK(y.hdr == 0xAB); - CHECK(y.a.tag == 0x3); - CHECK(y.a.val == 0x123); - CHECK(y.b.tag == 0xC); - CHECK(y.b.val == 0xDEF); - CHECK(y.ftr == 0xCD); -} - -// ============================================================================= -// 6) 定长数组(自然位宽 / 自定义位宽) -// ============================================================================= - -#define ARR_NATURAL_FIELDS(BSF) \ - BSF##_ARR(std::uint8_t, bytes6, 6) BSF##_ARR(std::uint16_t, words3, 3) - -BITSERIAL_DEFINE(ArrNat, ARR_NATURAL_FIELDS); - -#define ARR_PACKED_FIELDS(BSF) \ - BSF##_ARR(std::uint16_t, q12, 5, 12) /* 5 x 12 bits = 60 bits */ \ - BSF##_ARR(std::int16_t, s10, 4, 10) /* 4 x 10 bits signed = 40 bits */ \ - BSF##_F(std::uint8_t, pad, 4) - -BITSERIAL_DEFINE(ArrPacked, ARR_PACKED_FIELDS); - -TEST_CASE("arrays: natural bit widths") { - static_assert(bitserial::byte_size_v == 6 + 6); - - ArrNat x{}; - for (int i = 0; i < 6; ++i) - x.bytes6[i] = static_cast(i + 1); - x.words3[0] = 0x1111; - x.words3[1] = 0x2222; - x.words3[2] = 0x3333; - - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - for (int i = 0; i < 6; ++i) - CHECK(y.bytes6[i] == i + 1); - CHECK(y.words3[0] == 0x1111); - CHECK(y.words3[1] == 0x2222); - CHECK(y.words3[2] == 0x3333); -} - -TEST_CASE("arrays: packed with custom bit widths") { - static_assert(bitserial::bit_size_v == 60 + 40 + 4); - - ArrPacked x{}; - x.q12[0] = 0xABC; - x.q12[1] = 0x123; - x.q12[2] = 0xFFF; - x.q12[3] = 0x000; - x.q12[4] = 0x555; - x.s10[0] = -1; - x.s10[1] = 511; - x.s10[2] = -512; - x.s10[3] = 0; - x.pad = 0xA; - - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - CHECK(y.q12[0] == 0xABC); - CHECK(y.q12[1] == 0x123); - CHECK(y.q12[2] == 0xFFF); - CHECK(y.q12[3] == 0x000); - CHECK(y.q12[4] == 0x555); - CHECK(y.s10[0] == -1); - CHECK(y.s10[1] == 511); - CHECK(y.s10[2] == -512); - CHECK(y.s10[3] == 0); - CHECK(y.pad == 0xA); -} - -// ============================================================================= -// 7) HEX 与 bytes 双向转换 -// ============================================================================= - -TEST_CASE("hex roundtrip: upper and lowercase") { - UnsignedPkt x{ - .a = 0xA, .b = 0x5, .c = 0xABC, .d = 0xFEDCB, .e = 0xCAFEBABEFEull - }; - - auto hex_upper = bitserial::to_hex(x, /*upper=*/true); - auto hex_lower = bitserial::to_hex(x, /*upper=*/false); - - CHECK(hex_upper.size() == bitserial::byte_size_v * 2); - CHECK(hex_lower.size() == bitserial::byte_size_v * 2); - - auto y1 = bitserial::from_hex(hex_upper); - auto y2 = bitserial::from_hex(hex_lower); - CHECK(y1.a == x.a); - CHECK(y1.e == x.e); - CHECK(y2.c == x.c); - CHECK(y2.d == x.d); -} - -// ============================================================================= -// 8) 字节序:手工验证 MSB-first 的位排布 -// ============================================================================= - -TEST_CASE("byte order: MSB-first layout verification") { - UnsignedPkt x{ - .a = 0xA, - .b = 0x5, - .c = 0xABC, - .d = 0xFEDCB, - .e = 0x1122334455ull, - }; - auto buf = bitserial::to_bytes(x); - - CHECK(buf[0] == 0xA5); - CHECK(buf[1] == 0xAB); - CHECK(buf[2] == 0xCF); - CHECK(buf[3] == 0xED); - CHECK(buf[4] == 0xCB); - CHECK(buf[5] == 0x11); - CHECK(buf[6] == 0x22); - CHECK(buf[7] == 0x33); - CHECK(buf[8] == 0x44); - CHECK(buf[9] == 0x55); -} - -// ============================================================================= -// 9) 边界与异常 -// ============================================================================= - -TEST_CASE("error handling: buffer too small") { - UnsignedPkt x{}; - std::array - 1> small{}; - - CHECK_THROWS_AS( - bitserial::to_bytes(x, std::span(small)), - std::out_of_range - ); - CHECK_THROWS_AS( - bitserial::from_bytes(std::span(small)), - std::out_of_range - ); -} - -TEST_CASE("error handling: hex parsing errors") { - CHECK_THROWS_AS( - bitserial::from_hex("DEAD"), std::invalid_argument - ); - - std::string bad(bitserial::byte_size_v * 2, 'X'); - CHECK_THROWS_AS( - bitserial::from_hex(bad), std::invalid_argument - ); -} - -// ============================================================================= -// 10) 真实协议示例:IPv4 头部前 12 字节 -// ============================================================================= - -#define IPV4_FIELDS(BSF) \ - BSF##_F(std::uint8_t, version, 4) BSF##_F(std::uint8_t, ihl, 4) \ - BSF##_F(std::uint8_t, tos) BSF##_F(std::uint16_t, total_len) \ - BSF##_F(std::uint16_t, id) BSF##_F(std::uint8_t, flags, 3) \ - BSF##_F(std::uint16_t, frag_off, 13) BSF##_F(std::uint8_t, ttl) \ - BSF##_F(std::uint8_t, proto) \ - BSF##_F(std::uint16_t, checksum) - -BITSERIAL_DEFINE(IPv4Head, IPV4_FIELDS); - -TEST_CASE("real protocol: IPv4 header layout") { - static_assert(bitserial::byte_size_v == 12); - - IPv4Head h{ - .version = 4, - .ihl = 5, - .tos = 0, - .total_len = 0x0073, - .id = 0x1234, - .flags = 0b010, - .frag_off = 0, - .ttl = 64, - .proto = 17, - .checksum = 0xB861, - }; - - const auto buf = bitserial::to_bytes(h); - - const std::uint8_t expect[] = { - 0x45, 0x00, 0x00, 0x73, 0x12, 0x34, 0x40, 0x00, 0x40, 0x11, 0xB8, 0x61, - }; - for (std::size_t i = 0; i < sizeof(expect); ++i) - CHECK(buf[i] == expect[i]); - - CHECK(bitserial::to_hex(h) == "45000073123440004011B861"); - auto h2 = bitserial::from_hex("45000073123440004011B861"); - CHECK(h2.version == 4); - CHECK(h2.ihl == 5); - CHECK(h2.flags == 0b010); - CHECK(h2.frag_off == 0); - CHECK(h2.ttl == 64); - CHECK(h2.proto == 17); - CHECK(h2.checksum == 0xB861); -} - -// ============================================================================= -// 11) 综合压力:所有标量类型 + 嵌套 + 数组 一次往返 -// ============================================================================= - -#define ALL_INNER_FIELDS(BSF) BSF##_F(std::int32_t, a) BSF##_F(double, b) - -BITSERIAL_DEFINE(AllInner, ALL_INNER_FIELDS); - -#define ALL_FIELDS(BSF) \ - BSF##_F(bool, flag1) BSF##_F(bool, flag2, 3) BSF##_F(std::uint8_t, u8) \ - BSF##_F(std::int8_t, s8) BSF##_F(std::uint16_t, u16) \ - BSF##_F(std::int16_t, s16) BSF##_F(std::uint32_t, u32) \ - BSF##_F(std::int32_t, s32) BSF##_F(std::uint64_t, u64) \ - BSF##_F(std::int64_t, s64) BSF##_F(float, f32) \ - BSF##_F(double, f64) BSF##_F(std::uint16_t, packed, 11) \ - BSF##_F(std::int32_t, spacked, 19) \ - BSF##_NEST(AllInner, inner) \ - BSF##_ARR(std::uint8_t, bytes, 4) \ - BSF##_ARR(std::int16_t, q9, 3, 9) \ - BSF##_F(std::uint8_t, tail, 6) - -BITSERIAL_DEFINE(AllPkt, ALL_FIELDS); - -TEST_CASE("comprehensive: all types combined stress test") { - AllPkt x{ - .flag1 = true, - .flag2 = true, - .u8 = 0xAB, - .s8 = -42, - .u16 = 0xBEEF, - .s16 = -32000, - .u32 = 0xDEADBEEFu, - .s32 = -123456789, - .u64 = 0x0123456789ABCDEFull, - .s64 = std::numeric_limits::min() + 1, - .f32 = -3.5f, - .f64 = 2.718281828459045, - .packed = 0x7FF, - .spacked = -262144, - .inner = {.a = -7, .b = 1.5}, - .bytes = {0x11, 0x22, 0x33, 0x44}, - .q9 = {-256, 0, 255}, - .tail = 0x2A, - }; - - auto y = bitserial::from_bytes(bitserial::to_bytes(x)); - - CHECK(y.flag1 == true); - CHECK(y.flag2 == true); - CHECK(y.u8 == 0xAB); - CHECK(y.s8 == -42); - CHECK(y.u16 == 0xBEEF); - CHECK(y.s16 == -32000); - CHECK(y.u32 == 0xDEADBEEFu); - CHECK(y.s32 == -123456789); - CHECK(y.u64 == 0x0123456789ABCDEFull); - CHECK(y.s64 == std::numeric_limits::min() + 1); - CHECK(std::bit_cast(y.f32) == - std::bit_cast(x.f32)); - CHECK(std::bit_cast(y.f64) == - std::bit_cast(x.f64)); - CHECK(y.packed == 0x7FF); - CHECK(y.spacked == -262144); - CHECK(y.inner.a == -7); - CHECK(std::bit_cast(y.inner.b) == - std::bit_cast(1.5)); - CHECK(y.bytes[0] == 0x11); - CHECK(y.bytes[3] == 0x44); - CHECK(y.q9[0] == -256); - CHECK(y.q9[2] == 255); - CHECK(y.tail == 0x2A); - - auto hex = bitserial::to_hex(x); - auto z = bitserial::from_hex(hex); - CHECK(z.u64 == x.u64); - CHECK(z.s64 == x.s64); -} - -// ============================================================================= -// 12) 用户提供 span 的零分配路径 -// ============================================================================= - -TEST_CASE("user-provided buffer: zero-allocation path") { - AllPkt x{}; - x.u8 = 0x12; - x.s32 = -1; - x.f64 = 3.14; - x.inner = {.a = 100, .b = 0.5}; - - std::vector buf(bitserial::byte_size_v); - bitserial::to_bytes(x, std::span(buf)); - - auto y = - bitserial::from_bytes(std::span(buf)); - CHECK(y.u8 == 0x12); - CHECK(y.s32 == -1); - CHECK(std::bit_cast(y.f64) == - std::bit_cast(3.14)); - CHECK(y.inner.a == 100); -} - -// ============================================================================= -// 13) constexpr 编译期序列化 -// ============================================================================= - -constexpr UnsignedPkt make_pkt() { - UnsignedPkt p{ - .a = 0x1, .b = 0x2, .c = 0x345, .d = 0x67890, .e = 0xAABBCCDDEE - }; - return p; -} -constexpr auto kBytes = bitserial::to_bytes(make_pkt()); - -static_assert(kBytes[0] == 0x12); -static_assert(kBytes[1] == 0x34); -static_assert(kBytes[2] == 0x56); -static_assert(kBytes[3] == 0x78); -static_assert(kBytes[4] == 0x90); -static_assert(kBytes[5] == 0xAA); -static_assert(kBytes[9] == 0xEE); - -TEST_CASE("constexpr compile-time serialization") { - CHECK(kBytes[0] == 0x12); - CHECK(kBytes[2] == 0x56); - CHECK(kBytes[9] == 0xEE); -} - -template -void check_bulk_pack_unpack_edges() { - for (std::size_t n = 0; n <= 257; ++n) { - const std::size_t packed_size = (n * Bits + 7) / 8; - std::vector src(n); - std::vector packed_ref(packed_size, 0); - std::vector packed_bulk(packed_size, 0); - std::vector out_ref(n); - std::vector out_bulk(n); - - for (std::size_t i = 0; i < n; ++i) { - src[i] = static_cast((i * 37 + n * 11) & ((1u << Bits) - 1u)); - } - - std::size_t bit_pos = 0; - for (std::uint8_t x : src) { - bitserial::write_bits(packed_ref, bit_pos, Bits, x); - bit_pos += Bits; - } - bitserial::pack_bits(src, packed_bulk); - CHECK(packed_bulk == packed_ref); - - bit_pos = 0; - for (std::uint8_t &x : out_ref) { - x = static_cast(bitserial::read_bits(packed_ref, bit_pos, Bits)); - bit_pos += Bits; - } - bitserial::unpack_bits(packed_ref, out_bulk); - CHECK(out_bulk == out_ref); - } -} - -TEST_CASE("bulk BAQ pack/unpack matches bit loop for edge sizes") { - check_bulk_pack_unpack_edges<3>(); - check_bulk_pack_unpack_edges<4>(); - check_bulk_pack_unpack_edges<5>(); -} +#include "catch_amalgamated.hpp" +#include +#include +#include +#include +#include +#include +#include + +// ============================================================================= +// 1) 无符号整数 + 跨字节位宽 +// ============================================================================= + +#define UINT_FIELDS(BSF) \ + BSF##_F(std::uint8_t, a, 4) BSF##_F(std::uint8_t, b, 4) \ + BSF##_F(std::uint16_t, c, 12) BSF##_F(std::uint32_t, d, 20) \ + BSF##_F(std::uint64_t, e, 40) + +BITSERIAL_DEFINE(UnsignedPkt, UINT_FIELDS); + +TEST_CASE("unsigned integers with cross-byte bit widths") { + static_assert(bitserial::bit_size_v == 4 + 4 + 12 + 20 + 40); + static_assert( + bitserial::byte_size_v == (4 + 4 + 12 + 20 + 40 + 7) / 8 + ); + + UnsignedPkt x{ + .a = 0xA, .b = 0x5, .c = 0xABC, .d = 0xFEDCB, .e = 0x1122334455ull + }; + + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + + CHECK(y.a == 0xA); + CHECK(y.b == 0x5); + CHECK(y.c == 0xABC); + CHECK(y.d == 0xFEDCB); + CHECK(y.e == 0x1122334455ull); + + UnsignedPkt overflow{ + .a = 0xFF, // truncated to 0xF + .b = 0xFF, // 0xF + .c = 0xFFFF, // 0xFFF + .d = 0xFFFFFFFFu, // 0xFFFFF + .e = ~0ull, + }; + auto y2 = bitserial::from_bytes(bitserial::to_bytes(overflow)); + CHECK(y2.a == 0xF); + CHECK(y2.b == 0xF); + CHECK(y2.c == 0xFFF); + CHECK(y2.d == 0xFFFFFu); + CHECK(y2.e == (std::uint64_t{1} << 40) - 1); +} + +// ============================================================================= +// 2) 有符号整数:正、负、边界、位宽截取与符号扩展 +// ============================================================================= + +#define INT_FIELDS(BSF) \ + BSF##_F(std::int8_t, i8) BSF##_F(std::int16_t, i16) \ + BSF##_F(std::int32_t, i32) BSF##_F(std::int64_t, i64) \ + BSF##_F(std::int16_t, small, 10) /* -512..511 */ \ + BSF##_F(std::int32_t, mid, 20) /* -524288..524287 */ \ + BSF##_F(std::int64_t, big, 33) /* crosses 4 bytes */ + +BITSERIAL_DEFINE(SignedPkt, INT_FIELDS); + +TEST_CASE("signed integers: positive values") { + SignedPkt x{ + .i8 = 0x12, + .i16 = 0x1234, + .i32 = 0x12345678, + .i64 = 0x1122334455667788ll, + .small = 100, + .mid = 12345, + .big = 123456789ll, + }; + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + CHECK(y.i8 == 0x12); + CHECK(y.i16 == 0x1234); + CHECK(y.i32 == 0x12345678); + CHECK(y.i64 == 0x1122334455667788ll); + CHECK(y.small == 100); + CHECK(y.mid == 12345); + CHECK(y.big == 123456789ll); +} + +TEST_CASE("signed integers: negative values") { + SignedPkt x{ + .i8 = -1, + .i16 = -2, + .i32 = -3, + .i64 = -4, + .small = -1, + .mid = -1, + .big = -1, + }; + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + CHECK(y.i8 == -1); + CHECK(y.i16 == -2); + CHECK(y.i32 == -3); + CHECK(y.i64 == -4); + CHECK(y.small == -1); + CHECK(y.mid == -1); + CHECK(y.big == -1); +} + +TEST_CASE("signed integers: boundary values") { + using L8 = std::numeric_limits; + using L16 = std::numeric_limits; + using L32 = std::numeric_limits; + using L64 = std::numeric_limits; + + SignedPkt x_min{ + .i8 = L8::min(), + .i16 = L16::min(), + .i32 = L32::min(), + .i64 = L64::min(), + .small = -512, + .mid = -524288, + .big = -(1ll << 32), + }; + auto y = bitserial::from_bytes(bitserial::to_bytes(x_min)); + CHECK(y.i8 == L8::min()); + CHECK(y.i16 == L16::min()); + CHECK(y.i32 == L32::min()); + CHECK(y.i64 == L64::min()); + CHECK(y.small == -512); + CHECK(y.mid == -524288); + CHECK(y.big == -(1ll << 32)); + + SignedPkt x_max{ + .i8 = L8::max(), + .i16 = L16::max(), + .i32 = L32::max(), + .i64 = L64::max(), + .small = 511, + .mid = 524287, + .big = (1ll << 32) - 1, + }; + auto y2 = bitserial::from_bytes(bitserial::to_bytes(x_max)); + CHECK(y2.i8 == L8::max()); + CHECK(y2.i16 == L16::max()); + CHECK(y2.i32 == L32::max()); + CHECK(y2.i64 == L64::max()); + CHECK(y2.small == 511); + CHECK(y2.mid == 524287); + CHECK(y2.big == (1ll << 32) - 1); +} + +// ============================================================================= +// 3) bool:单 bit 与多 bit +// ============================================================================= + +#define BOOL_FIELDS(BSF) \ + BSF##_F(bool, a) BSF##_F(bool, b) BSF##_F(bool, c, 4) BSF##_F(bool, d, 8) \ + BSF##_F(std::uint8_t, pad, 2) + +BITSERIAL_DEFINE(BoolPkt, BOOL_FIELDS); + +TEST_CASE("bool fields: single and multi-bit") { + static_assert(bitserial::byte_size_v == 2); + + BoolPkt x{.a = true, .b = false, .c = true, .d = true, .pad = 3}; + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + CHECK(y.a == true); + CHECK(y.b == false); + CHECK(y.c == true); + CHECK(y.d == true); + CHECK(y.pad == 3); + + BoolPkt z{.a = false, .b = false, .c = false, .d = false, .pad = 0}; + auto z2 = bitserial::from_bytes(bitserial::to_bytes(z)); + CHECK(z2.a == false); + CHECK(z2.d == false); +} + +// ============================================================================= +// 4) float / double:含特殊值 +// ============================================================================= + +#define FLOAT_FIELDS(BSF) \ + BSF##_F(float, f1) BSF##_F(float, f2) BSF##_F(double, d1) BSF##_F(double, d2) + +BITSERIAL_DEFINE(FloatPkt, FLOAT_FIELDS); + +TEST_CASE("float and double: basic roundtrip") { + static_assert(bitserial::byte_size_v == 4 + 4 + 8 + 8); + + FloatPkt x{ + .f1 = 3.14159265f, + .f2 = -2.71828f, + .d1 = 1.41421356237309504, + .d2 = -1e-300, + }; + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + CHECK( + std::bit_cast(y.f1) == std::bit_cast(x.f1) + ); + CHECK( + std::bit_cast(y.f2) == std::bit_cast(x.f2) + ); + CHECK( + std::bit_cast(y.d1) == std::bit_cast(x.d1) + ); + CHECK( + std::bit_cast(y.d2) == std::bit_cast(x.d2) + ); +} + +TEST_CASE("float and double: special values (inf, nan, -0, subnormal)") { + const float pinf = std::numeric_limits::infinity(); + const float ninf = -pinf; + const float qnan = std::numeric_limits::quiet_NaN(); + const double pinfd = std::numeric_limits::infinity(); + const double mzero = -0.0; + const float sub = std::numeric_limits::denorm_min(); + + FloatPkt x{.f1 = pinf, .f2 = ninf, .d1 = pinfd, .d2 = mzero}; + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + CHECK((std::isinf(y.f1) && y.f1 > 0)); + CHECK((std::isinf(y.f2) && y.f2 < 0)); + CHECK(std::isinf(y.d1)); + CHECK( + std::bit_cast(y.d2) == std::bit_cast(mzero) + ); + + FloatPkt z{.f1 = qnan, .f2 = sub, .d1 = 0.0, .d2 = 0.0}; + auto z2 = bitserial::from_bytes(bitserial::to_bytes(z)); + CHECK(std::isnan(z2.f1)); + CHECK( + std::bit_cast(z2.f2) == std::bit_cast(sub) + ); +} + +// ============================================================================= +// 5) 嵌套结构体 +// ============================================================================= + +#define INNER_FIELDS(BSF) \ + BSF##_F(std::uint8_t, tag, 4) BSF##_F(std::uint16_t, val, 12) + +BITSERIAL_DEFINE(Inner, INNER_FIELDS); + +#define OUTER_FIELDS(BSF) \ + BSF##_F(std::uint8_t, hdr) BSF##_NEST(Inner, a) BSF##_NEST(Inner, b) \ + BSF##_F(std::uint8_t, ftr) + +BITSERIAL_DEFINE(Outer, OUTER_FIELDS); + +TEST_CASE("nested structs") { + static_assert(bitserial::bit_size_v == 16); + static_assert(bitserial::bit_size_v == 8 + 16 + 16 + 8); + + Outer x{ + .hdr = 0xAB, + .a = {.tag = 0x3, .val = 0x123}, + .b = {.tag = 0xC, .val = 0xDEF}, + .ftr = 0xCD, + }; + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + CHECK(y.hdr == 0xAB); + CHECK(y.a.tag == 0x3); + CHECK(y.a.val == 0x123); + CHECK(y.b.tag == 0xC); + CHECK(y.b.val == 0xDEF); + CHECK(y.ftr == 0xCD); +} + +// ============================================================================= +// 6) 定长数组(自然位宽 / 自定义位宽) +// ============================================================================= + +#define ARR_NATURAL_FIELDS(BSF) \ + BSF##_ARR(std::uint8_t, bytes6, 6) BSF##_ARR(std::uint16_t, words3, 3) + +BITSERIAL_DEFINE(ArrNat, ARR_NATURAL_FIELDS); + +#define ARR_PACKED_FIELDS(BSF) \ + BSF##_ARR(std::uint16_t, q12, 5, 12) /* 5 x 12 bits = 60 bits */ \ + BSF##_ARR(std::int16_t, s10, 4, 10) /* 4 x 10 bits signed = 40 bits */ \ + BSF##_F(std::uint8_t, pad, 4) + +BITSERIAL_DEFINE(ArrPacked, ARR_PACKED_FIELDS); + +TEST_CASE("arrays: natural bit widths") { + static_assert(bitserial::byte_size_v == 6 + 6); + + ArrNat x{}; + for (int i = 0; i < 6; ++i) + x.bytes6[i] = static_cast(i + 1); + x.words3[0] = 0x1111; + x.words3[1] = 0x2222; + x.words3[2] = 0x3333; + + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + for (int i = 0; i < 6; ++i) + CHECK(y.bytes6[i] == i + 1); + CHECK(y.words3[0] == 0x1111); + CHECK(y.words3[1] == 0x2222); + CHECK(y.words3[2] == 0x3333); +} + +TEST_CASE("arrays: packed with custom bit widths") { + static_assert(bitserial::bit_size_v == 60 + 40 + 4); + + ArrPacked x{}; + x.q12[0] = 0xABC; + x.q12[1] = 0x123; + x.q12[2] = 0xFFF; + x.q12[3] = 0x000; + x.q12[4] = 0x555; + x.s10[0] = -1; + x.s10[1] = 511; + x.s10[2] = -512; + x.s10[3] = 0; + x.pad = 0xA; + + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + CHECK(y.q12[0] == 0xABC); + CHECK(y.q12[1] == 0x123); + CHECK(y.q12[2] == 0xFFF); + CHECK(y.q12[3] == 0x000); + CHECK(y.q12[4] == 0x555); + CHECK(y.s10[0] == -1); + CHECK(y.s10[1] == 511); + CHECK(y.s10[2] == -512); + CHECK(y.s10[3] == 0); + CHECK(y.pad == 0xA); +} + +// ============================================================================= +// 7) HEX 与 bytes 双向转换 +// ============================================================================= + +TEST_CASE("hex roundtrip: upper and lowercase") { + UnsignedPkt x{ + .a = 0xA, .b = 0x5, .c = 0xABC, .d = 0xFEDCB, .e = 0xCAFEBABEFEull + }; + + auto hex_upper = bitserial::to_hex(x, /*upper=*/true); + auto hex_lower = bitserial::to_hex(x, /*upper=*/false); + + CHECK(hex_upper.size() == bitserial::byte_size_v * 2); + CHECK(hex_lower.size() == bitserial::byte_size_v * 2); + + auto y1 = bitserial::from_hex(hex_upper); + auto y2 = bitserial::from_hex(hex_lower); + CHECK(y1.a == x.a); + CHECK(y1.e == x.e); + CHECK(y2.c == x.c); + CHECK(y2.d == x.d); +} + +// ============================================================================= +// 8) 字节序:手工验证 MSB-first 的位排布 +// ============================================================================= + +TEST_CASE("byte order: MSB-first layout verification") { + UnsignedPkt x{ + .a = 0xA, + .b = 0x5, + .c = 0xABC, + .d = 0xFEDCB, + .e = 0x1122334455ull, + }; + auto buf = bitserial::to_bytes(x); + + CHECK(buf[0] == 0xA5); + CHECK(buf[1] == 0xAB); + CHECK(buf[2] == 0xCF); + CHECK(buf[3] == 0xED); + CHECK(buf[4] == 0xCB); + CHECK(buf[5] == 0x11); + CHECK(buf[6] == 0x22); + CHECK(buf[7] == 0x33); + CHECK(buf[8] == 0x44); + CHECK(buf[9] == 0x55); +} + +// ============================================================================= +// 9) 边界与异常 +// ============================================================================= + +TEST_CASE("error handling: buffer too small") { + UnsignedPkt x{}; + std::array - 1> small{}; + + CHECK_THROWS_AS( + bitserial::to_bytes(x, std::span(small)), std::out_of_range + ); + CHECK_THROWS_AS( + bitserial::from_bytes(std::span(small)), + std::out_of_range + ); +} + +TEST_CASE("error handling: hex parsing errors") { + CHECK_THROWS_AS( + bitserial::from_hex("DEAD"), std::invalid_argument + ); + + std::string bad(bitserial::byte_size_v * 2, 'X'); + CHECK_THROWS_AS(bitserial::from_hex(bad), std::invalid_argument); +} + +// ============================================================================= +// 10) 真实协议示例:IPv4 头部前 12 字节 +// ============================================================================= + +#define IPV4_FIELDS(BSF) \ + BSF##_F(std::uint8_t, version, 4) BSF##_F(std::uint8_t, ihl, 4) \ + BSF##_F(std::uint8_t, tos) BSF##_F(std::uint16_t, total_len) \ + BSF##_F(std::uint16_t, id) BSF##_F(std::uint8_t, flags, 3) \ + BSF##_F(std::uint16_t, frag_off, 13) BSF##_F(std::uint8_t, ttl) \ + BSF##_F(std::uint8_t, proto) \ + BSF##_F(std::uint16_t, checksum) + +BITSERIAL_DEFINE(IPv4Head, IPV4_FIELDS); + +TEST_CASE("real protocol: IPv4 header layout") { + static_assert(bitserial::byte_size_v == 12); + + IPv4Head h{ + .version = 4, + .ihl = 5, + .tos = 0, + .total_len = 0x0073, + .id = 0x1234, + .flags = 0b010, + .frag_off = 0, + .ttl = 64, + .proto = 17, + .checksum = 0xB861, + }; + + const auto buf = bitserial::to_bytes(h); + + const std::uint8_t expect[] = { + 0x45, 0x00, 0x00, 0x73, 0x12, 0x34, 0x40, 0x00, 0x40, 0x11, 0xB8, 0x61, + }; + for (std::size_t i = 0; i < sizeof(expect); ++i) + CHECK(buf[i] == expect[i]); + + CHECK(bitserial::to_hex(h) == "45000073123440004011B861"); + auto h2 = bitserial::from_hex("45000073123440004011B861"); + CHECK(h2.version == 4); + CHECK(h2.ihl == 5); + CHECK(h2.flags == 0b010); + CHECK(h2.frag_off == 0); + CHECK(h2.ttl == 64); + CHECK(h2.proto == 17); + CHECK(h2.checksum == 0xB861); +} + +// ============================================================================= +// 11) 综合压力:所有标量类型 + 嵌套 + 数组 一次往返 +// ============================================================================= + +#define ALL_INNER_FIELDS(BSF) BSF##_F(std::int32_t, a) BSF##_F(double, b) + +BITSERIAL_DEFINE(AllInner, ALL_INNER_FIELDS); + +#define ALL_FIELDS(BSF) \ + BSF##_F(bool, flag1) BSF##_F(bool, flag2, 3) BSF##_F(std::uint8_t, u8) \ + BSF##_F(std::int8_t, s8) BSF##_F(std::uint16_t, u16) \ + BSF##_F(std::int16_t, s16) BSF##_F(std::uint32_t, u32) \ + BSF##_F(std::int32_t, s32) BSF##_F(std::uint64_t, u64) \ + BSF##_F(std::int64_t, s64) BSF##_F(float, f32) \ + BSF##_F(double, f64) BSF##_F(std::uint16_t, packed, 11) \ + BSF##_F(std::int32_t, spacked, 19) \ + BSF##_NEST(AllInner, inner) \ + BSF##_ARR(std::uint8_t, bytes, 4) \ + BSF##_ARR(std::int16_t, q9, 3, 9) \ + BSF##_F(std::uint8_t, tail, 6) + +BITSERIAL_DEFINE(AllPkt, ALL_FIELDS); + +TEST_CASE("comprehensive: all types combined stress test") { + AllPkt x{ + .flag1 = true, + .flag2 = true, + .u8 = 0xAB, + .s8 = -42, + .u16 = 0xBEEF, + .s16 = -32000, + .u32 = 0xDEADBEEFu, + .s32 = -123456789, + .u64 = 0x0123456789ABCDEFull, + .s64 = std::numeric_limits::min() + 1, + .f32 = -3.5f, + .f64 = 2.718281828459045, + .packed = 0x7FF, + .spacked = -262144, + .inner = {.a = -7, .b = 1.5}, + .bytes = {0x11, 0x22, 0x33, 0x44}, + .q9 = {-256, 0, 255}, + .tail = 0x2A, + }; + + auto y = bitserial::from_bytes(bitserial::to_bytes(x)); + + CHECK(y.flag1 == true); + CHECK(y.flag2 == true); + CHECK(y.u8 == 0xAB); + CHECK(y.s8 == -42); + CHECK(y.u16 == 0xBEEF); + CHECK(y.s16 == -32000); + CHECK(y.u32 == 0xDEADBEEFu); + CHECK(y.s32 == -123456789); + CHECK(y.u64 == 0x0123456789ABCDEFull); + CHECK(y.s64 == std::numeric_limits::min() + 1); + CHECK( + std::bit_cast(y.f32) == std::bit_cast(x.f32) + ); + CHECK( + std::bit_cast(y.f64) == std::bit_cast(x.f64) + ); + CHECK(y.packed == 0x7FF); + CHECK(y.spacked == -262144); + CHECK(y.inner.a == -7); + CHECK( + std::bit_cast(y.inner.b) == + std::bit_cast(1.5) + ); + CHECK(y.bytes[0] == 0x11); + CHECK(y.bytes[3] == 0x44); + CHECK(y.q9[0] == -256); + CHECK(y.q9[2] == 255); + CHECK(y.tail == 0x2A); + + auto hex = bitserial::to_hex(x); + auto z = bitserial::from_hex(hex); + CHECK(z.u64 == x.u64); + CHECK(z.s64 == x.s64); +} + +// ============================================================================= +// 12) 用户提供 span 的零分配路径 +// ============================================================================= + +TEST_CASE("user-provided buffer: zero-allocation path") { + AllPkt x{}; + x.u8 = 0x12; + x.s32 = -1; + x.f64 = 3.14; + x.inner = {.a = 100, .b = 0.5}; + + std::vector buf(bitserial::byte_size_v); + bitserial::to_bytes(x, std::span(buf)); + + auto y = bitserial::from_bytes(std::span(buf)); + CHECK(y.u8 == 0x12); + CHECK(y.s32 == -1); + CHECK( + std::bit_cast(y.f64) == std::bit_cast(3.14) + ); + CHECK(y.inner.a == 100); +} + +// ============================================================================= +// 13) constexpr 编译期序列化 +// ============================================================================= + +constexpr UnsignedPkt make_pkt() { + UnsignedPkt p{ + .a = 0x1, .b = 0x2, .c = 0x345, .d = 0x67890, .e = 0xAABBCCDDEE + }; + return p; +} +constexpr auto kBytes = bitserial::to_bytes(make_pkt()); + +static_assert(kBytes[0] == 0x12); +static_assert(kBytes[1] == 0x34); +static_assert(kBytes[2] == 0x56); +static_assert(kBytes[3] == 0x78); +static_assert(kBytes[4] == 0x90); +static_assert(kBytes[5] == 0xAA); +static_assert(kBytes[9] == 0xEE); + +TEST_CASE("constexpr compile-time serialization") { + CHECK(kBytes[0] == 0x12); + CHECK(kBytes[2] == 0x56); + CHECK(kBytes[9] == 0xEE); +} + +template void check_bulk_pack_unpack_edges() { + for (std::size_t n = 0; n <= 257; ++n) { + const std::size_t packed_size = (n * Bits + 7) / 8; + std::vector src(n); + std::vector packed_ref(packed_size, 0); + std::vector packed_bulk(packed_size, 0); + std::vector out_ref(n); + std::vector out_bulk(n); + + for (std::size_t i = 0; i < n; ++i) { + src[i] = + static_cast((i * 37 + n * 11) & ((1u << Bits) - 1u)); + } + + std::size_t bit_pos = 0; + for (std::uint8_t x : src) { + bitserial::write_bits(packed_ref, bit_pos, Bits, x); + bit_pos += Bits; + } + bitserial::pack_bits(src, packed_bulk); + CHECK(packed_bulk == packed_ref); + + bit_pos = 0; + for (std::uint8_t &x : out_ref) { + x = static_cast( + bitserial::read_bits(packed_ref, bit_pos, Bits) + ); + bit_pos += Bits; + } + bitserial::unpack_bits(packed_ref, out_bulk); + CHECK(out_bulk == out_ref); + } +} + +TEST_CASE("bulk BAQ pack/unpack matches bit loop for edge sizes") { + check_bulk_pack_unpack_edges<3>(); + check_bulk_pack_unpack_edges<4>(); + check_bulk_pack_unpack_edges<5>(); +}