From f216ddd59ffd20125f0749418f818e20786e017d Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:12:13 +0200 Subject: [PATCH 01/64] refactor(internet): name internet_state{} in internet_compute, as adler32 does --- src/include/checksum/internet.hpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/include/checksum/internet.hpp b/src/include/checksum/internet.hpp index 165b8ee..55a194e 100644 --- a/src/include/checksum/internet.hpp +++ b/src/include/checksum/internet.hpp @@ -39,10 +39,10 @@ template [[nodiscard]] constexpr internet_state internet_upda /// The checksum of state: the one's complement of the sum, a last odd byte padded with zero. Store it most significant byte first. [[nodiscard]] constexpr std::uint16_t internet_finalize(internet_state state) noexcept; -/// internet_finalize(internet_update({}, data)). +/// internet_finalize(internet_update(internet_state{}, data)). [[nodiscard]] constexpr std::uint16_t internet_compute(std::span data) noexcept; -/// internet_finalize(internet_update({}, data)) for a byte range. +/// internet_finalize(internet_update(internet_state{}, data)) for a byte range. template [[nodiscard]] constexpr std::uint16_t internet_compute(Range &&data) noexcept; } // namespace checksum @@ -111,10 +111,12 @@ template constexpr internet_state internet_update(internet_st constexpr std::uint16_t internet_finalize(internet_state state) noexcept { return static_cast(~state.sum); } -constexpr std::uint16_t internet_compute(std::span data) noexcept { return internet_finalize(internet_update({}, data)); } +constexpr std::uint16_t internet_compute(std::span data) noexcept { + return internet_finalize(internet_update(internet_state{}, data)); +} template constexpr std::uint16_t internet_compute(Range &&data) noexcept { - return internet_finalize(internet_update({}, std::forward(data))); + return internet_finalize(internet_update(internet_state{}, std::forward(data))); } } // namespace checksum From 5d4095ac9e9b274bcaf17ce6b984febef57f48d1 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:12:13 +0200 Subject: [PATCH 02/64] test(internet): rename the test file to ut_internet.cpp, like the other algorithms --- tests/unit_tests/CMakeLists.txt | 2 +- tests/unit_tests/{ut_internet_checksum.cpp => ut_internet.cpp} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename tests/unit_tests/{ut_internet_checksum.cpp => ut_internet.cpp} (100%) diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt index 9828804..3ac1533 100644 --- a/tests/unit_tests/CMakeLists.txt +++ b/tests/unit_tests/CMakeLists.txt @@ -14,7 +14,7 @@ target_sources( ut_crc_vectors.cpp ut_fletcher.cpp ut_fletcher4.cpp - ut_internet_checksum.cpp + ut_internet.cpp ut_murmur3.cpp ut_xxh3.cpp ut_xxhash.cpp diff --git a/tests/unit_tests/ut_internet_checksum.cpp b/tests/unit_tests/ut_internet.cpp similarity index 100% rename from tests/unit_tests/ut_internet_checksum.cpp rename to tests/unit_tests/ut_internet.cpp From 0a86e00609c5f6973f6132d801e6c3788cc8c66d Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:12:13 +0200 Subject: [PATCH 03/64] docs(internet): definition section, fixed quick start, examples --- doc/design/acceleration.md | 2 +- doc/internet.md | 34 +++++++++++++++++++++------------- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index a0e565e..5ff25a2 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -1,7 +1,7 @@ # CPU acceleration How algorithms use CPU instructions and which architectures are worth it, per algorithm. Measured figures are in the -user guides ([CRC](../crc.md#8-performance), [Internet checksum](../internet.md#5-performance), +user guides ([CRC](../crc.md#8-performance), [Internet checksum](../internet.md#6-performance), [Fletcher](../fletcher.md#6-performance), [Adler-32](../adler32.md#6-performance), [MurmurHash3](../murmur3.md#5-performance), [xxHash](../xxhash.md#5-performance), [fletcher4](../fletcher4.md#6-performance)). diff --git a/doc/internet.md b/doc/internet.md index 59a9555..45e9147 100644 --- a/doc/internet.md +++ b/doc/internet.md @@ -13,7 +13,7 @@ allocates no memory and has no global state. #include // One call. The result goes into the packet most significant byte first. -std::uint16_t value = checksum::internet_compute(std::span(ipv4_header)); +std::uint16_t value = checksum::internet_compute(std::span(header)); header[10] = std::byte(value >> 8); header[11] = std::byte(value & 0xFF); @@ -28,7 +28,16 @@ std::uint16_t udp_checksum = checksum::internet_finalize(state); static_assert(checksum::internet_compute(std::string_view("123456789")) == 0xF62A); ``` -## 2. API +`examples/internet` has complete programs: an IPv4 header checksum filled in and verified, a UDP checksum summed from +the pseudo-header, the header and the payload, and the RFC 1624 update of a header after a TTL decrement. + +## 2. Definition + +The message is read as 16-bit big-endian words, a last odd byte padded with a zero byte. The words are added in one's +complement arithmetic, each carry out of bit 15 added back into bit 0, and the checksum is the one's complement +(bitwise NOT) of that sum. + +## 3. API | Name | What it does | | --- | --- | @@ -38,17 +47,16 @@ static_assert(checksum::internet_compute(std::string_view("123456789")) == 0xF62 | `internet_compute(data)` | `internet_finalize(internet_update({}, data))`. | All functions are `constexpr` and `noexcept`. `data` is a `std::span` or any range of `std::byte`, -`char`, `unsigned char`, `signed char` or `char8_t`, the same as for the CRC engines. Contiguous ranges are passed +`char`, `unsigned char`, `signed char` or `char8_t`, as for the other algorithms. Contiguous ranges are passed on as one span and other ranges in 64-byte chunks. Arrays of `char` are rejected, so the `'\0'` of a string literal is never summed: pass text as `std::string_view`. Every `internet_state` value is valid, so nothing has preconditions. -## 3. Behavior +## 4. Behavior - **Splits:** a message may be split anywhere, including inside a 16-bit word. `odd` records that the next byte is the low byte of a word, and the result is the same as for one call. -- **Odd length:** a last odd byte is padded with a zero byte, as RFC 1071 specifies. - **Zero:** the sum is 0 only if every byte is 0. Otherwise a sum that is a multiple of 0xFFFF is 0xFFFF, so: - the empty message and an all-zero message give 0xFFFF; - a message that already contains its correct checksum gives 0. @@ -57,7 +65,7 @@ Every `internet_state` value is valid, so nothing has preconditions. - **Byte order:** the result is a number; write it into the packet most significant byte first. The library reads the message the same way on little- and big-endian targets. -## 4. CPU acceleration +## 5. CPU acceleration The portable loop adds the widest native word (`std::size_t`) with two independent carry chains. It runs at every optimization level, and its result does not depend on the target's byte order. The order in which bytes are added @@ -77,11 +85,11 @@ Cortex-M3/M4/M7/M33 builds get their kernel from their usual `-march` or `-mcpu` byte-by-byte loop with the same result. Which other architectures are worth a kernel is discussed in [design/acceleration.md](design/acceleration.md). -## 5. Performance +## 6. Performance All figures are in MB/s (10⁶ bytes per second) and are medians of 5 runs of `checksum_bench_internet` on one core. -### 5.1 x86-64: Core Ultra 7 155H, `-O2` +### 6.1 x86-64: Core Ultra 7 155H, `-O2` AVX2 is with `-march=native`; portable is with `CHECKSUM_ACCELERATION=OFF` and default flags. @@ -97,7 +105,7 @@ AVX2 is with `-march=native`; portable is with `CHECKSUM_ACCELERATION=OFF` and d Below 512 bytes both builds run the portable loop; the differences come from `-march=native` and code layout. From 1500 bytes the AVX2 kernel is 1.6-1.8× faster. At 1 MiB the gain is smaller, because the data comes from the L2 cache. -### 5.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz +### 6.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz GCC 14.3, `-O2`, static binaries on one core. Portable is with `CHECKSUM_ACCELERATION=OFF`. In 32-bit mode, NEON is `-march=armv8-a+crc -mfpu=neon-fp-armv8`, and `ldm` is `-mfpu=vfpv3-d16` (no NEON). @@ -115,7 +123,7 @@ The 64-bit portable loop is already fast, so the NEON kernel starts at 512 bytes bytes. In 32-bit mode the kernels start at 192 bytes: NEON is 4.1× and `ldm` 2.0× faster at 4 KiB. Below the thresholds every build runs the portable loop, and the differences there come from code layout. -### 5.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz +### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz GCC 14.3, `-O2`, code in flash and data in RAM; the cycle counter gives the best of 5 calls. Offset is the start address modulo 4: 2 is typical for an IP header behind a 14-byte Ethernet header. @@ -135,7 +143,7 @@ and up to 2.5× from odd or 2-modulo-4 addresses, where the portable loop's unal same cycles per byte, so the figures scale with the clock. Below 192 bytes the build with the kernel is up to 5 % slower. -### 5.4 Code size +### 6.4 Code size `sum_loop` and its helpers, the whole run-time code, GCC with `-ffunction-sections`. A kernel build holds the portable loop twice: once for short inputs, once after the kernel. @@ -150,11 +158,11 @@ loop twice: once for short inputs, once after the kernel. RISC-V has not been measured on hardware; the vector kernel is tested in QEMU with vector lengths of 128-1024 bits. -## 6. Limitations +## 7. Limitations - **No in-place update helper:** RFC 1624 updates a checksum after one 16-bit-aligned field changes. The public API already does it: start from `internet_state{.sum = static_cast(~old_checksum)}`, fold the bitwise - complement of the old field, then the new field, and finalize. + complement of the old field, then the new field, and finalize, as `examples/internet/ttl_decrement.cpp` does. - **UDP zero:** the UDP rule of sending 0xFFFF instead of a computed 0 is protocol logic and stays in the caller. - **No verification helper:** to verify a packet, compute over it, checksum included, and compare the result with 0. - **Code size:** a build with a kernel adds 290-810 bytes; `CHECKSUM_ACCELERATION=OFF` keeps the portable loop alone. From 5fb6e8dffa0d31b649110c58f9109732de93dcea Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:12:13 +0200 Subject: [PATCH 04/64] examples(internet): IPv4 header, UDP datagram and TTL decrement --- .cspell.yml | 1 + examples/CMakeLists.txt | 1 + examples/internet/CMakeLists.txt | 4 ++ examples/internet/ipv4_header.cpp | 42 ++++++++++++++++++++ examples/internet/ttl_decrement.cpp | 44 +++++++++++++++++++++ examples/internet/udp_datagram.cpp | 59 +++++++++++++++++++++++++++++ 6 files changed, 151 insertions(+) create mode 100644 examples/internet/CMakeLists.txt create mode 100644 examples/internet/ipv4_header.cpp create mode 100644 examples/internet/ttl_decrement.cpp create mode 100644 examples/internet/udp_datagram.cpp diff --git a/.cspell.yml b/.cspell.yml index 407e540..10ba650 100644 --- a/.cspell.yml +++ b/.cspell.yml @@ -68,6 +68,7 @@ words: - cvtsi - cxxflags - darc +- datagram - dect - dtcm - eabi diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 09303dd..2a2bc3b 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1 +1,2 @@ add_subdirectory(crc) +add_subdirectory(internet) diff --git a/examples/internet/CMakeLists.txt b/examples/internet/CMakeLists.txt new file mode 100644 index 0000000..1810840 --- /dev/null +++ b/examples/internet/CMakeLists.txt @@ -0,0 +1,4 @@ +foreach (example ipv4_header udp_datagram ttl_decrement) + add_executable(checksum_example_internet_${example} ${example}.cpp) + target_link_libraries(checksum_example_internet_${example} PRIVATE checksum::checksum) +endforeach () diff --git a/examples/internet/ipv4_header.cpp b/examples/internet/ipv4_header.cpp new file mode 100644 index 0000000..73e8502 --- /dev/null +++ b/examples/internet/ipv4_header.cpp @@ -0,0 +1,42 @@ +// Fills in the checksum of an IPv4 header and verifies a received one. +// A header that holds its correct checksum sums to 0. + +#include + +#include +#include +#include +#include +#include + +namespace { + +// The checksum field is bytes 10 and 11, most significant byte first; it is zero while the checksum is computed. +void fill_checksum(std::span header) { + header[10] = std::byte{0}; + header[11] = std::byte{0}; + std::uint16_t const value = checksum::internet_compute(std::span{header}); + header[10] = static_cast(value >> 8U); + header[11] = static_cast(value & 0xFFU); +} + +bool is_valid(std::span header) { return checksum::internet_compute(header) == 0; } + +} // namespace + +int main() { + // Version 4, total length 0x73, TTL 64, UDP, 192.168.0.1 to 192.168.0.199. + std::array header{std::byte{0x45}, std::byte{0x00}, std::byte{0x00}, std::byte{0x73}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x40}, std::byte{0x00}, std::byte{0x40}, std::byte{0x11}, + std::byte{0x00}, std::byte{0x00}, std::byte{0xC0}, std::byte{0xA8}, std::byte{0x00}, + std::byte{0x01}, std::byte{0xC0}, std::byte{0xA8}, std::byte{0x00}, std::byte{0xC7}}; + fill_checksum(header); + auto const value = static_cast((std::to_integer(header[10]) << 8U) | std::to_integer(header[11])); + std::println("IPv4 header checksum = 0x{:04X}", value); + + bool const intact = is_valid(header); + header[15] ^= std::byte{0x01}; // a transmission error in the source address + bool const corrupted = is_valid(header); + std::println("intact header valid: {}, corrupted header valid: {}", intact ? "yes" : "no", corrupted ? "yes" : "no"); + return value == 0xB861 && intact && !corrupted ? 0 : 1; +} diff --git a/examples/internet/ttl_decrement.cpp b/examples/internet/ttl_decrement.cpp new file mode 100644 index 0000000..8cc28ff --- /dev/null +++ b/examples/internet/ttl_decrement.cpp @@ -0,0 +1,44 @@ +// A router decrements the TTL of an IPv4 header and updates its checksum without summing the header again (RFC 1624). +// The update starts from the complemented old checksum, folds the complemented old field, then the new field. + +#include + +#include +#include +#include +#include +#include + +namespace { + +// Bytes 8 and 9 (TTL and protocol) are the 16-bit field that changes; the checksum is bytes 10 and 11. +void decrement_ttl(std::span header) { + std::array const old_field{~header[8], ~header[9]}; + auto const old_checksum = static_cast((std::to_integer(header[10]) << 8U) | std::to_integer(header[11])); + header[8] = static_cast(std::to_integer(header[8]) - 1U); + + checksum::internet_state state{.sum = static_cast(~old_checksum)}; + state = checksum::internet_update(state, old_field); + state = checksum::internet_update(state, header.subspan<8, 2>()); + std::uint16_t const value = checksum::internet_finalize(state); + header[10] = static_cast(value >> 8U); + header[11] = static_cast(value & 0xFFU); +} + +} // namespace + +int main() { + // TTL 64, UDP, 192.168.0.1 to 192.168.0.199, checksum 0xB861. + std::array header{std::byte{0x45}, std::byte{0x00}, std::byte{0x00}, std::byte{0x73}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x40}, std::byte{0x00}, std::byte{0x40}, std::byte{0x11}, + std::byte{0xB8}, std::byte{0x61}, std::byte{0xC0}, std::byte{0xA8}, std::byte{0x00}, + std::byte{0x01}, std::byte{0xC0}, std::byte{0xA8}, std::byte{0x00}, std::byte{0xC7}}; + decrement_ttl(header); + std::println("TTL {}, checksum 0x{:02X}{:02X}", std::to_integer(header[8]), std::to_integer(header[10]), + std::to_integer(header[11])); + + // The updated header still sums to 0, and its checksum 0xB961 is what summing the whole header gives. + bool const valid = checksum::internet_compute(std::span{header}) == 0; + std::println("updated header valid: {}", valid ? "yes" : "no"); + return valid && header[10] == std::byte{0xB9} && header[11] == std::byte{0x61} ? 0 : 1; +} diff --git a/examples/internet/udp_datagram.cpp b/examples/internet/udp_datagram.cpp new file mode 100644 index 0000000..e12d127 --- /dev/null +++ b/examples/internet/udp_datagram.cpp @@ -0,0 +1,59 @@ +// Computes the checksum of a UDP datagram over IPv4 from its pieces: the pseudo-header, the UDP header and the payload. +// The pieces are never copied into one buffer, and the payload may have an odd length. + +#include + +#include +#include +#include +#include +#include + +using namespace std::literals; + +namespace { + +constexpr std::array source{std::byte{192}, std::byte{168}, std::byte{0}, std::byte{1}}; +constexpr std::array destination{std::byte{192}, std::byte{168}, std::byte{0}, std::byte{199}}; +constexpr std::uint16_t protocol_udp = 17; +constexpr std::uint16_t source_port = 1234; +constexpr std::uint16_t destination_port = 53; +constexpr std::string_view payload = "hello, checksum"sv; +constexpr auto udp_length = static_cast(8 + payload.size()); + +constexpr std::array big_endian(std::uint16_t value) { + return {static_cast(value >> 8U), static_cast(value & 0xFFU)}; +} + +// The checksum over the pseudo-header, the UDP header with checksum_field and the payload. +std::uint16_t udp_checksum(std::uint16_t checksum_field) { + // Pseudo-header: source, destination, a zero byte and the protocol, the UDP length. + checksum::internet_state state; + state = checksum::internet_update(state, source); + state = checksum::internet_update(state, destination); + state = checksum::internet_update(state, big_endian(protocol_udp)); + state = checksum::internet_update(state, big_endian(udp_length)); + // UDP header: ports, length, checksum. + state = checksum::internet_update(state, big_endian(source_port)); + state = checksum::internet_update(state, big_endian(destination_port)); + state = checksum::internet_update(state, big_endian(udp_length)); + state = checksum::internet_update(state, big_endian(checksum_field)); + state = checksum::internet_update(state, payload); + return checksum::internet_finalize(state); +} + +} // namespace + +int main() { + // The sender sums with a zero checksum field. UDP sends a computed 0 as 0xFFFF, because 0 means "no checksum". + std::uint16_t value = udp_checksum(0); + if(value == 0) { + value = 0xFFFF; + } + std::println("UDP checksum = 0x{:04X}", value); + + // The receiver sums the datagram as received and expects 0. + bool const valid = udp_checksum(value) == 0; + std::println("received datagram valid: {}", valid ? "yes" : "no"); + return value == 0x67F8 && valid ? 0 : 1; +} From a9f4e1aee8d0d700d0344d03e58526c99bbbef56 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:08:16 +0200 Subject: [PATCH 05/64] refactor(fletcher4): contiguous ranges take compute_loop, one AVX2 block fletcher4_compute(Range) now forwards contiguous ranges to the span overload at run time, as xxh3_compute does, so string views and vectors also get the out-of-line compute_loop. The x86-64 header keeps each threshold next to its kernel. --- src/include/checksum/fletcher4.hpp | 9 ++++++++- .../checksum_private/x86_64/fletcher4.hpp | 10 ++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/include/checksum/fletcher4.hpp b/src/include/checksum/fletcher4.hpp index 36fac31..6f41618 100644 --- a/src/include/checksum/fletcher4.hpp +++ b/src/include/checksum/fletcher4.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -51,7 +52,7 @@ template [[nodiscard]] constexpr fletcher4_state fletcher4_up /// fletcher4_finalize(fletcher4_update(fletcher4_state{}, data)). [[nodiscard]] constexpr fletcher4_value fletcher4_compute(std::span data) noexcept; -/// fletcher4_finalize(fletcher4_update(fletcher4_state{}, data)) for a byte range. +/// fletcher4_finalize(fletcher4_update(fletcher4_state{}, data)) for a byte range. A std::span takes the overload above. template [[nodiscard]] constexpr fletcher4_value fletcher4_compute(Range &&data) noexcept; } // namespace checksum @@ -142,6 +143,12 @@ constexpr fletcher4_value fletcher4_compute(std::span data) noe } template constexpr fletcher4_value fletcher4_compute(Range &&data) noexcept { + // Contiguous ranges take compute_loop() too. + if constexpr(std::ranges::contiguous_range && std::ranges::sized_range) { + if !consteval { + return fletcher4_compute(std::as_bytes(std::span(std::ranges::data(data), std::ranges::size(data)))); + } + } return fletcher4_finalize(fletcher4_update(fletcher4_state{}, std::forward(data))); } diff --git a/src/include_private/checksum_private/x86_64/fletcher4.hpp b/src/include_private/checksum_private/x86_64/fletcher4.hpp index efd3d19..ad1c54b 100644 --- a/src/include_private/checksum_private/x86_64/fletcher4.hpp +++ b/src/include_private/checksum_private/x86_64/fletcher4.hpp @@ -18,14 +18,9 @@ namespace checksum::fletcher4_detail { inline constexpr bool lane_kernel_available = true; #if defined(__AVX2__) + // Where the kernel overtakes the word loop on a Core Ultra 7 155H, with GCC and Clang. inline constexpr std::size_t lane_kernel_minimum_size = 192; -#else -// The kernel overtakes the word loop on a Core Ultra 7 155H at 192 bytes with GCC and at 384 with Clang, which is 10 % slower at 256. -inline constexpr std::size_t lane_kernel_minimum_size = 256; -#endif - -#if defined(__AVX2__) inline lane_sums lane_kernel(std::byte const *data, std::size_t groups) noexcept { __m256i sum1 = _mm256_setzero_si256(); @@ -51,6 +46,9 @@ inline lane_sums lane_kernel(std::byte const *data, std::size_t groups) noexcept #else +// The kernel overtakes the word loop on a Core Ultra 7 155H at 192 bytes with GCC and at 384 with Clang, which is 10 % slower at 256. +inline constexpr std::size_t lane_kernel_minimum_size = 256; + // Lanes 0 and 1 in the low vectors, 2 and 3 in the high ones. inline lane_sums lane_kernel(std::byte const *data, std::size_t groups) noexcept { __m128i const zero = _mm_setzero_si128(); From 9ae2b2d621e773ce0aa25a52342c634f1dad8aa0 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:09:15 +0200 Subject: [PATCH 06/64] examples(fletcher4): ZFS block verification and file checksum --- examples/CMakeLists.txt | 1 + examples/fletcher4/CMakeLists.txt | 4 +++ examples/fletcher4/file_checksum.cpp | 33 +++++++++++++++++++++ examples/fletcher4/zfs_block.cpp | 44 ++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+) create mode 100644 examples/fletcher4/CMakeLists.txt create mode 100644 examples/fletcher4/file_checksum.cpp create mode 100644 examples/fletcher4/zfs_block.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 2a2bc3b..875b41b 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,2 +1,3 @@ add_subdirectory(crc) add_subdirectory(internet) +add_subdirectory(fletcher4) diff --git a/examples/fletcher4/CMakeLists.txt b/examples/fletcher4/CMakeLists.txt new file mode 100644 index 0000000..0cc7904 --- /dev/null +++ b/examples/fletcher4/CMakeLists.txt @@ -0,0 +1,4 @@ +foreach (example zfs_block file_checksum) + add_executable(checksum_example_fletcher4_${example} ${example}.cpp) + target_link_libraries(checksum_example_fletcher4_${example} PRIVATE checksum::checksum) +endforeach () diff --git a/examples/fletcher4/file_checksum.cpp b/examples/fletcher4/file_checksum.cpp new file mode 100644 index 0000000..840666a --- /dev/null +++ b/examples/fletcher4/file_checksum.cpp @@ -0,0 +1,33 @@ +// Computes the fletcher4 checksum of a file in chunks; the state carries an unfinished word over to the next chunk. + +#include + +#include +#include +#include // stderr +#include +#include +#include + +int main(int argument_count, char **arguments) { + if(argument_count != 2) { + std::println(stderr, "usage: {} ", arguments[0]); + return 1; + } + std::ifstream file(arguments[1], std::ios::binary); + if(!file) { + std::println(stderr, "cannot open {}", arguments[1]); + return 1; + } + + checksum::fletcher4_state state; + std::array buffer{}; + while(file.read(buffer.data(), buffer.size()) || file.gcount() > 0) { + state = checksum::fletcher4_update(state, std::span{buffer}.first(static_cast(file.gcount()))); + } + + // A size that is not a multiple of 4 is padded with zero bytes. + checksum::fletcher4_value const value = checksum::fletcher4_finalize(state); + std::println("{:x}:{:x}:{:x}:{:x} {}", value[0], value[1], value[2], value[3], arguments[1]); + return 0; +} diff --git a/examples/fletcher4/zfs_block.cpp b/examples/fletcher4/zfs_block.cpp new file mode 100644 index 0000000..1ac152f --- /dev/null +++ b/examples/fletcher4/zfs_block.cpp @@ -0,0 +1,44 @@ +// Verifies a 4 KiB block against its stored fletcher4 checksum, as ZFS does when it reads a block, and detects a flipped bit. + +#include + +#include +#include +#include + +namespace { + +// The checksum in the notation of zdb: the four sums in hexadecimal, separated by colons. +void print_checksum(char const *label, checksum::fletcher4_value const &value) { + std::println("{} {:x}:{:x}:{:x}:{:x}", label, value[0], value[1], value[2], value[3]); +} + +} // namespace + +int main() { + std::array block{}; + for(std::size_t index = 0; index < block.size(); ++index) { + block[index] = static_cast((index * 31) + 7); + } + + // The checksum the block pointer stores for this block. + constexpr checksum::fletcher4_value stored{0x1F9FE020400, 0x3F56A75807600, 0x54A3344A4A66000, 0x4E81CF973F7DBB00}; + + checksum::fletcher4_value const computed = checksum::fletcher4_compute(block); + print_checksum("stored ", stored); + print_checksum("computed", computed); + if(computed != stored) { + std::println("checksum mismatch"); + return 1; + } + + block[1000] ^= std::byte{0x10}; + checksum::fletcher4_value const damaged = checksum::fletcher4_compute(block); + print_checksum("damaged ", damaged); + if(damaged == stored) { + std::println("bit flip not detected"); + return 1; + } + std::println("bit flip detected"); + return 0; +} From d0545b8f81bd1a965cb0b5f0331089e071c776a2 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:09:42 +0200 Subject: [PATCH 07/64] docs(fletcher4): mention the examples --- README.md | 1 + doc/fletcher4.md | 3 +++ 2 files changed, 4 insertions(+) diff --git a/README.md b/README.md index e58affc..b015ee5 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ CPU acceleration follows your compiler flags (for example `-march=native` or `-m - [MurmurHash3 user guide](doc/murmur3.md): the API, seeds, byte order, measured performance and limitations. - [examples/crc](examples/crc): compile-time CRC, a file checksum, a custom CRC, run-time parameters, a MODBUS frame and a strategy driving an MCU CRC peripheral. +- [examples/fletcher4](examples/fletcher4): verifying a ZFS block and a file checksum. ## Contributing diff --git a/doc/fletcher4.md b/doc/fletcher4.md index a342f1c..3f48c11 100644 --- a/doc/fletcher4.md +++ b/doc/fletcher4.md @@ -27,6 +27,9 @@ static_assert(checksum::fletcher4_compute("abcdefgh"sv) == checksum::fletcher4_value{0xCCCAC8C6, 0x1312E2B27, 0x195918D88, 0x1F9F4EFE9}); ``` +`examples/fletcher4` has complete programs: verifying a 4 KiB block against its stored checksum as ZFS does, and the +checksum of a file read in chunks. + ## 2. Definition fletcher4 reads the message as 32-bit little-endian words and keeps four 64-bit sums, all starting at 0. For each word From cf65250e42fb7c000f1d05147b851683630a25dd Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:09:59 +0200 Subject: [PATCH 08/64] refactor(murmur3): read the 2-byte tail word with load() --- src/include/checksum/murmur3.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/include/checksum/murmur3.hpp b/src/include/checksum/murmur3.hpp index d062499..67bc550 100644 --- a/src/include/checksum/murmur3.hpp +++ b/src/include/checksum/murmur3.hpp @@ -139,7 +139,7 @@ template constexpr Integer load(std::byte const *data) noexcept Integer value = 0; if consteval { for(std::size_t index = 0; index < sizeof(Integer); ++index) { - value |= std::to_integer(data[index]) << (8 * index); + value |= static_cast(std::to_integer(data[index]) << (8 * index)); } } else { std::memcpy(&value, data, sizeof(Integer)); @@ -160,7 +160,7 @@ template constexpr Integer load_partial(std::byte const *data, s } } if((size & 2U) != 0) { - value |= (std::to_integer(data[offset]) | (std::to_integer(data[offset + 1]) << 8)) << (8 * offset); + value |= Integer{load(data + offset)} << (8 * offset); offset += 2; } if((size & 1U) != 0) { From aac07781a9471c3f8c5991452dcd7c0808cd4808 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:09:59 +0200 Subject: [PATCH 09/64] feat(murmur3): murmur3_32 and murmur3_128 aliases --- src/include/checksum/murmur3.hpp | 20 ++++++++++++++++++++ tests/unit_tests/ut_murmur3.cpp | 21 +++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/include/checksum/murmur3.hpp b/src/include/checksum/murmur3.hpp index 67bc550..195af33 100644 --- a/src/include/checksum/murmur3.hpp +++ b/src/include/checksum/murmur3.hpp @@ -60,6 +60,18 @@ template requires(!std::same_as, std::span>) [[nodiscard]] constexpr murmur3_state::value_type murmur3_compute(Range &&data, std::uint32_t seed = 0) noexcept; +/// Running MurmurHash3_x86_32 hash. +using murmur3_32_state = murmur3_state<32>; + +/// Running MurmurHash3_x64_128 hash. +using murmur3_128_state = murmur3_state<128>; + +/// The MurmurHash3_x86_32 hash of data: murmur3_compute<32>(data, seed). +template [[nodiscard]] constexpr murmur3_32_state::value_type murmur3_32_compute(Range &&data, std::uint32_t seed = 0) noexcept; + +/// The MurmurHash3_x64_128 hash of data: murmur3_compute<128>(data, seed). +template [[nodiscard]] constexpr murmur3_128_state::value_type murmur3_128_compute(Range &&data, std::uint32_t seed = 0) noexcept; + } // namespace checksum /// Implementation details; not part of the public API. @@ -308,6 +320,14 @@ constexpr murmur3_state::value_type murmur3_compute(Range &&data, std::ui return murmur3_finalize(murmur3_update(murmur3_state{.seed = seed}, std::forward(data))); } +template constexpr murmur3_32_state::value_type murmur3_32_compute(Range &&data, std::uint32_t seed) noexcept { + return murmur3_compute<32>(std::forward(data), seed); +} + +template constexpr murmur3_128_state::value_type murmur3_128_compute(Range &&data, std::uint32_t seed) noexcept { + return murmur3_compute<128>(std::forward(data), seed); +} + } // namespace checksum #endif // CHECKSUM_MURMUR3_HPP diff --git a/tests/unit_tests/ut_murmur3.cpp b/tests/unit_tests/ut_murmur3.cpp index 4bf8169..122ff12 100644 --- a/tests/unit_tests/ut_murmur3.cpp +++ b/tests/unit_tests/ut_murmur3.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -72,6 +73,9 @@ static_assert(chunked<32>(message, 3, murmur3_32_vectors[1].seed) == murmur3_32_ // Every tail length around a few blocks; longer prefixes exceed the constant-evaluation step limit of Clang. static_assert(prefix_mismatches<32>(70) == 0); static_assert(prefix_mismatches<128>(70) == 0); +static_assert(murmur3_32_compute("Hello, world!"sv, 1234) == 0xFAF6CDB3U); +static_assert(murmur3_128_compute("Hello, world!"sv, 1234) == hash128{0x61130E64AA0AC6FEU, 0x51F9046D087E1B56U}); +static_assert(std::same_as> && std::same_as>); template class murmur3 : public testing::Test {}; @@ -171,6 +175,23 @@ TEST(murmur3_x86_32, length_wraps) { EXPECT_EQ(murmur3_finalize(state), murmur3_finalize(wrapped)); } +// The aliases take the same inputs as the generic form: spans of std::byte, text and other byte ranges. +TEST(murmur3_aliases, match_generic_form) { + auto const bytes = std::span(message); + constexpr std::string_view text = "123456789"; + std::list const list(text.begin(), text.end()); + for(std::uint32_t const seed : {0U, 1U, 0x9747B28CU}) { + EXPECT_EQ(murmur3_32_compute(bytes, seed), murmur3_compute<32>(bytes, seed)); + EXPECT_EQ(murmur3_32_compute(text, seed), murmur3_compute<32>(text, seed)); + EXPECT_EQ(murmur3_32_compute(list, seed), murmur3_compute<32>(list, seed)); + EXPECT_EQ(murmur3_128_compute(bytes, seed), murmur3_compute<128>(bytes, seed)); + EXPECT_EQ(murmur3_128_compute(text, seed), murmur3_compute<128>(text, seed)); + EXPECT_EQ(murmur3_128_compute(list, seed), murmur3_compute<128>(list, seed)); + } + EXPECT_EQ(murmur3_32_compute(bytes), murmur3_compute<32>(bytes)); + EXPECT_EQ(murmur3_128_compute(bytes), murmur3_compute<128>(bytes)); +} + TYPED_TEST(murmur3, long_message) { constexpr unsigned width = TypeParam::value; std::vector data(murmur3_test::long_message_size); From abdd113fc1dfe8cf8aeb50de543894003c01c8dd Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:11:26 +0200 Subject: [PATCH 10/64] examples(murmur3): command dispatch, Bloom filter and deduplication --- examples/CMakeLists.txt | 1 + examples/murmur3/CMakeLists.txt | 4 ++ examples/murmur3/bloom_filter.cpp | 62 +++++++++++++++++++++++++++++++ examples/murmur3/compile_time.cpp | 40 ++++++++++++++++++++ examples/murmur3/deduplicate.cpp | 49 ++++++++++++++++++++++++ 5 files changed, 156 insertions(+) create mode 100644 examples/murmur3/CMakeLists.txt create mode 100644 examples/murmur3/bloom_filter.cpp create mode 100644 examples/murmur3/compile_time.cpp create mode 100644 examples/murmur3/deduplicate.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 875b41b..e8153ec 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,3 +1,4 @@ add_subdirectory(crc) add_subdirectory(internet) add_subdirectory(fletcher4) +add_subdirectory(murmur3) diff --git a/examples/murmur3/CMakeLists.txt b/examples/murmur3/CMakeLists.txt new file mode 100644 index 0000000..6bbf9d8 --- /dev/null +++ b/examples/murmur3/CMakeLists.txt @@ -0,0 +1,4 @@ +foreach (example compile_time bloom_filter deduplicate) + add_executable(checksum_example_murmur3_${example} ${example}.cpp) + target_link_libraries(checksum_example_murmur3_${example} PRIVATE checksum::checksum) +endforeach () diff --git a/examples/murmur3/bloom_filter.cpp b/examples/murmur3/bloom_filter.cpp new file mode 100644 index 0000000..3d8d265 --- /dev/null +++ b/examples/murmur3/bloom_filter.cpp @@ -0,0 +1,62 @@ +// A Bloom filter of user names: one MurmurHash3_x64_128 hash per key gives all its bit positions. + +#include + +#include +#include +#include +#include +#include + +using namespace std::literals; + +namespace { + +class bloom_filter { +public: + void insert(std::string_view key) { + for(std::size_t index = 0; index < hash_count; ++index) { + bits.set(position(key, index)); + } + } + + // False means the key was never inserted; true means it probably was. + [[nodiscard]] bool may_contain(std::string_view key) const { + for(std::size_t index = 0; index < hash_count; ++index) { + if(!bits.test(position(key, index))) { + return false; + } + } + return true; + } + +private: + static constexpr std::size_t bit_count = 1024; + static constexpr std::size_t hash_count = 5; + + // The halves h1 and h2 combine into hash_count positions as h1 + index * h2 (Kirsch and Mitzenmacher). + static std::size_t position(std::string_view key, std::size_t index) { + auto const [h1, h2] = checksum::murmur3_128_compute(key); + return static_cast((h1 + (index * h2)) % bit_count); + } + + std::bitset bits; +}; + +} // namespace + +int main() { + bloom_filter users; + for(std::string_view const name : {"alice"sv, "bob"sv, "carol"sv, "dave"sv}) { + users.insert(name); + } + bool all_found = true; + for(std::string_view const name : {"alice"sv, "bob"sv, "carol"sv, "dave"sv}) { + all_found = all_found && users.may_contain(name); + } + for(std::string_view const name : {"alice"sv, "mallory"sv, "trent"sv}) { + std::println("{:8} {}", name, users.may_contain(name) ? "probably present" : "absent"); + } + // A filter never reports an inserted key as absent. + return all_found ? 0 : 1; +} diff --git a/examples/murmur3/compile_time.cpp b/examples/murmur3/compile_time.cpp new file mode 100644 index 0000000..0e34ed5 --- /dev/null +++ b/examples/murmur3/compile_time.cpp @@ -0,0 +1,40 @@ +// Dispatches text commands with a switch on their MurmurHash3_x86_32 hash: the case labels are hashed at compile time. + +#include + +#include +#include +#include + +using namespace std::literals; + +// The compiler verifies a reference value of MurmurHash3_x86_32. +static_assert(checksum::murmur3_32_compute("Hello, world!"sv, 1234) == 0xFAF6CDB3); + +namespace { + +constexpr std::uint32_t key(std::string_view command) { return checksum::murmur3_32_compute(command); } + +// Two commands with the same hash would be duplicate case labels, a compile error. Unknown text that collides with a label runs +// that command; compare the text too where this matters. +std::string_view execute(std::string_view command) { + switch(key(command)) { + case key("start"): + return "starting"; + case key("stop"): + return "stopping"; + case key("status"): + return "running"; + default: + return "unknown command"; + } +} + +} // namespace + +int main() { + for(std::string_view const command : {"status"sv, "stop"sv, "reboot"sv}) { + std::println("{:8} 0x{:08X} -> {}", command, key(command), execute(command)); + } + return execute("stop") == "stopping" && execute("reboot") == "unknown command" ? 0 : 1; +} diff --git a/examples/murmur3/deduplicate.cpp b/examples/murmur3/deduplicate.cpp new file mode 100644 index 0000000..b965dca --- /dev/null +++ b/examples/murmur3/deduplicate.cpp @@ -0,0 +1,49 @@ +// Finds duplicate records by their MurmurHash3_x64_128 hash, folding each record from its fields with the streaming API. + +#include + +#include +#include +#include +#include +#include +#include + +using namespace std::literals; + +namespace { + +struct record { + std::string_view name; + std::string_view payload; +}; + +// The fields are folded one after another; a separator keeps {"ab", "c"} and {"a", "bc"} apart. +std::array record_hash(record const &value) { + checksum::murmur3_128_state state{.seed = 0x5EED}; + state = checksum::murmur3_update(state, value.name); + state = checksum::murmur3_update(state, "\037"sv); + state = checksum::murmur3_update(state, value.payload); + return checksum::murmur3_finalize(state); +} + +} // namespace + +int main() { + constexpr std::array records{ + record{"sensor-1", "21.5 C"}, record{"sensor-2", "19.0 C"}, record{"sensor-1", "21.5 C"}, + record{"sensor-1", "21.6 C"}, record{"sensor-2", "19.0 C"}, + }; + std::set> seen; + std::size_t duplicates = 0; + for(record const &value : records) { + auto const hash = record_hash(value); + bool const is_new = seen.insert(hash).second; + duplicates += is_new ? 0 : 1; + std::println("{:016x}{:016x} {} {}{}", hash[0], hash[1], value.name, value.payload, is_new ? "" : " (duplicate)"); + } + std::println("{} unique, {} duplicates", seen.size(), duplicates); + // The streamed hash equals the hash of the whole record in one call. + bool const streaming_matches = record_hash(records[0]) == checksum::murmur3_128_compute("sensor-1\03721.5 C"sv, 0x5EED); + return seen.size() == 3 && duplicates == 2 && streaming_matches ? 0 : 1; +} From 246572456c513e02db46b1090c57436ed3db4910 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:12:07 +0200 Subject: [PATCH 11/64] docs(murmur3): aliases, examples, section order like the other guides --- doc/murmur3.md | 39 ++++++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/doc/murmur3.md b/doc/murmur3.md index 030fff8..223d178 100644 --- a/doc/murmur3.md +++ b/doc/murmur3.md @@ -14,19 +14,23 @@ allocates no memory and has no global state. using namespace std::literals; // One call, seed 0 or another seed. -std::uint32_t hash = checksum::murmur3_compute<32>(std::span(key)); -std::array wide = checksum::murmur3_compute<128>(std::span(key), 1234); +std::string_view key = "user:42"; +std::uint32_t hash = checksum::murmur3_32_compute(key); +std::array wide = checksum::murmur3_128_compute(key, 1234); // Incremental: a message may be split anywhere. -checksum::murmur3_state<128> state{.seed = 1234}; +checksum::murmur3_128_state state{.seed = 1234}; state = checksum::murmur3_update(state, first_part); state = checksum::murmur3_update(state, second_part); std::array value = checksum::murmur3_finalize(state); // Compile time. -static_assert(checksum::murmur3_compute<32>("Hello, world!"sv, 1234) == 0xFAF6CDB3); +static_assert(checksum::murmur3_32_compute("Hello, world!"sv, 1234) == 0xFAF6CDB3); ``` +`examples/murmur3` has complete programs: command dispatch on hashes computed at compile time, a Bloom filter and +deduplication of records by their 128-bit hash. + ## 2. API `Width` is 32 for MurmurHash3_x86_32 and 128 for MurmurHash3_x64_128. @@ -37,13 +41,16 @@ static_assert(checksum::murmur3_compute<32>("Hello, world!"sv, 1234) == 0xFAF6CD | `murmur3_update(state, data)` | Folds `data` into `state` and returns the new state. | | `murmur3_finalize(state)` | The hash of the message folded into `state`; the state is unchanged. | | `murmur3_compute(data, seed = 0)` | `murmur3_finalize(murmur3_update(murmur3_state{.seed = seed}, data))`. | +| `murmur3_32_state`, `murmur3_128_state` | `murmur3_state<32>` and `murmur3_state<128>`. | +| `murmur3_32_compute(data, seed = 0)`, `murmur3_128_compute(data, seed = 0)` | `murmur3_compute<32>(data, seed)` and `murmur3_compute<128>(data, seed)`. | `murmur3_state::value_type` is the hash: `std::uint32_t` for Width 32, and for Width 128 a `std::array` holding the two halves h1 and h2 in the order the reference implementation stores them. All functions are `constexpr` and `noexcept`. `data` is a `std::span` or any range of -`std::byte`, `char`, `unsigned char`, `signed char` or `char8_t`, as for the other algorithms. `murmur3_compute` hashes -contiguous ranges directly, without the state's buffer; other ranges are folded in 64-byte chunks. Arrays of `char` are -rejected, so the `'\0'` of a string literal is never hashed: pass text as `std::string_view`. +`std::byte`, `char`, `unsigned char`, `signed char` or `char8_t`, as for the other algorithms. At run time +`murmur3_compute` hashes contiguous ranges directly, without the state's buffer; other ranges are folded in 64-byte +chunks. Arrays of `char` are rejected, so the `'\0'` of a string literal is never hashed: pass text as +`std::string_view`. Every state value is valid, so nothing has preconditions. Before the first whole block (4 or 16 bytes), the lanes and the unused bytes of the buffer are ignored. @@ -59,7 +66,7 @@ the unused bytes of the buffer are ignored. - **Long messages:** MurmurHash3_x86_32 mixes in the length modulo 2^32, MurmurHash3_x64_128 the 64-bit length. The reference implementation takes the length as an `int`, so it cannot hash messages of 2 GiB or more. -## 4. No CPU acceleration +## 4. CPU acceleration MurmurHash3 has no kernel, on any target. Every block updates the hash lanes through a rotation, a multiplication and an addition of their previous values, and in MurmurHash3_x64_128 the second lane also takes the first lane of the same @@ -68,12 +75,17 @@ function, the block loop, is compiled once per width in `src/murmur3/block_loop. 256 bytes fold inline instead, which saves the call. MurmurHash3_x64_128 needs 64-bit multiplications, which 32-bit targets build from several 32-bit ones. On 32-bit -targets MurmurHash3_x86_32 is the faster of the two; on 64-bit targets MurmurHash3_x64_128 is faster from about -64 bytes. +targets MurmurHash3_x86_32 is the faster of the two; on 64-bit targets MurmurHash3_x64_128 is at least as fast at 20 +bytes and faster from 64 bytes. ## 5. Performance -### 5.1 Cortex-A72: Raspberry Pi 4, 1.5 GHz +### 5.1 x86-64: Core Ultra 7 155H + +GCC, `-O2 -march=native`: MurmurHash3_x86_32 runs 5 388 MB/s at 20 bytes and 4 233 at 1 MiB, MurmurHash3_x64_128 +6 140 and 10 006. + +### 5.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz GCC 14.3, `-O2`, one core. MB/s (10⁶ bytes per second): @@ -84,15 +96,12 @@ GCC 14.3, `-O2`, one core. MB/s (10⁶ bytes per second): | x86_32, AArch32 | 653 | 952 | 1 063 | 1 166 | 1 180 | 1 093 | | x64_128, AArch32 | 278 | 408 | 536 | 595 | 604 | 599 | -### 5.2 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz +### 5.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz GCC 14.3, `-O2`, code in flash and data in RAM, measured with the cycle counter. At 4 KiB MurmurHash3_x86_32 takes 3.03 cycles per byte (26 MB/s at 80 MHz) and MurmurHash3_x64_128 4.43 (18 MB/s); at 20 bytes they reach 9.6 and 6.8 MB/s. Both chips run the same cycles per byte, so the figures scale with the clock. -On x86-64 (Core Ultra 7 155H, GCC, `-O2 -march=native`) MurmurHash3_x86_32 runs 5 388 MB/s at 20 bytes and 4 233 at -1 MiB, MurmurHash3_x64_128 6 140 and 10 006. - ## 6. Limitations - **Not cryptographic:** MurmurHash3 does not resist inputs crafted to collide, even with a secret seed. Do not use it From 0b8ffe2222343134c8be8cd039b9ee9f6387e412 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:12:13 +0200 Subject: [PATCH 12/64] examples(murmur3): plain wording in the Bloom filter comment --- examples/murmur3/bloom_filter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/murmur3/bloom_filter.cpp b/examples/murmur3/bloom_filter.cpp index 3d8d265..e4f0dc2 100644 --- a/examples/murmur3/bloom_filter.cpp +++ b/examples/murmur3/bloom_filter.cpp @@ -34,7 +34,7 @@ class bloom_filter { static constexpr std::size_t bit_count = 1024; static constexpr std::size_t hash_count = 5; - // The halves h1 and h2 combine into hash_count positions as h1 + index * h2 (Kirsch and Mitzenmacher). + // The halves h1 and h2 combine into hash_count positions as h1 + index * h2, double hashing. static std::size_t position(std::string_view key, std::size_t index) { auto const [h1, h2] = checksum::murmur3_128_compute(key); return static_cast((h1 + (index * h2)) % bit_count); From ca94ec4d5dec53df5ef05e8cd405829da364a9ca Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:11:22 +0200 Subject: [PATCH 13/64] feat(xxhash): add xxh32 and xxh64 aliases xxh32_state, xxh64_state, xxh32_compute and xxh64_compute forward to the generic templates. Also document the 2^32 length wrap of XXH32 on xxhash_finalize and spell detail types as word. --- src/include/checksum/xxhash.hpp | 27 +++++++++++++++++++++++---- tests/benchmarks/bench_xxhash.cpp | 4 ++-- tests/unit_tests/ut_xxhash.cpp | 19 +++++++++++++++++++ 3 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/include/checksum/xxhash.hpp b/src/include/checksum/xxhash.hpp index 735b92c..58b94c1 100644 --- a/src/include/checksum/xxhash.hpp +++ b/src/include/checksum/xxhash.hpp @@ -47,7 +47,7 @@ template template [[nodiscard]] constexpr xxhash_state xxhash_update(xxhash_state state, Range &&data) noexcept; -/// The hash of the message folded into state. +/// The hash of the message folded into state. Messages of 4 GiB or more mix in their length modulo 2^32 for Width 32. template [[nodiscard]] constexpr xxhash_state::value_type xxhash_finalize(xxhash_state const &state) noexcept; /// The hash of data: xxhash_finalize(xxhash_update(xxhash_state{.seed = seed}, data)). @@ -60,6 +60,18 @@ template requires(!std::same_as, std::span>) [[nodiscard]] constexpr xxhash_state::value_type xxhash_compute(Range &&data, typename xxhash_state::value_type seed = 0) noexcept; +/// Running XXH32 hash. +using xxh32_state = xxhash_state<32>; + +/// Running XXH64 hash. +using xxh64_state = xxhash_state<64>; + +/// The XXH32 hash of data: xxhash_compute<32>(data, seed). +template [[nodiscard]] constexpr std::uint32_t xxh32_compute(Range &&data, std::uint32_t seed = 0) noexcept; + +/// The XXH64 hash of data: xxhash_compute<64>(data, seed). +template [[nodiscard]] constexpr std::uint64_t xxh64_compute(Range &&data, std::uint64_t seed = 0) noexcept; + } // namespace checksum /// Implementation details; not part of the public API. @@ -271,8 +283,7 @@ template constexpr xxhash_state xxhash template constexpr xxhash_state::value_type xxhash_finalize(xxhash_state const &state) noexcept { auto const buffered = static_cast(state.length % xxhash_detail::stripe_size); // Before the first stripe the lanes are unused, and converging them would cost 8 multiplications for nothing. - typename xxhash_state::value_type const converged = - state.length >= xxhash_detail::stripe_size ? xxhash_detail::converge(state.lanes) : 0; + xxhash_detail::word const converged = state.length >= xxhash_detail::stripe_size ? xxhash_detail::converge(state.lanes) : 0; return xxhash_detail::finish(converged, state.seed, state.length, std::span(state.buffer).first(buffered)); } @@ -286,7 +297,7 @@ constexpr xxhash_state::value_type xxhash_compute(std::span::value_type converged = 0; + xxhash_detail::word converged = 0; if(whole != 0) { xxhash_detail::lane_array lanes = xxhash_detail::initial_lanes(seed); converged = xxhash_detail::fold_and_converge(lanes, data.first(whole), true); @@ -306,6 +317,14 @@ constexpr xxhash_state::value_type xxhash_compute(Range &&data, typename return xxhash_finalize(xxhash_update(xxhash_state{.seed = seed}, std::forward(data))); } +template constexpr std::uint32_t xxh32_compute(Range &&data, std::uint32_t seed) noexcept { + return xxhash_compute<32>(std::forward(data), seed); +} + +template constexpr std::uint64_t xxh64_compute(Range &&data, std::uint64_t seed) noexcept { + return xxhash_compute<64>(std::forward(data), seed); +} + } // namespace checksum #endif // CHECKSUM_XXHASH_HPP diff --git a/tests/benchmarks/bench_xxhash.cpp b/tests/benchmarks/bench_xxhash.cpp index 5b7932c..b1dede2 100644 --- a/tests/benchmarks/bench_xxhash.cpp +++ b/tests/benchmarks/bench_xxhash.cpp @@ -30,11 +30,11 @@ template void run(benchmark::State &state, Hash hash) { } void xxhash32(benchmark::State &state) { - run(state, [](std::span data) { return checksum::xxhash_compute<32>(data); }); + run(state, [](std::span data) { return checksum::xxh32_compute(data); }); } void xxhash64(benchmark::State &state) { - run(state, [](std::span data) { return checksum::xxhash_compute<64>(data); }); + run(state, [](std::span data) { return checksum::xxh64_compute(data); }); } void xxh3_64(benchmark::State &state) { diff --git a/tests/unit_tests/ut_xxhash.cpp b/tests/unit_tests/ut_xxhash.cpp index 5f47c57..ea5f02c 100644 --- a/tests/unit_tests/ut_xxhash.cpp +++ b/tests/unit_tests/ut_xxhash.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -71,6 +72,8 @@ static_assert(chunked<32>(message, 13, xxhash32_vectors[1].seed) == xxhash32_vec // Every tail length around two XXH64 stripes; longer prefixes exceed the constant-evaluation step limit of Clang. static_assert(prefix_mismatches<32>(70) == 0); static_assert(prefix_mismatches<64>(70) == 0); +static_assert(std::same_as> && std::same_as>); +static_assert(xxh32_compute("abc"sv) == 0x32D153FFU && xxh64_compute("abc"sv, 1) == xxhash_compute<64>("abc"sv, 1)); template class xxhash : public testing::Test {}; @@ -159,6 +162,22 @@ TYPED_TEST(xxhash, long_message) { } } +TEST(xxhash, aliases) { + constexpr std::string_view text = "123456789 123456789 123456789 123456789"; + auto const bytes = std::as_bytes(std::span(text)); + for(auto const &set : xxhash32_vectors) { + EXPECT_EQ(xxh32_compute(text, set.seed), xxhash_compute<32>(text, set.seed)); + EXPECT_EQ(xxh32_compute(bytes, set.seed), xxhash_compute<32>(bytes, set.seed)); + EXPECT_EQ(xxh32_compute(std::span(message), set.seed), set.prefixes[300]); + } + for(auto const &set : xxhash64_vectors) { + EXPECT_EQ(xxh64_compute(text, set.seed), xxhash_compute<64>(text, set.seed)); + EXPECT_EQ(xxh64_compute(bytes, set.seed), xxhash_compute<64>(bytes, set.seed)); + EXPECT_EQ(xxh64_compute(std::span(message), set.seed), set.prefixes[300]); + } + EXPECT_EQ(xxhash_finalize(xxhash_update(xxh64_state{.seed = 7}, text)), xxh64_compute(text, 7)); +} + // Seeds of all ones wrap every lane's initial value; hashes from xxhash.h 0.8.4. TEST(xxhash, all_ones_seed) { struct expected_hashes { From d917482cc27f38ff6d011d954031e41a2c76b765 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:11:22 +0200 Subject: [PATCH 14/64] examples(xxhash): compile-time IDs, file hash and cache key --- examples/CMakeLists.txt | 1 + examples/xxhash/CMakeLists.txt | 4 +++ examples/xxhash/cache_key.cpp | 40 +++++++++++++++++++++++++++ examples/xxhash/compile_time.cpp | 46 ++++++++++++++++++++++++++++++++ examples/xxhash/file_hash.cpp | 32 ++++++++++++++++++++++ 5 files changed, 123 insertions(+) create mode 100644 examples/xxhash/CMakeLists.txt create mode 100644 examples/xxhash/cache_key.cpp create mode 100644 examples/xxhash/compile_time.cpp create mode 100644 examples/xxhash/file_hash.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index e8153ec..a2f434b 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -2,3 +2,4 @@ add_subdirectory(crc) add_subdirectory(internet) add_subdirectory(fletcher4) add_subdirectory(murmur3) +add_subdirectory(xxhash) diff --git a/examples/xxhash/CMakeLists.txt b/examples/xxhash/CMakeLists.txt new file mode 100644 index 0000000..4bf8efe --- /dev/null +++ b/examples/xxhash/CMakeLists.txt @@ -0,0 +1,4 @@ +foreach (example compile_time file_hash cache_key) + add_executable(checksum_example_xxhash_${example} ${example}.cpp) + target_link_libraries(checksum_example_xxhash_${example} PRIVATE checksum::checksum) +endforeach () diff --git a/examples/xxhash/cache_key.cpp b/examples/xxhash/cache_key.cpp new file mode 100644 index 0000000..992ef34 --- /dev/null +++ b/examples/xxhash/cache_key.cpp @@ -0,0 +1,40 @@ +// Content-addressed cache: a build step is skipped when the XXH64 of its source and options is already known. + +#include + +#include +#include +#include +#include +#include + +using namespace std::literals; + +namespace { + +// The options seed the hash of the source, so the same source built with other options gets another key. +std::uint64_t cache_key(std::string_view source, std::string_view options) { + return checksum::xxh64_compute(source, checksum::xxh64_compute(options)); +} + +} // namespace + +int main() { + // XXH64("abc") of the reference implementation. + if(checksum::xxh64_compute("abc"sv) != 0x44BC2CF5AD770999) { + std::println("XXH64 mismatch"); + return 1; + } + + std::unordered_map cache; + auto const build = [&](std::string_view source, std::string_view options) { + std::uint64_t const key = cache_key(source, options); + auto const [entry, inserted] = cache.try_emplace(key, std::string(options) + " build of " + std::string(source)); + std::println("{:016x} {}: {}", key, inserted ? "built" : "cached", entry->second); + }; + + build("int main() {}", "-O2"); + build("int main() {}", "-O0"); + build("int main() {}", "-O2"); + return 0; +} diff --git a/examples/xxhash/compile_time.cpp b/examples/xxhash/compile_time.cpp new file mode 100644 index 0000000..9f16b45 --- /dev/null +++ b/examples/xxhash/compile_time.cpp @@ -0,0 +1,46 @@ +// Hashes message names at compile time into 32-bit IDs and dispatches on them with a switch. + +#include + +#include +#include +#include + +using namespace std::literals; + +// The compiler verifies the reference value of XXH32("abc"). +static_assert(checksum::xxh32_compute("abc"sv) == 0x32D153FF); + +// The seed keeps these IDs apart from hashes of the same names elsewhere. +constexpr std::uint32_t message_id(std::string_view name) { return checksum::xxh32_compute(name, 0x4D534731); } + +constexpr std::uint32_t temperature_id = message_id("sensor/temperature"); +constexpr std::uint32_t humidity_id = message_id("sensor/humidity"); +static_assert(temperature_id != humidity_id); + +namespace { + +void handle(std::string_view name) { + // A run-time hash of the same text matches the constant. + switch(message_id(name)) { + case temperature_id: + std::println("{}: temperature handler", name); + break; + case humidity_id: + std::println("{}: humidity handler", name); + break; + default: + std::println("{}: unknown message", name); + break; + } +} + +} // namespace + +int main() { + std::println("ID of sensor/temperature = 0x{:08X}", temperature_id); + handle("sensor/temperature"); + handle("sensor/humidity"); + handle("sensor/pressure"); + return 0; +} diff --git a/examples/xxhash/file_hash.cpp b/examples/xxhash/file_hash.cpp new file mode 100644 index 0000000..9f7725f --- /dev/null +++ b/examples/xxhash/file_hash.cpp @@ -0,0 +1,32 @@ +// Computes the XXH64 hash of a file in chunks, in the output format of `xxh64sum`. + +#include + +#include +#include +#include // stderr +#include +#include +#include + +int main(int argument_count, char **arguments) { + if(argument_count != 2) { + std::println(stderr, "usage: {} ", arguments[0]); + return 1; + } + std::ifstream file(arguments[1], std::ios::binary); + if(!file) { + std::println(stderr, "cannot open {}", arguments[1]); + return 1; + } + + // The state is a plain value: each update returns it with one more chunk folded in. + checksum::xxh64_state state{}; + std::array buffer{}; + while(file.read(buffer.data(), buffer.size()) || file.gcount() > 0) { + state = checksum::xxhash_update(state, std::span{buffer}.first(static_cast(file.gcount()))); + } + + std::println("{:016x} {}", checksum::xxhash_finalize(state), arguments[1]); + return 0; +} From 680c69a15503b023f9f1e6cbbab23dbbe30488d0 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:11:22 +0200 Subject: [PATCH 15/64] docs(xxhash): aliases, examples and the run-time XXH32 path --- doc/xxhash.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/doc/xxhash.md b/doc/xxhash.md index d78a0ba..b02c32b 100644 --- a/doc/xxhash.md +++ b/doc/xxhash.md @@ -15,7 +15,7 @@ memory and there is no global state; XXH3 keeps its 192-byte default secret in r using namespace std::literals; // One call, seed 0 or another seed. -std::uint32_t small = checksum::xxhash_compute<32>(std::span(key)); +std::uint32_t small = checksum::xxh32_compute(key); std::uint64_t hash = checksum::xxh3_compute<64>(std::span(key), 1234); checksum::xxh3_hash128 wide = checksum::xxh3_compute<128>(std::span(key)); @@ -26,8 +26,8 @@ state = checksum::xxh3_update(state, second_part); std::uint64_t value = checksum::xxh3_finalize(state); // Compile time. -static_assert(checksum::xxhash_compute<32>("abc"sv) == 0x32D153FF); -static_assert(checksum::xxhash_compute<64>("abc"sv) == 0x44BC2CF5AD770999); +static_assert(checksum::xxh32_compute("abc"sv) == 0x32D153FF); +static_assert(checksum::xxh64_compute("abc"sv) == 0x44BC2CF5AD770999); static_assert(checksum::xxh3_compute<64>("abc"sv) == 0x78AF5F94892F3950); static_assert(checksum::xxh3_compute<128>("abc"sv) == checksum::xxh3_hash128{.low = 0x78AF5F94892F3950, .high = 0x06B05AB6733A6185}); @@ -55,11 +55,16 @@ prefix of a message several ways. | `xxhash_update(state, data)` | Folds `data` into `state` and returns the new state. | | `xxhash_finalize(state)` | The hash of the message folded into `state`; the state is unchanged. | | `xxhash_compute(data, seed = 0)` | `xxhash_finalize(xxhash_update(xxhash_state{.seed = seed}, data))`. | +| `xxh32_state`, `xxh64_state` | `xxhash_state<32>` and `xxhash_state<64>`. | +| `xxh32_compute(data, seed = 0)`, `xxh64_compute(data, seed = 0)` | `xxhash_compute<32>` and `xxhash_compute<64>`. | `xxhash_state::value_type` is the type of the hash, the seed and the lanes: `std::uint32_t` for XXH32 and `std::uint64_t` for XXH64. The lanes are set from the seed when the first whole stripe is folded; before that they are ignored. +`examples/xxhash` has complete programs: message IDs hashed at compile time, the XXH64 of a file read in chunks, and +a cache keyed by the hash of its input. + ### 2.2 XXH3-64 and XXH3-128 `Width` is 64 for XXH3-64 and 128 for XXH3-128. @@ -104,7 +109,8 @@ XXH32 and XXH64 have no kernel, on any target. Each of the four lanes is a seria rotation per word; the scalar loop already keeps four of them in flight. A NEON prototype of XXH32 ran 1 685 MB/s on a Cortex-A72 at 4 KiB against 2 333 for the scalar loop, and Clang vectorizing the lanes on its own lost 38 % on x86-64. XXH64 needs 64-bit multiplications per lane, which SSE2, AVX2 and NEON do not have. The stripe loop is -compiled once per width in `src/xxhash/stripe_loop.cpp`, out of line, so that compilers keep the lanes scalar. +compiled once per width in `src/xxhash/stripe_loop.cpp`, out of line, so that compilers keep the lanes scalar; the +one-shot XXH32 of a message of at least 16 bytes runs a function there that keeps them in local variables. ### 4.2 XXH3 From 3a129fddf52fe91cffa9c87dbd600584fed13280 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:09:25 +0200 Subject: [PATCH 16/64] feat(xxh3): xxh3_64 and xxh3_128 state and compute aliases --- src/include/checksum/xxh3.hpp | 20 ++++++++++++++++++++ tests/unit_tests/ut_xxh3.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/include/checksum/xxh3.hpp b/src/include/checksum/xxh3.hpp index 51ec490..c01969e 100644 --- a/src/include/checksum/xxh3.hpp +++ b/src/include/checksum/xxh3.hpp @@ -70,6 +70,18 @@ template requires(!std::same_as, std::span>) [[nodiscard]] constexpr xxh3_state::value_type xxh3_compute(Range &&data, std::uint64_t seed = 0) noexcept; +/// Running XXH3-64 hash. +using xxh3_64_state = xxh3_state<64>; + +/// Running XXH3-128 hash. +using xxh3_128_state = xxh3_state<128>; + +/// The XXH3-64 hash of data: xxh3_compute<64>(data, seed). +template [[nodiscard]] constexpr std::uint64_t xxh3_64_compute(Range &&data, std::uint64_t seed = 0) noexcept; + +/// The XXH3-128 hash of data: xxh3_compute<128>(data, seed). +template [[nodiscard]] constexpr xxh3_hash128 xxh3_128_compute(Range &&data, std::uint64_t seed = 0) noexcept; + } // namespace checksum /// Implementation details; not part of the public API. @@ -624,6 +636,14 @@ constexpr xxh3_state::value_type xxh3_compute(Range &&data, std::uint64_t return xxh3_finalize(xxh3_update(xxh3_state{.seed = seed}, std::forward(data))); } +template constexpr std::uint64_t xxh3_64_compute(Range &&data, std::uint64_t seed) noexcept { + return xxh3_compute<64>(std::forward(data), seed); +} + +template constexpr xxh3_hash128 xxh3_128_compute(Range &&data, std::uint64_t seed) noexcept { + return xxh3_compute<128>(std::forward(data), seed); +} + } // namespace checksum #endif // CHECKSUM_XXH3_HPP diff --git a/tests/unit_tests/ut_xxh3.cpp b/tests/unit_tests/ut_xxh3.cpp index e93b649..0bbfa93 100644 --- a/tests/unit_tests/ut_xxh3.cpp +++ b/tests/unit_tests/ut_xxh3.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -107,6 +108,10 @@ static_assert(edge_seed_mismatches<128>(513) == 0); static_assert(xxh3_detail::multiply_portable(~std::uint64_t{0}, ~std::uint64_t{0}) == xxh3_hash128{.low = 1, .high = ~std::uint64_t{1}}); static_assert(xxh3_detail::multiply_portable(0x9E3779B185EBCA87U, 0xC2B2AE3D27D4EB4FU) == xxh3_hash128{.low = 0xDEF35B010F796CA9U, .high = 0x7854787AA57880A8U}); +static_assert(xxh3_64_compute("abc"sv) == 0x78AF5F94892F3950U); +static_assert(xxh3_128_compute(std::span(message).first(241), xxh3_128_vectors[1].seed) == xxh3_128_vectors[1].prefixes[241]); +static_assert(std::same_as> && std::same_as>); +static_assert(sizeof(xxh3_state<64>) == 336); template class xxh3 : public testing::Test {}; @@ -305,6 +310,25 @@ TYPED_TEST(xxh3, long_message) { } } +// The aliases give the hashes of the generic functions, for spans, string views and other byte ranges. +TEST(xxh3_aliases, match_generic) { + constexpr std::string_view text = "123456789 123456789 123456789 123456789"; + std::span const bytes = std::as_bytes(std::span(text)); + std::list const list(text.begin(), text.end()); + for(std::uint64_t const seed : {std::uint64_t{0}, std::uint64_t{0x9E3779B97F4A7C15U}}) { + EXPECT_EQ(xxh3_64_compute(bytes, seed), xxh3_compute<64>(bytes, seed)); + EXPECT_EQ(xxh3_64_compute(text, seed), xxh3_compute<64>(bytes, seed)); + EXPECT_EQ(xxh3_64_compute(list, seed), xxh3_compute<64>(bytes, seed)); + EXPECT_EQ(xxh3_128_compute(bytes, seed), xxh3_compute<128>(bytes, seed)); + EXPECT_EQ(xxh3_128_compute(text, seed), xxh3_compute<128>(bytes, seed)); + EXPECT_EQ(xxh3_128_compute(list, seed), xxh3_compute<128>(bytes, seed)); + EXPECT_EQ(xxh3_finalize(xxh3_update(xxh3_64_state{.seed = seed}, text)), xxh3_64_compute(text, seed)); + EXPECT_EQ(xxh3_finalize(xxh3_update(xxh3_128_state{.seed = seed}, text)), xxh3_128_compute(text, seed)); + } + EXPECT_EQ(xxh3_64_compute(message), xxh3_64_vectors[0].blocks.back()); + EXPECT_EQ(xxh3_128_compute(message), xxh3_128_vectors[0].blocks.back()); +} + // The run-time multiplication, native where the compiler has one, against the portable one. TEST(xxh3_multiply, matches_portable) { std::uint64_t left = 0x0123456789ABCDEFU; From c33b258ed08c9c9e0972ab068c4d8a674541c6ec Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:11:44 +0200 Subject: [PATCH 17/64] refactor(xxh3): accumulate and scramble only as portable_kernel members --- src/include/checksum/xxh3.hpp | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/src/include/checksum/xxh3.hpp b/src/include/checksum/xxh3.hpp index c01969e..2aaa060 100644 --- a/src/include/checksum/xxh3.hpp +++ b/src/include/checksum/xxh3.hpp @@ -184,19 +184,15 @@ template constexpr value hash_midsize(std::span constexpr void accumulate_lane(accumulator_array &accumulators, std::byte const *stripe, std::byte const *secret) noexcept; -// Mixes one stripe into the accumulators. Spelled out per lane: as a loop, GCC keeps the accumulators in memory; GCC for Cortex-M4 -// outlines the unforced lanes and calls them per stripe. -constexpr void accumulate(accumulator_array &accumulators, std::byte const *stripe, std::byte const *secret) noexcept; - -// Scrambles the accumulators with the last 64 bytes of the secret, at secret. -constexpr void scramble(accumulator_array &accumulators, std::byte const *secret) noexcept; - // The portable stripe kernel. A kernel keeps the accumulators in its lanes type and defines the same four functions. struct portable_kernel { using lanes = accumulator_array; static constexpr lanes load(accumulator_array const &accumulators) noexcept; static constexpr void store(accumulator_array &accumulators, lanes const &values) noexcept; + // Mixes one stripe into the accumulators. Spelled out per lane: as a loop, GCC keeps the accumulators in memory; GCC for + // Cortex-M4 outlines the unforced lanes and calls them per stripe. static constexpr void accumulate(lanes &values, std::byte const *stripe, std::byte const *secret) noexcept; + // Scrambles the accumulators with the last 64 bytes of the secret, at secret. static constexpr void scramble(lanes &values, std::byte const *secret) noexcept; }; @@ -465,28 +461,22 @@ constexpr void accumulate_lane(accumulator_array &accumulators, std::byte const std::get(accumulators) += (key & low_half_mask) * (key >> 32U); } -constexpr void accumulate(accumulator_array &accumulators, std::byte const *stripe, std::byte const *secret) noexcept { - [&] [[gnu::always_inline]] (std::index_sequence) { - (accumulate_lane(accumulators, stripe, secret), ...); - }(std::make_index_sequence>{}); -} - -constexpr void scramble(accumulator_array &accumulators, std::byte const *secret) noexcept { - for(std::size_t lane = 0; lane < accumulators.size(); ++lane) { - std::uint64_t const accumulator = accumulators[lane] ^ (accumulators[lane] >> scramble_shift); - accumulators[lane] = (accumulator ^ load(secret + (8 * lane))) * primes_32::prime_1; - } -} - constexpr portable_kernel::lanes portable_kernel::load(accumulator_array const &accumulators) noexcept { return accumulators; } constexpr void portable_kernel::store(accumulator_array &accumulators, lanes const &values) noexcept { accumulators = values; } constexpr void portable_kernel::accumulate(lanes &values, std::byte const *stripe, std::byte const *secret) noexcept { - xxh3_detail::accumulate(values, stripe, secret); + [&] [[gnu::always_inline]] (std::index_sequence) { + (accumulate_lane(values, stripe, secret), ...); + }(std::make_index_sequence>{}); } -constexpr void portable_kernel::scramble(lanes &values, std::byte const *secret) noexcept { xxh3_detail::scramble(values, secret); } +constexpr void portable_kernel::scramble(lanes &values, std::byte const *secret) noexcept { + for(std::size_t lane = 0; lane < values.size(); ++lane) { + std::uint64_t const accumulator = values[lane] ^ (values[lane] >> scramble_shift); + values[lane] = (accumulator ^ xxh3_detail::load(secret + (8 * lane))) * primes_32::prime_1; + } +} template constexpr void fold_stripes(accumulator_array &accumulators, std::span data, std::size_t block_stripe, secret_array const &secret, From f4103968809ec3b006cfa9775a846a3bdb3a4f9a Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:12:43 +0200 Subject: [PATCH 18/64] examples(xxh3): file hash, block dedup and seeded hash table --- examples/CMakeLists.txt | 1 + examples/xxh3/CMakeLists.txt | 4 ++++ examples/xxh3/dedup_blocks.cpp | 44 ++++++++++++++++++++++++++++++++++ examples/xxh3/file_hash.cpp | 32 +++++++++++++++++++++++++ examples/xxh3/hash_table.cpp | 39 ++++++++++++++++++++++++++++++ 5 files changed, 120 insertions(+) create mode 100644 examples/xxh3/CMakeLists.txt create mode 100644 examples/xxh3/dedup_blocks.cpp create mode 100644 examples/xxh3/file_hash.cpp create mode 100644 examples/xxh3/hash_table.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index a2f434b..cdc977a 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -3,3 +3,4 @@ add_subdirectory(internet) add_subdirectory(fletcher4) add_subdirectory(murmur3) add_subdirectory(xxhash) +add_subdirectory(xxh3) diff --git a/examples/xxh3/CMakeLists.txt b/examples/xxh3/CMakeLists.txt new file mode 100644 index 0000000..91f9a28 --- /dev/null +++ b/examples/xxh3/CMakeLists.txt @@ -0,0 +1,4 @@ +foreach (example file_hash dedup_blocks hash_table) + add_executable(checksum_example_xxh3_${example} ${example}.cpp) + target_link_libraries(checksum_example_xxh3_${example} PRIVATE checksum::checksum) +endforeach () diff --git a/examples/xxh3/dedup_blocks.cpp b/examples/xxh3/dedup_blocks.cpp new file mode 100644 index 0000000..0535eb4 --- /dev/null +++ b/examples/xxh3/dedup_blocks.cpp @@ -0,0 +1,44 @@ +// Finds the distinct 4 KiB blocks of a buffer by their XXH3-128 hash, as a deduplicating store does. + +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace std::literals; + +// The hash is uniformly distributed, so its lower half is a good bucket index. +struct hash128_hasher { + std::size_t operator()(checksum::xxh3_hash128 const &hash) const noexcept { return static_cast(hash.low); } +}; + +// The XXH3-128 check value of "abc". +static_assert(checksum::xxh3_128_compute("abc"sv) == checksum::xxh3_hash128{.low = 0x78AF5F94892F3950, .high = 0x06B05AB6733A6185}); + +int main() { + constexpr std::size_t block_size = 4096; + constexpr std::size_t block_count = 64; + constexpr std::size_t pattern_count = 5; + + // A disk image whose blocks repeat five patterns. + std::vector image(block_size * block_count); + for(std::size_t index = 0; index < image.size(); ++index) { + std::size_t const pattern = (index / block_size) % pattern_count; + image[index] = static_cast(((index % block_size) * (pattern + 1)) ^ pattern); + } + + // Block number of the first copy of each content. + std::unordered_map first_copy; + for(std::size_t block = 0; block < block_count; ++block) { + std::span const data = std::span(image).subspan(block * block_size, block_size); + first_copy.try_emplace(checksum::xxh3_128_compute(data), block); + } + + std::println("{} blocks, {} distinct, {} bytes saved", block_count, first_copy.size(), (block_count - first_copy.size()) * block_size); + return first_copy.size() == pattern_count ? 0 : 1; +} diff --git a/examples/xxh3/file_hash.cpp b/examples/xxh3/file_hash.cpp new file mode 100644 index 0000000..4773d93 --- /dev/null +++ b/examples/xxh3/file_hash.cpp @@ -0,0 +1,32 @@ +// Computes the XXH3-64 hash of a file in chunks, like `xxhsum -H3`. + +#include + +#include +#include +#include // stderr +#include +#include +#include + +int main(int argument_count, char **arguments) { + if(argument_count != 2) { + std::println(stderr, "usage: {} ", arguments[0]); + return 1; + } + std::ifstream file(arguments[1], std::ios::binary); + if(!file) { + std::println(stderr, "cannot open {}", arguments[1]); + return 1; + } + + // The state is a 336-byte value passed in and out of each update: large chunks keep that copy negligible. + checksum::xxh3_64_state state{}; + std::array buffer{}; + while(file.read(buffer.data(), buffer.size()) || file.gcount() > 0) { + state = checksum::xxh3_update(state, std::span{buffer}.first(static_cast(file.gcount()))); + } + + std::println("XXH3_{:016x} {}", checksum::xxh3_finalize(state), arguments[1]); + return 0; +} diff --git a/examples/xxh3/hash_table.cpp b/examples/xxh3/hash_table.cpp new file mode 100644 index 0000000..fe7af22 --- /dev/null +++ b/examples/xxh3/hash_table.cpp @@ -0,0 +1,39 @@ +// A hash table keyed by strings, hashed with seeded XXH3-64. + +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace std::literals; + +// Hashes keys with a seed chosen per table: tables with different seeds place the same keys differently. The seed does not protect +// against keys crafted to collide. +struct seeded_hasher { + using is_transparent = void; // Lets find() take a std::string_view without building a std::string. + std::uint64_t seed = 0; + std::size_t operator()(std::string_view key) const noexcept { return static_cast(checksum::xxh3_64_compute(key, seed)); } +}; + +// The XXH3-64 check value of "abc", computed at compile time. +static_assert(checksum::xxh3_64_compute("abc"sv) == 0x78AF5F94892F3950); + +int main() { + std::unordered_map> port_by_service(16, seeded_hasher{.seed = 0x9E3779B97F4A7C15}); + port_by_service.emplace("ssh", 22); + port_by_service.emplace("http", 80); + port_by_service.emplace("https", 443); + port_by_service.emplace("mqtt", 1883); + + auto const found = port_by_service.find("https"sv); + if(found == port_by_service.end() || found->second != 443) { + return 1; + } + std::println("https -> {}, hash 0x{:016X}", found->second, checksum::xxh3_64_compute("https"sv, port_by_service.hash_function().seed)); + return 0; +} From 59a3f5ff610a4fb12e34b13d342340d632797176 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:13:33 +0200 Subject: [PATCH 19/64] examples(xxh3): plain words for spelling --- examples/xxh3/file_hash.cpp | 2 +- examples/xxh3/hash_table.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/xxh3/file_hash.cpp b/examples/xxh3/file_hash.cpp index 4773d93..a6d0829 100644 --- a/examples/xxh3/file_hash.cpp +++ b/examples/xxh3/file_hash.cpp @@ -1,4 +1,4 @@ -// Computes the XXH3-64 hash of a file in chunks, like `xxhsum -H3`. +// Computes the XXH3-64 hash of a file in chunks and prints it with the file name. #include diff --git a/examples/xxh3/hash_table.cpp b/examples/xxh3/hash_table.cpp index fe7af22..250eb33 100644 --- a/examples/xxh3/hash_table.cpp +++ b/examples/xxh3/hash_table.cpp @@ -28,7 +28,7 @@ int main() { port_by_service.emplace("ssh", 22); port_by_service.emplace("http", 80); port_by_service.emplace("https", 443); - port_by_service.emplace("mqtt", 1883); + port_by_service.emplace("domain", 53); auto const found = port_by_service.find("https"sv); if(found == port_by_service.end() || found->second != 443) { From edd1a366ff6bf25d136c6171dfee97c3d49db77d Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:13:33 +0200 Subject: [PATCH 20/64] docs(xxh3): aliases, examples and the AArch64 kernel threshold in streaming --- doc/xxhash.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/doc/xxhash.md b/doc/xxhash.md index b02c32b..e4b4650 100644 --- a/doc/xxhash.md +++ b/doc/xxhash.md @@ -16,11 +16,11 @@ using namespace std::literals; // One call, seed 0 or another seed. std::uint32_t small = checksum::xxh32_compute(key); -std::uint64_t hash = checksum::xxh3_compute<64>(std::span(key), 1234); -checksum::xxh3_hash128 wide = checksum::xxh3_compute<128>(std::span(key)); +std::uint64_t hash = checksum::xxh3_64_compute(key, 1234); +checksum::xxh3_hash128 wide = checksum::xxh3_128_compute(key); // Incremental: a message may be split anywhere. -checksum::xxh3_state<64> state{.seed = 1234}; +checksum::xxh3_64_state state{.seed = 1234}; state = checksum::xxh3_update(state, first_part); state = checksum::xxh3_update(state, second_part); std::uint64_t value = checksum::xxh3_finalize(state); @@ -28,11 +28,14 @@ std::uint64_t value = checksum::xxh3_finalize(state); // Compile time. static_assert(checksum::xxh32_compute("abc"sv) == 0x32D153FF); static_assert(checksum::xxh64_compute("abc"sv) == 0x44BC2CF5AD770999); -static_assert(checksum::xxh3_compute<64>("abc"sv) == 0x78AF5F94892F3950); -static_assert(checksum::xxh3_compute<128>("abc"sv) == +static_assert(checksum::xxh3_64_compute("abc"sv) == 0x78AF5F94892F3950); +static_assert(checksum::xxh3_128_compute("abc"sv) == checksum::xxh3_hash128{.low = 0x78AF5F94892F3950, .high = 0x06B05AB6733A6185}); ``` +`examples/xxh3` has complete programs: the XXH3-64 hash of a file read in chunks, deduplication of blocks by their +XXH3-128 hash, and a hash table with seeded XXH3-64. + ## 2. API Both families have the same four names with their own prefix: a state, `update`, `finalize` and `compute`. All @@ -76,6 +79,8 @@ a cache keyed by the hash of its input. | `xxh3_finalize(state)` | The hash of the message folded into `state`; the state is unchanged. | | `xxh3_compute(data, seed = 0)` | `xxh3_finalize(xxh3_update(xxh3_state{.seed = seed}, data))`. | | `xxh3_hash128` | The XXH3-128 hash: `low` and `high`, its lower and upper 64 bits, as `XXH128_hash_t` of the reference. Compares with `==`. | +| `xxh3_64_state`, `xxh3_128_state` | `xxh3_state<64>` and `xxh3_state<128>`. | +| `xxh3_64_compute(data, seed = 0)`, `xxh3_128_compute(data, seed = 0)` | `xxh3_compute<64>` and `xxh3_compute<128>`. `xxh3_update` and `xxh3_finalize` take the width from the state. | `xxh3_state::value_type` is `std::uint64_t` for Width 64 and `xxh3_hash128` for Width 128. The seed is a `std::uint64_t` for both. The hashes always use the default secret; a custom secret cannot be passed. @@ -121,7 +126,7 @@ Inputs up to 240 bytes run straight-line code with no loop and no kernel. Longer | --- | --- | | x86-64 with AVX2 (`-mavx2`, or a `-march` that includes it) | Two 256-bit vectors, every stripe. | | x86-64 without AVX2 (SSE2 is always there) | Four 128-bit vectors, every stripe. | -| AArch64, little-endian | Four lanes in NEON and four in scalar registers, from 448 bytes of whole stripes (messages from 512 bytes). | +| AArch64, little-endian | Four lanes in NEON and four in scalar registers, from 448 bytes of whole stripes in one fold: one-shot messages from 512 bytes, and `xxh3_update` calls that fold that much past the state's 256-byte buffer. | | 32-bit Arm with NEON, little-endian | All eight lanes in NEON, every stripe. | | RISC-V RV64 with the V extension, VLEN ≥ 128 | One register group of eight 64-bit lanes, every stripe. Tested in QEMU, not measured on hardware. | | everything else (Cortex-M, 32-bit Arm without NEON, big-endian, RISC-V without V), or `CHECKSUM_ACCELERATION=OFF` | Portable loop. | From b9994f2448ad19231d5339b5afd6e68807ce22c2 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:17:28 +0200 Subject: [PATCH 21/64] build: GCC-only warning flags only for GCC --- cmake/common_presets.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cmake/common_presets.json b/cmake/common_presets.json index 176a8e8..6b32b40 100644 --- a/cmake/common_presets.json +++ b/cmake/common_presets.json @@ -25,7 +25,8 @@ "CMAKE_CXX_FLAGS_DEBUG": "-g -D_GLIBCXX_ASSERTIONS -fstack-protector-strong -ftrivial-auto-var-init=pattern" }, "environment": { - "CHECKSUM_WARNINGS": "-Wall -Wextra -Wpedantic -Wunused-parameter -Winit-self -Wcast-align -Wconversion -Wnull-dereference -Wduplicated-cond -Wsign-conversion -Wlogical-op -Wno-psabi", + "CHECKSUM_WARNINGS": "-Wall -Wextra -Wpedantic -Wunused-parameter -Winit-self -Wcast-align -Wconversion -Wnull-dereference -Wsign-conversion -Wno-psabi $env{CHECKSUM_GCC_WARNINGS}", + "CHECKSUM_GCC_WARNINGS": "-Wduplicated-cond -Wlogical-op", "CFLAGS": "$env{CHECKSUM_WARNINGS} $env{CHECKSUM_SECTIONS} $env{CHECKSUM_EXTRA_CFLAGS}", "CXXFLAGS": "$env{CHECKSUM_WARNINGS} $env{CHECKSUM_SECTIONS} $env{CHECKSUM_EXTRA_CXXFLAGS}", "CHECKSUM_EXTRA_CFLAGS": "", @@ -49,6 +50,9 @@ "inherits": "gcc-clang-common", "cacheVariables": { "CMAKE_CXX_COMPILER": "clang++" + }, + "environment": { + "CHECKSUM_GCC_WARNINGS": "" } } ], From 7ab772967d9218f6355affef273e67ea4b8d883c Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:17:40 +0200 Subject: [PATCH 22/64] docs(crc): CHECKSUM_EXAMPLES builds every example --- doc/crc.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/crc.md b/doc/crc.md index c8c9f0e..922fcfd 100644 --- a/doc/crc.md +++ b/doc/crc.md @@ -22,7 +22,7 @@ target_link_libraries(app PRIVATE checksum::checksum) | `CHECKSUM_ACCELERATION` | `ON` | Lets `crc_lut_sliced` and `crc_lut_braided` use the CPU instructions that the compiler flags enable (section 7). `OFF` keeps only the portable loops. | | `CHECKSUM_TESTS` | top-level project | Unit tests and negative compile tests (downloads GoogleTest). | | `CHECKSUM_BENCHMARKS` | `OFF` | Benchmarks (downloads Google Benchmark and zlib); on in the `native-*-bench` presets. | -| `CHECKSUM_EXAMPLES` | top-level project | Builds `examples/crc`. | +| `CHECKSUM_EXAMPLES` | top-level project | Builds `examples/`. | Compile and link the application with `-ffunction-sections -fdata-sections` and `-Wl,--gc-sections`: the library compiles the run-time loops of every strategy and register type, and the linker then keeps only the ones the From 038ba5bfc7f2fe612cbd3a4515d9deee06694bd7 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:27:59 +0200 Subject: [PATCH 23/64] refactor(xxhash, xxh3, murmur3): one little-endian load, one XXH64 avalanche --- src/include/checksum/byte_range.hpp | 20 +++++++++++++++ src/include/checksum/murmur3.hpp | 19 +-------------- src/include/checksum/xxh3.hpp | 20 ++++----------- src/include/checksum/xxhash.hpp | 38 +++++++++++------------------ 4 files changed, 40 insertions(+), 57 deletions(-) diff --git a/src/include/checksum/byte_range.hpp b/src/include/checksum/byte_range.hpp index 0d66060..d48a4a0 100644 --- a/src/include/checksum/byte_range.hpp +++ b/src/include/checksum/byte_range.hpp @@ -2,8 +2,10 @@ #define CHECKSUM_BYTE_RANGE_HPP #include +#include #include #include +#include #include #include #include @@ -37,6 +39,9 @@ namespace checksum::detail { // Calls visit(std::span) once for a contiguous range at run time, otherwise once per 64-byte chunk copied to the stack. template constexpr void for_each_chunk(Range &&data, Visitor visit) noexcept; +// Reads a little-endian integer from the first sizeof(Integer) bytes at data. +template constexpr Integer load(std::byte const *data) noexcept; + } // namespace checksum::detail ///@} @@ -73,6 +78,21 @@ template constexpr void for_each_chunk(Range & } } +template constexpr Integer load(std::byte const *data) noexcept { + Integer value = 0; + if consteval { + for(std::size_t index = 0; index < sizeof(Integer); ++index) { + value |= static_cast(std::to_integer(data[index]) << (8 * index)); + } + } else { + std::memcpy(&value, data, sizeof(Integer)); + if constexpr(std::endian::native == std::endian::big) { + value = std::byteswap(value); + } + } + return value; +} + } // namespace checksum::detail #endif // CHECKSUM_BYTE_RANGE_HPP diff --git a/src/include/checksum/murmur3.hpp b/src/include/checksum/murmur3.hpp index 195af33..9a3175d 100644 --- a/src/include/checksum/murmur3.hpp +++ b/src/include/checksum/murmur3.hpp @@ -9,7 +9,6 @@ #include #include #include -#include #include #include #include @@ -108,8 +107,7 @@ template <> struct algorithm_constants<128> { static constexpr std::array avalanche_shifts{33, 33, 33}; }; -// Reads a little-endian integer from the first sizeof(Integer) bytes at data. -template constexpr Integer load(std::byte const *data) noexcept; +using detail::load; // Reads a little-endian integer from the first size bytes at data, size < sizeof(Integer), with fixed-size loads. template constexpr Integer load_partial(std::byte const *data, std::size_t size) noexcept; @@ -147,21 +145,6 @@ constexpr murmur3_state::value_type finish(lane_array lanes, std:: namespace checksum::murmur3_detail { -template constexpr Integer load(std::byte const *data) noexcept { - Integer value = 0; - if consteval { - for(std::size_t index = 0; index < sizeof(Integer); ++index) { - value |= static_cast(std::to_integer(data[index]) << (8 * index)); - } - } else { - std::memcpy(&value, data, sizeof(Integer)); - if constexpr(std::endian::native == std::endian::big) { - value = std::byteswap(value); - } - } - return value; -} - template constexpr Integer load_partial(std::byte const *data, std::size_t size) noexcept { Integer value = 0; std::size_t offset = 0; diff --git a/src/include/checksum/xxh3.hpp b/src/include/checksum/xxh3.hpp index 2aaa060..3aaca2c 100644 --- a/src/include/checksum/xxh3.hpp +++ b/src/include/checksum/xxh3.hpp @@ -153,8 +153,6 @@ std::uint64_t run_time_multiply_fold(std::uint64_t left, std::uint64_t right) no constexpr std::uint64_t avalanche(std::uint64_t hash) noexcept; -constexpr std::uint64_t avalanche_xxh64(std::uint64_t hash) noexcept; - // The default secret with the seed added to its even words and subtracted from its odd ones. constexpr secret_array make_secret(std::uint64_t seed) noexcept; @@ -276,14 +274,6 @@ constexpr std::uint64_t avalanche(std::uint64_t hash) noexcept { return hash ^ (hash >> 32U); } -constexpr std::uint64_t avalanche_xxh64(std::uint64_t hash) noexcept { - hash ^= hash >> static_cast(primes_64::avalanche_shifts[0]); - hash *= primes_64::prime_2; - hash ^= hash >> static_cast(primes_64::avalanche_shifts[1]); - hash *= primes_64::prime_3; - return hash ^ (hash >> static_cast(primes_64::avalanche_shifts[2])); -} - constexpr secret_array make_secret(std::uint64_t seed) noexcept { std::array words = default_secret_words; for(std::size_t index = 0; index < words.size(); ++index) { @@ -368,18 +358,18 @@ template constexpr value hash_small(std::span(input[0]) << 16U) | (std::to_integer(input[length / 2]) << 24U); std::uint64_t const low = (std::uint64_t{secret_xor(secret)} + seed) ^ combined; if constexpr(Width == 64) { - return avalanche_xxh64(low); + return xxhash_detail::avalanche<64>(low); } else { std::uint64_t const high = (std::uint64_t{secret_xor(secret + 8)} - seed) ^ std::rotl(std::byteswap(combined), 13); - return {.low = avalanche_xxh64(low), .high = avalanche_xxh64(high)}; + return {.low = xxhash_detail::avalanche<64>(low), .high = xxhash_detail::avalanche<64>(high)}; } } if constexpr(Width == 64) { constexpr std::size_t offset = 56; - return avalanche_xxh64(seed ^ secret_xor(secret + offset)); + return xxhash_detail::avalanche<64>(seed ^ secret_xor(secret + offset)); } else { - return {.low = avalanche_xxh64(seed ^ secret_xor(secret + 64)), - .high = avalanche_xxh64(seed ^ secret_xor(secret + 64 + 16))}; + return {.low = xxhash_detail::avalanche<64>(seed ^ secret_xor(secret + 64)), + .high = xxhash_detail::avalanche<64>(seed ^ secret_xor(secret + 64 + 16))}; } } diff --git a/src/include/checksum/xxhash.hpp b/src/include/checksum/xxhash.hpp index 58b94c1..fd2441e 100644 --- a/src/include/checksum/xxhash.hpp +++ b/src/include/checksum/xxhash.hpp @@ -9,7 +9,6 @@ #include #include #include -#include #include #include #include @@ -115,8 +114,7 @@ template <> struct algorithm_constants<64> { static constexpr std::array avalanche_shifts{33, 29, 32}; }; -// Reads a little-endian integer from the first sizeof(Integer) bytes at data. -template constexpr Integer load(std::byte const *data) noexcept; +using detail::load; // Mixes one input lane into a lane accumulator. template constexpr word round(word accumulator, word lane) noexcept; @@ -137,6 +135,9 @@ template word stripe_loop(lane_array &lanes, std: // fold_stripes() and converge() if wanted, during constant evaluation, else stripe_loop(). template constexpr word fold_and_converge(lane_array &lanes, std::span data, bool converged) noexcept; +// The final mix of a hash. +template constexpr word avalanche(word hash) noexcept; + // The hash of a message of length bytes: converged holds its stripes if length reaches a stripe, tail holds the rest. template constexpr word finish(word converged, word seed, std::uint64_t length, std::span tail) noexcept; @@ -152,21 +153,6 @@ std::uint32_t run_time_xxh32(std::span data, std::uint32_t seed namespace checksum::xxhash_detail { -template constexpr Integer load(std::byte const *data) noexcept { - Integer value = 0; - if consteval { - for(std::size_t index = 0; index < sizeof(Integer); ++index) { - value |= std::to_integer(data[index]) << (8 * index); - } - } else { - std::memcpy(&value, data, sizeof(Integer)); - if constexpr(std::endian::native == std::endian::big) { - value = std::byteswap(value); - } - } - return value; -} - template constexpr word round(word accumulator, word lane) noexcept { using constants = algorithm_constants; return std::rotl(static_cast>(accumulator + (lane * constants::prime_2)), constants::round_rotation) * constants::prime_1; @@ -211,6 +197,15 @@ constexpr word fold_and_converge(lane_array &lanes, std::span constexpr word avalanche(word hash) noexcept { + using constants = algorithm_constants; + hash ^= hash >> constants::avalanche_shifts[0]; + hash *= constants::prime_2; + hash ^= hash >> constants::avalanche_shifts[1]; + hash *= constants::prime_3; + return hash ^ (hash >> constants::avalanche_shifts[2]); +} + template constexpr word finish(word converged, word seed, std::uint64_t length, std::span tail) noexcept { using constants = algorithm_constants; @@ -239,12 +234,7 @@ constexpr word finish(word converged, word seed, std::uint6 value_type const byte = std::to_integer(*position) * constants::prime_5; hash = std::rotl(static_cast(Width == 32 ? hash + byte : hash ^ byte), constants::byte_rotation) * constants::prime_1; } - hash ^= hash >> constants::avalanche_shifts[0]; - hash *= constants::prime_2; - hash ^= hash >> constants::avalanche_shifts[1]; - hash *= constants::prime_3; - hash ^= hash >> constants::avalanche_shifts[2]; - return hash; + return avalanche(hash); } } // namespace checksum::xxhash_detail From 36baf201ceffbf77b1cae4d2e9229287a5664650 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:19:01 +0200 Subject: [PATCH 24/64] refactor(fletcher, adler32): share the run-time loops Fletcher and Adler-32 now run one portable loop, chunk loop and kernel dispatch from checksum_private/fletcher_loops.hpp, with one reduction bound and one division-free reduction. The public headers keep only the constant-evaluation loop; the run-time path finishes an unfinished Fletcher block in src/. --- src/adler32/sum_loop.cpp | 97 +------ src/fletcher/sum_loop.cpp | 176 +---------- src/include/checksum/fletcher.hpp | 49 +--- .../checksum_private/fletcher_arch.hpp | 86 +----- .../checksum_private/fletcher_loops.hpp | 274 ++++++++++++++++++ 5 files changed, 306 insertions(+), 376 deletions(-) create mode 100644 src/include_private/checksum_private/fletcher_loops.hpp diff --git a/src/adler32/sum_loop.cpp b/src/adler32/sum_loop.cpp index 7e1ae21..c4bbd1c 100644 --- a/src/adler32/sum_loop.cpp +++ b/src/adler32/sum_loop.cpp @@ -1,105 +1,18 @@ -// Run-time loop of the Adler-32 checksum. +// Run-time loop of the Adler-32 checksum: the loops of the Fletcher checksums on bytes, modulo 65521. #include -#include +#include -#include #include #include -#include #include namespace checksum::adler32_detail { -namespace { - -// Largest n with (n+1)(M-1) + 255n(n+1)/2 <= the maximum of std::size_t. Sums start at most at M-1, and n bytes of at most 255 raise sum1 to -// at most M-1 + 255n and sum2 to at most (n+1)(M-1) + 255n(n+1)/2. -constexpr std::size_t bytes_per_reduction() noexcept { - constexpr std::size_t maximum = std::numeric_limits::max(); - std::size_t low = 0; - std::size_t high = std::size_t{1} << ((sizeof(std::size_t) * 4U) - 1U); // n(n+1) and (n+1)(M-1) cannot overflow - while(low < high) { - std::size_t const middle = high - ((high - low) / 2); - std::size_t const start = (middle + 1) * (modulus - 1); - if(middle * (middle + 1) / 2 <= (maximum - start) / 255) { - low = middle; - } else { - high = middle - 1; - } - } - return low; -} - -static_assert(std::numeric_limits::digits != 64 || bytes_per_reduction() == 380'368'439); -static_assert(std::numeric_limits::digits != 32 || bytes_per_reduction() == 5'552); - -// value modulo 65521, without a division: 2^16 is 15 modulo 65521, so the high bits fold onto the low ones. -template Integer reduce(Integer value) noexcept; - -// The portable loop. -[[gnu::always_inline]] inline adler32_state sum_bytes(adler32_state state, std::span data) noexcept; - -// The byte kernel of Fletcher-16, then the portable loop over what it left. Not inlined, so that short inputs run sum_loop() -// without a call. -[[gnu::noinline, maybe_unused]] adler32_state sum_long(adler32_state state, std::span data) noexcept; - -using byte_kernel = fletcher_detail::kernel<8>; - -template Integer reduce(Integer value) noexcept { - while(value > 0xFFFF) { - value = (value & 0xFFFF) + (15 * (value >> 16U)); - } - return reduce_once(static_cast(value)); -} - -[[gnu::always_inline]] inline adler32_state sum_bytes(adler32_state state, std::span data) noexcept { - constexpr std::size_t run = bytes_per_reduction(); - static_assert(run >= 4); - std::size_t sum1 = reduce_once(state.sum1); - std::size_t sum2 = reduce_once(state.sum2); - std::byte const *position = data.data(); - std::size_t remaining = data.size(); - while(remaining != 0) { - std::size_t count = std::min(remaining, run); - remaining -= count; - // Four bytes at a time: sum1 has one addition per group in its dependency chain instead of four. - for(; count >= 4; count -= 4, position += 4) { - std::size_t const first = std::to_integer(position[0]); - std::size_t const second = std::to_integer(position[1]); - std::size_t const third = std::to_integer(position[2]); - std::size_t const fourth = std::to_integer(position[3]); - sum2 += (4 * sum1) + (4 * first) + (3 * second) + (2 * third) + fourth; - sum1 += first + second + third + fourth; - } - for(; count != 0; --count, ++position) { - sum1 += std::to_integer(*position); - sum2 += sum1; - } - sum1 = reduce(sum1); - sum2 = reduce(sum2); - } - return {.sum1 = static_cast(sum1), .sum2 = static_cast(sum2)}; -} - -[[gnu::noinline, maybe_unused]] adler32_state sum_long(adler32_state state, std::span data) noexcept { - if constexpr(byte_kernel::available) { - fletcher_detail::sum_pair sums{.sum1 = state.sum1, .sum2 = state.sum2}; - std::size_t const size = fletcher_detail::sum_chunks<8, modulus>(sums, data); - return sum_bytes({.sum1 = static_cast(sums.sum1), .sum2 = static_cast(sums.sum2)}, data.subspan(size)); - } else { - return sum_bytes(state, data); - } -} - -} // namespace - adler32_state sum_loop(adler32_state state, std::span data) noexcept { - if constexpr(byte_kernel::available) { - return data.size() >= byte_kernel::minimum_size ? sum_long(state, data) : sum_bytes(state, data); - } else { - return sum_bytes(state, data); - } + fletcher_detail::sum_pair const sums = + fletcher_detail::sum_values({.sum1 = reduce_once(state.sum1), .sum2 = reduce_once(state.sum2)}, data); + return {.sum1 = static_cast(sums.sum1), .sum2 = static_cast(sums.sum2)}; } } // namespace checksum::adler32_detail diff --git a/src/fletcher/sum_loop.cpp b/src/fletcher/sum_loop.cpp index fa75790..9dbd3af 100644 --- a/src/fletcher/sum_loop.cpp +++ b/src/fletcher/sum_loop.cpp @@ -1,181 +1,27 @@ // Run-time loop of the Fletcher checksums. #include -#include +#include #include #include -#include -#include #include -#include namespace checksum::fletcher_detail { namespace { -// The widest integer the target adds natively, or 64 bits for the 32-bit blocks of Fletcher-64. -template using accumulator = std::conditional_t; - -// Fletcher-32 on 32-bit targets sums 32-bit words, two blocks each; 64-bit targets keep the 4-block formula on native words. -template constexpr bool sums_words = Width == 32 && std::numeric_limits::digits == 32; - -// Largest n with M * (1 + n(n+3)/2) <= the accumulator's maximum. Sums start at most at M, and n blocks of at most M raise sum1 to at most -// (n+1)M and sum2 to at most M(1 + n(n+3)/2). -template constexpr std::size_t blocks_per_reduction() noexcept { - using integer = accumulator; - constexpr std::uint64_t quotient = std::numeric_limits::max() / modulus; - constexpr std::uint64_t limit = quotient - 1; - integer low = 0; - integer high = integer{1} << ((sizeof(integer) * 4U) - 1U); // n(n+3) cannot overflow - while(low < high) { - integer const middle = high - ((high - low) / 2); - if(middle * (middle + 3) / 2 <= limit) { - low = middle; - } else { - high = middle - 1; - } - } - return static_cast(low); -} - -static_assert(std::numeric_limits::digits != 64 || blocks_per_reduction<16>() == 380'368'695); -static_assert(std::numeric_limits::digits != 64 || blocks_per_reduction<32>() == 23'726'745); -static_assert(std::numeric_limits::digits != 32 || blocks_per_reduction<16>() == 5'802); -static_assert(std::numeric_limits::digits != 32 || blocks_per_reduction<32>() == 360); -static_assert(blocks_per_reduction<64>() == 92'680); - -// The little-endian Integer of at most 32 bits at data. Compilers merge the bytes into one load where unaligned loads are -// allowed, and elsewhere load single bytes instead of calling memcpy. -template Integer load(std::byte const *data) noexcept; - -// The portable loop. -template -[[gnu::always_inline]] inline fletcher_state sum_blocks(fletcher_state state, std::span data) noexcept; - -// The CPU kernel, then the portable loop over what it left. Not inlined, so that short inputs run sum_any() without a call. -template -[[gnu::noinline, maybe_unused]] fletcher_state sum_long(fletcher_state state, std::span data) noexcept; - -// The kernel from its minimum size, else the portable loop. -template fletcher_state sum_any(fletcher_state state, std::span data) noexcept; - -template Integer load(std::byte const *data) noexcept { - auto const byte = [data](unsigned index) { return std::to_integer(data[index]) << (8U * index); }; - if constexpr(sizeof(Integer) == 1) { - return std::to_integer(data[0]); - } else if constexpr(sizeof(Integer) == 2) { - return static_cast(byte(0) | byte(1)); - } else { - static_assert(sizeof(Integer) == 4); - return byte(0) | byte(1) | byte(2) | byte(3); - } -} - -template -[[gnu::always_inline]] inline fletcher_state sum_blocks(fletcher_state state, std::span data) noexcept { - using sum_type = fletcher_state::sum_type; - constexpr std::size_t size = block_size; - constexpr std::size_t run = blocks_per_reduction(); - static_assert(run >= 8); - // In a run of w words, previous is at most 2M * w(w - 1) / 2. - static_assert(!sums_words || modulus * (run / 2) * ((run / 2) - 1) <= std::numeric_limits::max()); - accumulator sum1 = state.sum1; - accumulator sum2 = state.sum2; - std::byte const *position = data.data(); - std::size_t blocks = data.size() / size; - while(blocks != 0) { - std::size_t count = std::min(blocks, run); - blocks -= count; - if constexpr(sums_words) { - // One block first if that aligns the words. A word adds 2 * sum1 + 2 * first half + second half to sum2, so per word - // previous += sum, sum adds both halves and first_halves the first half. - if((reinterpret_cast(position) & 2U) != 0) { - sum1 += load(position); - sum2 += sum1; - position += size; - --count; - } - std::size_t const words = (count / 8) * 4; - std::uint32_t sum = 0; - std::uint32_t previous = 0; - std::uint32_t first_halves = 0; - for(; count >= 8; count -= 8, position += 16) { - auto const first = load(position); - auto const second = load(position + 4); - auto const third = load(position + 8); - auto const fourth = load(position + 12); - previous += sum; - sum += (first & 0xFFFFU) + (first >> 16U); - first_halves += first & 0xFFFFU; - previous += sum; - sum += (second & 0xFFFFU) + (second >> 16U); - first_halves += second & 0xFFFFU; - previous += sum; - sum += (third & 0xFFFFU) + (third >> 16U); - first_halves += third & 0xFFFFU; - previous += sum; - sum += (fourth & 0xFFFFU) + (fourth >> 16U); - first_halves += fourth & 0xFFFFU; - } - // With previous reduced, sum2 stays below 1300 * M. - sum2 += (2 * words * sum1) + (2 * static_cast>(reduce(previous))) + sum + first_halves; - sum1 += sum; - } else { - // Four blocks at a time: sum1 has one addition per group in its dependency chain instead of four. With 64-bit sums on a - // 32-bit target the multiplications cost more than the chain, so the blocks are added one by one. - for(; count >= 4; count -= 4, position += 4 * size) { - accumulator const first = load(position); - accumulator const second = load(position + size); - accumulator const third = load(position + (2 * size)); - accumulator const fourth = load(position + (3 * size)); - if constexpr(sizeof(accumulator) > sizeof(std::size_t)) { - sum1 += first; - sum2 += sum1; - sum1 += second; - sum2 += sum1; - sum1 += third; - sum2 += sum1; - sum1 += fourth; - sum2 += sum1; - } else { - sum2 += (4 * sum1) + (4 * first) + (3 * second) + (2 * third) + fourth; - sum1 += first + second + third + fourth; - } - } - } - for(; count != 0; --count, position += size) { - sum1 += load(position); - sum2 += sum1; - } - sum1 = static_cast>(reduce(sum1)); - sum2 = static_cast>(reduce(sum2)); - } - // The bytes of an unfinished block, at most 3, go to sum1 only. - std::size_t const tail = data.size() % size; - for(std::size_t index = 0; index < tail; ++index) { - sum1 += std::to_integer>(position[index]) << (8 * index); - } - return {.sum1 = static_cast(reduce(sum1)), - .sum2 = static_cast(reduce(sum2)), - .block_offset = static_cast(tail)}; -} - -template -[[gnu::noinline, maybe_unused]] fletcher_state sum_long(fletcher_state state, std::span data) noexcept { - using sum_type = fletcher_state::sum_type; - sum_pair sums{.sum1 = state.sum1, .sum2 = state.sum2}; - std::size_t const size = sum_chunks>(sums, data); - state = {.sum1 = static_cast(sums.sum1), .sum2 = static_cast(sums.sum2), .block_offset = 0}; - return sum_blocks(state, data.subspan(size)); -} - +// Finishes an unfinished block byte by byte, sums the whole blocks with the shared loops, and adds the bytes of a last +// unfinished block to sum1. template fletcher_state sum_any(fletcher_state state, std::span data) noexcept { - if constexpr(kernel::available) { - return data.size() >= kernel::minimum_size ? sum_long(state, data) : sum_blocks(state, data); - } else { - return sum_blocks(state, data); - } + using sum_type = fletcher_state::sum_type; + constexpr unsigned size = block_size; + std::size_t const head = std::min(data.size(), (size - (state.block_offset % size)) % size); + state = update_bytes(state, data.first(head)); + data = data.subspan(head); + sum_pair const sums = sum_values>({.sum1 = state.sum1, .sum2 = state.sum2}, data); + state = {.sum1 = static_cast(sums.sum1), .sum2 = static_cast(sums.sum2), .block_offset = state.block_offset}; + return update_bytes(state, data.last(data.size() % size)); } } // namespace diff --git a/src/include/checksum/fletcher.hpp b/src/include/checksum/fletcher.hpp index b4ea391..b9362a3 100644 --- a/src/include/checksum/fletcher.hpp +++ b/src/include/checksum/fletcher.hpp @@ -3,7 +3,6 @@ #include -#include #include #include #include @@ -68,16 +67,13 @@ template inline constexpr unsigned block_size = Width / 16; // M = 2^(Width/2) - 1. template inline constexpr std::uint64_t modulus = (std::uint64_t{1} << (Width / 2)) - 1; -// value modulo M, in 0..M-1. -template constexpr std::uint64_t reduce(std::uint64_t value) noexcept; +// value modulo M for value < 2M. +template constexpr std::uint64_t reduce_once(std::uint64_t value) noexcept; -// (sum + value) modulo M for sum < M and value <= M. -template constexpr std::uint64_t add(std::uint64_t sum, std::uint64_t value) noexcept; - -// Folds data byte by byte; the constant-evaluation loop, also used to finish an unfinished block at run time. +// Folds data byte by byte; the constant-evaluation loop, also used at run time for the bytes of an unfinished block. template constexpr fletcher_state update_bytes(fletcher_state state, std::span data) noexcept; -// The same fold at run time for a state at a block boundary, defined in src/fletcher/sum_loop.cpp. +// The same fold at run time, defined in src/fletcher/sum_loop.cpp. fletcher_state<16> sum_loop(fletcher_state<16> state, std::span data) noexcept; fletcher_state<32> sum_loop(fletcher_state<32> state, std::span data) noexcept; fletcher_state<64> sum_loop(fletcher_state<64> state, std::span data) noexcept; @@ -89,30 +85,20 @@ fletcher_state<64> sum_loop(fletcher_state<64> state, std::span namespace checksum::fletcher_detail { -// 2^(Width/2) is 1 modulo M, so the high bits fold onto the low ones; each fold makes value smaller until it is at most M. -template constexpr std::uint64_t reduce(std::uint64_t value) noexcept { - while(value > modulus) { - std::uint64_t const low = value & modulus; - value = low + (value >> (Width / 2)); - } - return value == modulus ? 0 : value; -} - -template constexpr std::uint64_t add(std::uint64_t sum, std::uint64_t value) noexcept { - sum += value; - return sum >= modulus ? sum - modulus : sum; +template constexpr std::uint64_t reduce_once(std::uint64_t value) noexcept { + return value >= modulus ? value - modulus : value; } template constexpr fletcher_state update_bytes(fletcher_state state, std::span data) noexcept { using sum_type = fletcher_state::sum_type; - std::uint64_t sum1 = reduce(state.sum1); - std::uint64_t sum2 = reduce(state.sum2); + std::uint64_t sum1 = reduce_once(state.sum1); + std::uint64_t sum2 = reduce_once(state.sum2); unsigned offset = state.block_offset % block_size; for(std::byte const byte : data) { - sum1 = add(sum1, std::to_integer(byte) << (8 * offset)); + sum1 = reduce_once(sum1 + (std::to_integer(byte) << (8 * offset))); if(++offset == block_size) { offset = 0; - sum2 = add(sum2, sum1); + sum2 = reduce_once(sum2 + sum1); } } return {.sum1 = static_cast(sum1), .sum2 = static_cast(sum2), .block_offset = static_cast(offset)}; @@ -126,14 +112,7 @@ template constexpr fletcher_state fletcher_update(fletch if consteval { return fletcher_detail::update_bytes(state, data); } else { - constexpr unsigned block_size = fletcher_detail::block_size; - // Bytes that finish an unfinished block; the loop starts at a block boundary. - std::size_t const head = std::min(data.size(), (block_size - (state.block_offset % block_size)) % block_size); - state = fletcher_detail::update_bytes(state, data.first(head)); - if(head == data.size()) { - return state; - } - return fletcher_detail::sum_loop(state, data.subspan(head)); + return fletcher_detail::sum_loop(state, data); } } @@ -144,11 +123,11 @@ template constexpr fletcher_state flet template constexpr fletcher_state::value_type fletcher_finalize(fletcher_state state) noexcept { using value_type = fletcher_state::value_type; - std::uint64_t const sum1 = fletcher_detail::reduce(state.sum1); - std::uint64_t sum2 = fletcher_detail::reduce(state.sum2); + std::uint64_t const sum1 = fletcher_detail::reduce_once(state.sum1); + std::uint64_t sum2 = fletcher_detail::reduce_once(state.sum2); // The zero padding adds nothing to sum1, but the padded block still adds sum1 to sum2. if(state.block_offset % fletcher_detail::block_size != 0) { - sum2 = fletcher_detail::add(sum2, sum1); + sum2 = fletcher_detail::reduce_once(sum2 + sum1); } return static_cast((sum2 << (Width / 2)) | sum1); } diff --git a/src/include_private/checksum_private/fletcher_arch.hpp b/src/include_private/checksum_private/fletcher_arch.hpp index 830a240..ec1d4d6 100644 --- a/src/include_private/checksum_private/fletcher_arch.hpp +++ b/src/include_private/checksum_private/fletcher_arch.hpp @@ -8,17 +8,12 @@ // - available = true; static chunk_sums sum(std::byte const *data, std::size_t blocks), for 1 to max_blocks blocks // - block_size: bytes per block; max_blocks // - minimum_size: shortest input for the kernel (max: never) -// - for kernel<8> also alignment: sum_chunks() adds single bytes up to an address of that alignment before the kernel +// - for kernel<8> also alignment: sum_chunks() of fletcher_loops.hpp adds single bytes up to an address of that alignment +// before the kernel #include -#include -#include -#include #include -#include -#include -#include namespace checksum::fletcher_detail { @@ -28,21 +23,6 @@ struct chunk_sums { std::uint64_t weighted = 0; }; -// Both sums of a checksum, each below 2^32. -struct sum_pair { - std::uint64_t sum1 = 0; - std::uint64_t sum2 = 0; -}; - -// Adds the whole kernel blocks at the start of data to sums (each below 2^32), a chunk of at most max_blocks blocks per -// kernel call, each sum reduced modulo Modulus after every chunk. Returns the number of bytes taken; inlined into its one caller. -template -[[gnu::always_inline]] inline std::size_t sum_chunks(sum_pair &sums, std::span data) noexcept; - -// value modulo Modulus. The high half of a 64-bit value folds onto the low one with the weight 2^32 modulo Modulus, so that -// the constant % is a 32-bit multiplication on every target. -template Word reduce_chunk(Word value) noexcept; - } // namespace checksum::fletcher_detail #if defined(CHECKSUM_ARCH_X86_64) @@ -53,66 +33,4 @@ template Word reduce_chunk(Word value) noexc #include #endif -namespace checksum::fletcher_detail { - -template Word reduce_chunk(Word value) noexcept { - if constexpr(sizeof(Word) > sizeof(std::uint32_t)) { - constexpr std::uint64_t high_weight = (std::uint64_t{1} << 32U) % Modulus; - while((value >> 32U) != 0) { - value = (value & 0xFFFF'FFFFU) + ((value >> 32U) * high_weight); - } - } - return static_cast(value) % static_cast(Modulus); -} - -template -[[gnu::always_inline]] inline std::size_t sum_chunks(sum_pair &sums, std::span data) noexcept { - using chunk_kernel = kernel; - constexpr std::uint64_t values_per_block = chunk_kernel::block_size * 8 / Bits; - constexpr std::uint64_t max_values = chunk_kernel::max_blocks * values_per_block; - constexpr std::uint64_t largest_value = (std::uint64_t{1} << Bits) - 1; - constexpr std::uint64_t largest_weighted = max_values * (max_values + 1) / 2 * largest_value; - constexpr std::uint64_t largest_sum = std::bit_ceil(Modulus) - 1; - // The weighted sum of a chunk fits 64 bits, and so does sum2 plus max_values * sum1. - static_assert(max_values * (max_values + 1) / 2 <= std::numeric_limits::max() / largest_value); - static_assert(max_values <= std::uint64_t{1} << 31U); - // 32-bit arithmetic where every intermediate result fits, so that 32-bit targets reduce without 64-bit operations. - constexpr std::uint64_t largest_word = std::numeric_limits::max(); - using word = std::conditional_t; - auto sum1 = static_cast(sums.sum1); - auto sum2 = static_cast(sums.sum2); - std::byte const *position = data.data(); - std::size_t head = 0; - if constexpr(Bits == 8) { - if constexpr(chunk_kernel::alignment > 1) { - // Bytes are single blocks, so the bytes before the alignment of the kernel can go first, one by one. - head = std::min(data.size(), (0 - reinterpret_cast(position)) & (chunk_kernel::alignment - 1)); - for(std::byte const byte : data.first(head)) { - sum1 += std::to_integer(byte); - sum2 += sum1; - } - sum1 = reduce_chunk(sum1); - sum2 = reduce_chunk(sum2); - position += head; - } - } - std::size_t blocks = (data.size() - head) / chunk_kernel::block_size; - std::size_t const size = head + (blocks * chunk_kernel::block_size); - while(blocks != 0) { - std::size_t const count = std::min(blocks, chunk_kernel::max_blocks); - chunk_sums const chunk = chunk_kernel::sum(position, count); - sum2 = - reduce_chunk(static_cast(sum2 + (count * values_per_block * sum1) + reduce_chunk(static_cast(chunk.weighted)))); - sum1 = reduce_chunk(static_cast(sum1 + chunk.sum)); - blocks -= count; - position += count * chunk_kernel::block_size; - } - sums = {.sum1 = sum1, .sum2 = sum2}; - return size; -} - -} // namespace checksum::fletcher_detail - #endif // CHECKSUM_PRIVATE_FLETCHER_ARCH_HPP diff --git a/src/include_private/checksum_private/fletcher_loops.hpp b/src/include_private/checksum_private/fletcher_loops.hpp new file mode 100644 index 0000000..548610b --- /dev/null +++ b/src/include_private/checksum_private/fletcher_loops.hpp @@ -0,0 +1,274 @@ +#ifndef CHECKSUM_PRIVATE_FLETCHER_LOOPS_HPP +#define CHECKSUM_PRIVATE_FLETCHER_LOOPS_HPP + +// Run-time loops shared by src/fletcher/sum_loop.cpp and src/adler32/sum_loop.cpp: the portable loop over little-endian +// values, the chunk loop of the kernels of fletcher_arch.hpp and the choice between them. Fletcher-N sums values of N/2 +// bits modulo 2^(N/2) - 1, Adler-32 bytes modulo 65521. + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace checksum::fletcher_detail { + +// Both sums of a checksum, each below the modulus. +struct sum_pair { + std::uint64_t sum1 = 0; + std::uint64_t sum2 = 0; +}; + +// Internal linkage lets compilers inline these loops fully into each source; with external linkage they keep an +// out-of-line copy. +// NOLINTNEXTLINE(misc-anonymous-namespace-in-header): a private header, included only by src/fletcher and src/adler32. +namespace { + +// Largest n with (n + 1)(Modulus - 1) + largest_value * n(n + 1) / 2 <= the maximum of Integer: sums below Modulus stay within +// Integer while they add n values of at most largest_value, sum2 after each. +template constexpr std::size_t values_per_reduction(std::uint64_t largest_value) noexcept; + +// value modulo Modulus without a division: with k the bit width of Modulus, the bits from k on fold onto the low ones with the +// weight 2^k - Modulus. +template Integer reduce(Integer value) noexcept; + +// value modulo Modulus for the kernel chunks. The high half of a 64-bit value folds onto the low one with the weight 2^32 modulo +// Modulus, so that the constant % is a 32-bit multiplication on every target. +template Word reduce_chunk(Word value) noexcept; + +// The little-endian Value of at most 32 bits at data. Compilers merge the bytes into one load where unaligned loads are allowed, +// and elsewhere load single bytes instead of calling memcpy. +template Value load(std::byte const *data) noexcept; + +// Adds the whole kernel blocks at the start of data to sums, a chunk of at most max_blocks blocks per kernel call, each sum +// reduced after every chunk. Returns the number of bytes taken; inlined into its one caller. +template +[[gnu::always_inline]] inline std::size_t sum_chunks(sum_pair &sums, std::span data) noexcept; + +// The portable loop over the whole Values of data. +template +[[gnu::always_inline]] inline sum_pair sum_portable(sum_pair sums, std::span data) noexcept; + +// The CPU kernel, then the portable loop over what it left. Not inlined, so that short inputs run sum_values() without a call. +template +[[gnu::noinline, maybe_unused]] sum_pair sum_long(sum_pair sums, std::span data) noexcept; + +// Adds the whole Values of data to sums: the kernel from its minimum size, else the portable loop. +template sum_pair sum_values(sum_pair sums, std::span data) noexcept; + +template constexpr std::size_t values_per_reduction(std::uint64_t largest_value) noexcept { + constexpr std::uint64_t maximum = std::numeric_limits::max(); + std::uint64_t low = 0; + std::uint64_t high = std::uint64_t{1} << ((std::numeric_limits::digits / 2) - 1); // n(n+1) and (n+1)(Modulus-1) cannot overflow + while(low < high) { + std::uint64_t const middle = high - ((high - low) / 2); + std::uint64_t const start = (middle + 1) * (Modulus - 1); + if(start <= maximum && middle * (middle + 1) / 2 <= (maximum - start) / largest_value) { + low = middle; + } else { + high = middle - 1; + } + } + return static_cast(low); +} + +static_assert(std::numeric_limits::digits != 64 || values_per_reduction(255) == 380'368'695); +static_assert(std::numeric_limits::digits != 64 || values_per_reduction(65'535) == 23'726'745); +static_assert(std::numeric_limits::digits != 64 || values_per_reduction(255) == 380'368'439); +static_assert(std::numeric_limits::digits != 32 || values_per_reduction(255) == 5'802); +static_assert(std::numeric_limits::digits != 32 || values_per_reduction(65'535) == 360); +static_assert(std::numeric_limits::digits != 32 || values_per_reduction(255) == 5'552); +static_assert(values_per_reduction(0xFFFF'FFFF) == 92'680); + +template Integer reduce(Integer value) noexcept { + constexpr int bits = std::bit_width(Modulus); + if constexpr(bits < std::numeric_limits::digits) { + constexpr Integer low_bits = (Integer{1} << bits) - 1; + constexpr Integer high_weight = (Integer{1} << bits) - Modulus; + while((value >> bits) != 0) { + value = (value & low_bits) + (high_weight * (value >> bits)); + } + } + return value >= Modulus ? static_cast(value - Modulus) : value; +} + +template Word reduce_chunk(Word value) noexcept { + if constexpr(sizeof(Word) > sizeof(std::uint32_t)) { + constexpr std::uint64_t high_weight = (std::uint64_t{1} << 32U) % Modulus; + while((value >> 32U) != 0) { + value = (value & 0xFFFF'FFFFU) + ((value >> 32U) * high_weight); + } + } + return static_cast(value) % static_cast(Modulus); +} + +template Value load(std::byte const *data) noexcept { + auto const byte = [data](unsigned index) { return std::to_integer(data[index]) << (8U * index); }; + if constexpr(sizeof(Value) == 1) { + return std::to_integer(data[0]); + } else if constexpr(sizeof(Value) == 2) { + return static_cast(byte(0) | byte(1)); + } else { + static_assert(sizeof(Value) == 4); + return byte(0) | byte(1) | byte(2) | byte(3); + } +} + +template +[[gnu::always_inline]] inline std::size_t sum_chunks(sum_pair &sums, std::span data) noexcept { + constexpr unsigned bits = std::numeric_limits::digits; + using chunk_kernel = kernel; + constexpr std::uint64_t values_per_block = chunk_kernel::block_size / sizeof(Value); + constexpr std::uint64_t max_values = chunk_kernel::max_blocks * values_per_block; + constexpr std::uint64_t largest_value = std::numeric_limits::max(); + constexpr std::uint64_t largest_weighted = max_values * (max_values + 1) / 2 * largest_value; + constexpr std::uint64_t largest_sum = std::bit_ceil(Modulus) - 1; + // The weighted sum of a chunk fits 64 bits, and so does sum2 plus max_values * sum1. + static_assert(max_values * (max_values + 1) / 2 <= std::numeric_limits::max() / largest_value); + static_assert(max_values <= std::uint64_t{1} << 31U); + // 32-bit arithmetic where every intermediate result fits, so that 32-bit targets reduce without 64-bit operations. + constexpr std::uint64_t largest_word = std::numeric_limits::max(); + using word = std::conditional_t; + auto sum1 = static_cast(sums.sum1); + auto sum2 = static_cast(sums.sum2); + std::byte const *position = data.data(); + std::size_t head = 0; + if constexpr(bits == 8) { + if constexpr(chunk_kernel::alignment > 1) { + // Bytes are single blocks, so the bytes before the alignment of the kernel can go first, one by one. + head = std::min(data.size(), (0 - reinterpret_cast(position)) & (chunk_kernel::alignment - 1)); + for(std::byte const byte : data.first(head)) { + sum1 += std::to_integer(byte); + sum2 += sum1; + } + sum1 = reduce_chunk(sum1); + sum2 = reduce_chunk(sum2); + position += head; + } + } + std::size_t blocks = (data.size() - head) / chunk_kernel::block_size; + std::size_t const size = head + (blocks * chunk_kernel::block_size); + while(blocks != 0) { + std::size_t const count = std::min(blocks, chunk_kernel::max_blocks); + chunk_sums const chunk = chunk_kernel::sum(position, count); + sum2 = + reduce_chunk(static_cast(sum2 + (count * values_per_block * sum1) + reduce_chunk(static_cast(chunk.weighted)))); + sum1 = reduce_chunk(static_cast(sum1 + chunk.sum)); + blocks -= count; + position += count * chunk_kernel::block_size; + } + sums = {.sum1 = sum1, .sum2 = sum2}; + return size; +} + +template +[[gnu::always_inline]] inline sum_pair sum_portable(sum_pair sums, std::span data) noexcept { + // The widest integer the target adds natively, or 64 bits for 32-bit values. + using accumulator = std::conditional_t; + // 32-bit targets sum 16-bit values as 32-bit words, two values each; 64-bit targets keep the 4-value formula on native words. + constexpr bool sums_words = sizeof(Value) == 2 && std::numeric_limits::digits == 32; + constexpr std::size_t size = sizeof(Value); + constexpr std::size_t run = values_per_reduction(std::numeric_limits::max()); + static_assert(run >= 8); + // In a run of w words, previous is at most 2M * w(w - 1) / 2. + static_assert(!sums_words || Modulus * (run / 2) * ((run / 2) - 1) <= std::numeric_limits::max()); + auto sum1 = static_cast(sums.sum1); + auto sum2 = static_cast(sums.sum2); + std::byte const *position = data.data(); + std::size_t values = data.size() / size; + while(values != 0) { + std::size_t count = std::min(values, run); + values -= count; + if constexpr(sums_words) { + // One value first if that aligns the words. A word adds 2 * sum1 + 2 * first half + second half to sum2, so per word + // previous += sum, sum adds both halves and first_halves the first half. + if((reinterpret_cast(position) & 2U) != 0) { + sum1 += load(position); + sum2 += sum1; + position += size; + --count; + } + std::size_t const words = (count / 8) * 4; + std::uint32_t sum = 0; + std::uint32_t previous = 0; + std::uint32_t first_halves = 0; + for(; count >= 8; count -= 8, position += 16) { + auto const first = load(position); + auto const second = load(position + 4); + auto const third = load(position + 8); + auto const fourth = load(position + 12); + previous += sum; + sum += (first & 0xFFFFU) + (first >> 16U); + first_halves += first & 0xFFFFU; + previous += sum; + sum += (second & 0xFFFFU) + (second >> 16U); + first_halves += second & 0xFFFFU; + previous += sum; + sum += (third & 0xFFFFU) + (third >> 16U); + first_halves += third & 0xFFFFU; + previous += sum; + sum += (fourth & 0xFFFFU) + (fourth >> 16U); + first_halves += fourth & 0xFFFFU; + } + // With previous reduced, sum2 stays below 1300 * M. + sum2 += (2 * words * sum1) + (2 * static_cast(reduce(previous))) + sum + first_halves; + sum1 += sum; + } else { + // Four values at a time: sum1 has one addition per group in its dependency chain instead of four. With 64-bit sums on a + // 32-bit target the multiplications cost more than the chain, so the values are added one by one. + for(; count >= 4; count -= 4, position += 4 * size) { + accumulator const first = load(position); + accumulator const second = load(position + size); + accumulator const third = load(position + (2 * size)); + accumulator const fourth = load(position + (3 * size)); + if constexpr(sizeof(accumulator) > sizeof(std::size_t)) { + sum1 += first; + sum2 += sum1; + sum1 += second; + sum2 += sum1; + sum1 += third; + sum2 += sum1; + sum1 += fourth; + sum2 += sum1; + } else { + sum2 += (4 * sum1) + (4 * first) + (3 * second) + (2 * third) + fourth; + sum1 += first + second + third + fourth; + } + } + } + for(; count != 0; --count, position += size) { + sum1 += load(position); + sum2 += sum1; + } + sum1 = reduce(sum1); + sum2 = reduce(sum2); + } + return {.sum1 = sum1, .sum2 = sum2}; +} + +template +[[gnu::noinline, maybe_unused]] sum_pair sum_long(sum_pair sums, std::span data) noexcept { + std::size_t const size = sum_chunks(sums, data); + return sum_portable(sums, data.subspan(size)); +} + +template sum_pair sum_values(sum_pair sums, std::span data) noexcept { + using value_kernel = kernel::digits>; + if constexpr(value_kernel::available) { + return data.size() >= value_kernel::minimum_size ? sum_long(sums, data) : sum_portable(sums, data); + } else { + return sum_portable(sums, data); + } +} + +} // namespace + +} // namespace checksum::fletcher_detail + +#endif // CHECKSUM_PRIVATE_FLETCHER_LOOPS_HPP From c9782e5cdc219cd73665a32d581743e321b85471 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:19:01 +0200 Subject: [PATCH 25/64] feat(fletcher): fletcher16, fletcher32 and fletcher64 aliases --- src/include/checksum/fletcher.hpp | 30 ++++++++++++++++++++++++++++++ tests/unit_tests/ut_fletcher.cpp | 18 ++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/include/checksum/fletcher.hpp b/src/include/checksum/fletcher.hpp index b9362a3..a3013f6 100644 --- a/src/include/checksum/fletcher.hpp +++ b/src/include/checksum/fletcher.hpp @@ -56,6 +56,24 @@ template [[nodiscard]] constexpr fletcher_state::value_t /// fletcher_finalize(fletcher_update(fletcher_state{}, data)) for a byte range. template [[nodiscard]] constexpr fletcher_state::value_type fletcher_compute(Range &&data) noexcept; +/// Running Fletcher-16 checksum. +using fletcher16_state = fletcher_state<16>; + +/// Running Fletcher-32 checksum. +using fletcher32_state = fletcher_state<32>; + +/// Running Fletcher-64 checksum. +using fletcher64_state = fletcher_state<64>; + +/// fletcher_compute<16>(data). +template [[nodiscard]] constexpr std::uint16_t fletcher16_compute(Range &&data) noexcept; + +/// fletcher_compute<32>(data). +template [[nodiscard]] constexpr std::uint32_t fletcher32_compute(Range &&data) noexcept; + +/// fletcher_compute<64>(data). +template [[nodiscard]] constexpr std::uint64_t fletcher64_compute(Range &&data) noexcept; + } // namespace checksum /// Implementation details; not part of the public API. @@ -140,6 +158,18 @@ template constexpr fletcher_state::val return fletcher_finalize(fletcher_update(fletcher_state{}, std::forward(data))); } +template constexpr std::uint16_t fletcher16_compute(Range &&data) noexcept { + return fletcher_compute<16>(std::forward(data)); +} + +template constexpr std::uint32_t fletcher32_compute(Range &&data) noexcept { + return fletcher_compute<32>(std::forward(data)); +} + +template constexpr std::uint64_t fletcher64_compute(Range &&data) noexcept { + return fletcher_compute<64>(std::forward(data)); +} + } // namespace checksum #endif // CHECKSUM_FLETCHER_HPP diff --git a/tests/unit_tests/ut_fletcher.cpp b/tests/unit_tests/ut_fletcher.cpp index b0d61b2..35dabd2 100644 --- a/tests/unit_tests/ut_fletcher.cpp +++ b/tests/unit_tests/ut_fletcher.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -31,6 +32,12 @@ static_assert(fletcher_compute<64>("abcdef"sv) == 0xC8C72B276463C8C6); static_assert(fletcher_compute<64>("abcdefgh"sv) == 0x312E2B28CCCAC8C6); static_assert(fletcher_compute<32>(std::span{}) == 0); +// The aliases of each width are the generic forms. +static_assert(std::same_as> && std::same_as> && + std::same_as>); +static_assert(fletcher16_compute("abcde"sv) == 0xC8F0 && fletcher32_compute("abcde"sv) == 0xF04FC729 && + fletcher64_compute("abcde"sv) == 0xC8C6C527646362C6); + // Independent model: whole blocks read byte by byte with zero padding, each sum reduced with %. template std::uint64_t reference(std::span data) { constexpr std::size_t block_size = Width / 16; @@ -80,6 +87,17 @@ TEST(fletcher_vectors, published_examples) { EXPECT_EQ(fletcher_compute<64>("abcdefgh"sv), 0x312E2B28CCCAC8C6); } +TEST(fletcher_vectors, aliases) { + auto const data = random_bytes(300, 8); + auto const message = std::span(data); + EXPECT_EQ(fletcher16_compute(message), fletcher_compute<16>(message)); + EXPECT_EQ(fletcher32_compute(message), fletcher_compute<32>(message)); + EXPECT_EQ(fletcher64_compute(message), fletcher_compute<64>(message)); + EXPECT_EQ(fletcher16_compute(data), fletcher_compute<16>(message)); + EXPECT_EQ(fletcher32_compute(std::list(data.begin(), data.end())), fletcher_compute<32>(message)); + EXPECT_EQ(fletcher64_compute("123456789"sv), fletcher_compute<64>("123456789"sv)); +} + // All lengths past the kernel thresholds and a few kernel blocks, at every alignment of a vector. TYPED_TEST(fletcher, matches_model) { constexpr unsigned width = TypeParam::value; From 11bb98d1c827a9e7937e684be084f3d8f4bef112 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:21:22 +0200 Subject: [PATCH 26/64] refactor(adler32): start compute from {} like the Internet checksum --- src/include/checksum/adler32.hpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/include/checksum/adler32.hpp b/src/include/checksum/adler32.hpp index 36b6ac7..dcc2e3b 100644 --- a/src/include/checksum/adler32.hpp +++ b/src/include/checksum/adler32.hpp @@ -38,10 +38,10 @@ template [[nodiscard]] constexpr adler32_state adler32_update /// The checksum of state. [[nodiscard]] constexpr std::uint32_t adler32_finalize(adler32_state state) noexcept; -/// adler32_finalize(adler32_update(adler32_state{}, data)). +/// adler32_finalize(adler32_update({}, data)). [[nodiscard]] constexpr std::uint32_t adler32_compute(std::span data) noexcept; -/// adler32_finalize(adler32_update(adler32_state{}, data)) for a byte range. +/// adler32_finalize(adler32_update({}, data)) for a byte range. template [[nodiscard]] constexpr std::uint32_t adler32_compute(Range &&data) noexcept; } // namespace checksum @@ -101,10 +101,10 @@ constexpr std::uint32_t adler32_finalize(adler32_state state) noexcept { return (adler32_detail::reduce_once(state.sum2) << 16U) | adler32_detail::reduce_once(state.sum1); } -constexpr std::uint32_t adler32_compute(std::span data) noexcept { return adler32_finalize(adler32_update(adler32_state{}, data)); } +constexpr std::uint32_t adler32_compute(std::span data) noexcept { return adler32_finalize(adler32_update({}, data)); } template constexpr std::uint32_t adler32_compute(Range &&data) noexcept { - return adler32_finalize(adler32_update(adler32_state{}, std::forward(data))); + return adler32_finalize(adler32_update({}, std::forward(data))); } } // namespace checksum From 35061a06f63a8c9c8942342fd237a69d3f8566c6 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:21:22 +0200 Subject: [PATCH 27/64] examples(fletcher, adler32): frame check, file checksum, compile time, zlib trailer, resume --- examples/CMakeLists.txt | 2 ++ examples/adler32/CMakeLists.txt | 4 +++ examples/adler32/resume.cpp | 23 +++++++++++++++ examples/adler32/zlib_trailer.cpp | 35 ++++++++++++++++++++++ examples/fletcher/CMakeLists.txt | 4 +++ examples/fletcher/compile_time.cpp | 21 ++++++++++++++ examples/fletcher/file_checksum.cpp | 32 ++++++++++++++++++++ examples/fletcher/frame_check.cpp | 45 +++++++++++++++++++++++++++++ 8 files changed, 166 insertions(+) create mode 100644 examples/adler32/CMakeLists.txt create mode 100644 examples/adler32/resume.cpp create mode 100644 examples/adler32/zlib_trailer.cpp create mode 100644 examples/fletcher/CMakeLists.txt create mode 100644 examples/fletcher/compile_time.cpp create mode 100644 examples/fletcher/file_checksum.cpp create mode 100644 examples/fletcher/frame_check.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index cdc977a..64b588c 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,5 +1,7 @@ add_subdirectory(crc) add_subdirectory(internet) +add_subdirectory(fletcher) +add_subdirectory(adler32) add_subdirectory(fletcher4) add_subdirectory(murmur3) add_subdirectory(xxhash) diff --git a/examples/adler32/CMakeLists.txt b/examples/adler32/CMakeLists.txt new file mode 100644 index 0000000..b692f84 --- /dev/null +++ b/examples/adler32/CMakeLists.txt @@ -0,0 +1,4 @@ +foreach (example zlib_trailer resume) + add_executable(checksum_example_adler32_${example} ${example}.cpp) + target_link_libraries(checksum_example_adler32_${example} PRIVATE checksum::checksum) +endforeach () diff --git a/examples/adler32/resume.cpp b/examples/adler32/resume.cpp new file mode 100644 index 0000000..957205d --- /dev/null +++ b/examples/adler32/resume.cpp @@ -0,0 +1,23 @@ +// Extends a stored Adler-32 when data is appended, without reading the old data again: the checksum is the whole state. + +#include + +#include +#include +#include + +using namespace std::literals; + +int main() { + // The checksum of the first part, e.g. kept next to a log file. + std::uint32_t const stored = checksum::adler32_compute("12345"sv); + + // Later, more data is appended: resume from the stored value. + checksum::adler32_state state{.sum1 = static_cast(stored & 0xFFFFU), .sum2 = static_cast(stored >> 16U)}; + state = checksum::adler32_update(state, "6789"sv); + std::uint32_t const extended = checksum::adler32_finalize(state); + + std::uint32_t const whole = checksum::adler32_compute("123456789"sv); + std::println("resumed 0x{:08X}, whole 0x{:08X}", extended, whole); + return extended == whole && whole == 0x091E01DE ? 0 : 1; +} diff --git a/examples/adler32/zlib_trailer.cpp b/examples/adler32/zlib_trailer.cpp new file mode 100644 index 0000000..549c5c3 --- /dev/null +++ b/examples/adler32/zlib_trailer.cpp @@ -0,0 +1,35 @@ +// Checks the Adler-32 trailer of a zlib stream (RFC 1950): the checksum of the uncompressed data, most significant byte first. + +#include + +#include +#include +#include +#include +#include + +namespace { + +// The 4-byte big-endian number at data. +std::uint32_t load_big_endian(std::span data) { + std::uint32_t value = 0; + for(std::byte const byte : data) { + value = (value << 8U) | std::to_integer(byte); + } + return value; +} + +} // namespace + +int main() { + // zlib header 78 01, one final stored block of 9 bytes (01, length 0009, its complement FFF6), "Wikipedia", Adler-32. + constexpr std::array stream{0x78, 0x01, 0x01, 0x09, 0x00, 0xF6, 0xFF, 'W', 'i', 'k', + 'i', 'p', 'e', 'd', 'i', 'a', 0x11, 0xE6, 0x03, 0x98}; + auto const bytes = std::as_bytes(std::span(stream)); + auto const data = bytes.subspan(7, 9); + std::uint32_t const stored = load_big_endian(bytes.last<4>()); + + std::uint32_t const computed = checksum::adler32_compute(data); + std::println("stored 0x{:08X}, computed 0x{:08X}: {}", stored, computed, stored == computed ? "intact" : "corrupted"); + return stored == computed && computed == 0x11E60398 ? 0 : 1; +} diff --git a/examples/fletcher/CMakeLists.txt b/examples/fletcher/CMakeLists.txt new file mode 100644 index 0000000..a2b7adb --- /dev/null +++ b/examples/fletcher/CMakeLists.txt @@ -0,0 +1,4 @@ +foreach (example compile_time file_checksum frame_check) + add_executable(checksum_example_fletcher_${example} ${example}.cpp) + target_link_libraries(checksum_example_fletcher_${example} PRIVATE checksum::checksum) +endforeach () diff --git a/examples/fletcher/compile_time.cpp b/examples/fletcher/compile_time.cpp new file mode 100644 index 0000000..4ef2b91 --- /dev/null +++ b/examples/fletcher/compile_time.cpp @@ -0,0 +1,21 @@ +// Computes Fletcher checksums at compile time: the results are constants. + +#include + +#include +#include +#include + +using namespace std::literals; + +// The compiler verifies the examples of the Wikipedia article "Fletcher's checksum". +static_assert(checksum::fletcher16_compute("abcde"sv) == 0xC8F0); +static_assert(checksum::fletcher32_compute("abcde"sv) == 0xF04FC729); +static_assert(checksum::fletcher64_compute("abcde"sv) == 0xC8C6C527646362C6); + +constexpr std::uint32_t version_checksum = checksum::fletcher32_compute("firmware 1.4.2"sv); + +int main() { + std::println("Fletcher-32 of \"firmware 1.4.2\" = 0x{:08X}", version_checksum); + return 0; +} diff --git a/examples/fletcher/file_checksum.cpp b/examples/fletcher/file_checksum.cpp new file mode 100644 index 0000000..2e3722c --- /dev/null +++ b/examples/fletcher/file_checksum.cpp @@ -0,0 +1,32 @@ +// Computes the Fletcher-32 of a file in chunks. A chunk may end inside a 16-bit block: the state keeps the unfinished +// block. + +#include + +#include +#include +#include // stderr +#include +#include +#include + +int main(int argument_count, char **arguments) { + if(argument_count != 2) { + std::println(stderr, "usage: {} ", arguments[0]); + return 1; + } + std::ifstream file(arguments[1], std::ios::binary); + if(!file) { + std::println(stderr, "cannot open {}", arguments[1]); + return 1; + } + + checksum::fletcher32_state state; + std::array buffer{}; + while(file.read(buffer.data(), buffer.size()) || file.gcount() > 0) { + state = checksum::fletcher_update(state, std::span{buffer}.first(static_cast(file.gcount()))); + } + + std::println("{:08x} {}", checksum::fletcher_finalize(state), arguments[1]); + return 0; +} diff --git a/examples/fletcher/frame_check.cpp b/examples/fletcher/frame_check.cpp new file mode 100644 index 0000000..db02cc1 --- /dev/null +++ b/examples/fletcher/frame_check.cpp @@ -0,0 +1,45 @@ +// Appends a Fletcher-16 to a serial frame and checks a received frame. +// The checksum is a number; this protocol sends it most significant byte first, sum2 then sum1. + +#include + +#include +#include +#include +#include +#include + +namespace { + +// frame is the message followed by two bytes that receive its checksum. +void append_checksum(std::span frame) { + std::uint16_t const value = checksum::fletcher16_compute(std::span{frame}.first(frame.size() - 2)); + frame[frame.size() - 2] = static_cast(value >> 8U); + frame[frame.size() - 1] = static_cast(value & 0xFFU); +} + +// Recomputes the checksum of the message and compares it with the last two bytes. +bool is_valid(std::span frame) { + if(frame.size() < 2) { + return false; + } + auto const received = + static_cast((std::to_integer(frame[frame.size() - 2]) << 8U) | std::to_integer(frame[frame.size() - 1])); + return checksum::fletcher16_compute(frame.first(frame.size() - 2)) == received; +} + +} // namespace + +int main() { + // The message "abcde", whose Fletcher-16 is 0xC8F0, then two checksum bytes. + std::array frame{std::byte{'a'}, std::byte{'b'}, std::byte{'c'}, std::byte{'d'}, std::byte{'e'}, std::byte{0}, std::byte{0}}; + append_checksum(frame); + std::println("checksum bytes on the wire: {:02X} {:02X}", std::to_integer(frame[5]), std::to_integer(frame[6])); + + bool const expected = frame[5] == std::byte{0xC8} && frame[6] == std::byte{0xF0}; + bool const intact = is_valid(frame); + frame[2] ^= std::byte{0x01}; // a transmission error + bool const corrupted = is_valid(frame); + std::println("intact frame valid: {}, corrupted frame valid: {}", intact ? "yes" : "no", corrupted ? "yes" : "no"); + return expected && intact && !corrupted ? 0 : 1; +} From d8efee306adf6ebfa4c315ff3407080911ab0055 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:21:22 +0200 Subject: [PATCH 28/64] docs(fletcher, adler32): aliases, examples, chunk sizes, shared loops --- README.md | 7 +++++++ doc/adler32.md | 3 +++ doc/design/acceleration.md | 3 ++- doc/fletcher.md | 20 +++++++++++++------- 4 files changed, 25 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index b015ee5..ed3d2bf 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,14 @@ CPU acceleration follows your compiler flags (for example `-march=native` or `-m - [MurmurHash3 user guide](doc/murmur3.md): the API, seeds, byte order, measured performance and limitations. - [examples/crc](examples/crc): compile-time CRC, a file checksum, a custom CRC, run-time parameters, a MODBUS frame and a strategy driving an MCU CRC peripheral. +- [examples/internet](examples/internet): an IPv4 header, a UDP datagram with its pseudo-header and an incremental + update after a TTL decrement. +- [examples/fletcher](examples/fletcher) and [examples/adler32](examples/adler32): compile-time checksums, a file + checksum, a frame check, a zlib trailer and extending a stored Adler-32. - [examples/fletcher4](examples/fletcher4): verifying a ZFS block and a file checksum. +- [examples/xxhash](examples/xxhash) and [examples/xxh3](examples/xxh3): compile-time IDs, file hashes, a cache key, + block deduplication and a seeded hash table. +- [examples/murmur3](examples/murmur3): command dispatch, a Bloom filter and record deduplication. ## Contributing diff --git a/doc/adler32.md b/doc/adler32.md index bbd55d7..17d520d 100644 --- a/doc/adler32.md +++ b/doc/adler32.md @@ -26,6 +26,9 @@ static_assert(checksum::adler32_compute("123456789"sv) == 0x091E01DE); static_assert(checksum::adler32_compute("Wikipedia"sv) == 0x11E60398); ``` +`examples/adler32` has complete programs: checking the Adler-32 trailer of a zlib stream, and extending a stored +checksum when data is appended. + ## 2. Definition Adler-32 keeps two sums modulo 65521, the largest prime below 2^16: `sum1` starts at 1 and adds each byte, `sum2` diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index 5ff25a2..95e917d 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -133,7 +133,8 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Cortex-M Fletcher-16, Fletcher-32, Fletcher-64 and Adler-32 share one kernel interface in `fletcher_arch.hpp`: `kernel` sums little-endian values of 8, 16 or 32 bits and returns, for a chunk of n values v_i, their sum and the weighted sum of (n − i) · v_i. The caller adds n · `sum1` plus the weighted sum to `sum2` and reduces both sums after every chunk. -Fletcher-16 and Adler-32 run the same byte kernel with moduli 255 and 65521. +Fletcher-16 and Adler-32 run the same byte kernel with moduli 255 and 65521. The portable loop, the chunk loop and the +choice between them are written once, in `fletcher_loops.hpp`, for both families. The portable loops are the baseline. They reduce only when an overflow could otherwise happen (every 380 million bytes on 64-bit targets for Fletcher-16 and Adler-32) and add four blocks per step, so a byte loop still runs 7 300 MB/s on diff --git a/doc/fletcher.md b/doc/fletcher.md index fbbf68c..b18f06f 100644 --- a/doc/fletcher.md +++ b/doc/fletcher.md @@ -14,20 +14,23 @@ allocates no memory and has no global state. using namespace std::literals; // One call. -std::uint32_t value = checksum::fletcher_compute<32>(std::span(buffer)); +std::uint32_t value = checksum::fletcher32_compute(std::span(buffer)); // Incremental: a message may be split anywhere. -checksum::fletcher_state<16> state; +checksum::fletcher16_state state; state = checksum::fletcher_update(state, header); state = checksum::fletcher_update(state, payload); std::uint16_t frame_checksum = checksum::fletcher_finalize(state); // Compile time. -static_assert(checksum::fletcher_compute<16>("abcde"sv) == 0xC8F0); -static_assert(checksum::fletcher_compute<32>("abcde"sv) == 0xF04FC729); -static_assert(checksum::fletcher_compute<64>("abcde"sv) == 0xC8C6C527646362C6); +static_assert(checksum::fletcher16_compute("abcde"sv) == 0xC8F0); +static_assert(checksum::fletcher32_compute("abcde"sv) == 0xF04FC729); +static_assert(checksum::fletcher64_compute("abcde"sv) == 0xC8C6C527646362C6); ``` +`examples/fletcher` has complete programs: checksums at compile time, a file checksum computed in chunks, and a frame +check. + ## 2. Definition Fletcher-N reads the message as blocks of N/2 bits and keeps two sums modulo M = 2^(N/2) − 1, both starting at 0: @@ -44,7 +47,8 @@ A last incomplete block is padded with zero bytes. The values match the examples ## 3. API -`Width` is 16, 32 or 64. +`Width` is 16, 32 or 64. `fletcher_update` and `fletcher_finalize` take the width from the state, so only the state +and `fletcher_compute` have aliases per width. | Name | What it does | | --- | --- | @@ -52,6 +56,8 @@ A last incomplete block is padded with zero bytes. The values match the examples | `fletcher_update(state, data)` | Folds `data` into `state` and returns the new state. | | `fletcher_finalize(state)` | The checksum, an unfinished block padded with zero bytes. | | `fletcher_compute(data)` | `fletcher_finalize(fletcher_update(fletcher_state{}, data))`. | +| `fletcher16_state`, `fletcher32_state`, `fletcher64_state` | `fletcher_state<16>`, `fletcher_state<32>`, `fletcher_state<64>`. | +| `fletcher16_compute(data)`, `fletcher32_compute(data)`, `fletcher64_compute(data)` | `fletcher_compute<16>(data)`, `fletcher_compute<32>(data)`, `fletcher_compute<64>(data)`. | `fletcher_state::value_type` is the checksum type and `sum_type` the type of one sum (`std::uint8_t`, `std::uint16_t`, `std::uint32_t`). All functions are `constexpr` and `noexcept`. `data` is a @@ -79,7 +85,7 @@ adds four blocks per step, so `sum1` has one addition per four blocks in its dep Fletcher-32 sums 32-bit words, two blocks at a time. From a minimum size, a kernel sums whole vectors of blocks. It returns the sum of the blocks and their weighted sum, -and `sum2` gains both at the end of each chunk of a few kilobytes. +and `sum2` gains both at the end of each chunk, 2 KiB to 256 KiB depending on the kernel. | Target and flags | Fletcher-16 | Fletcher-32 | Fletcher-64 | | --- | --- | --- | --- | From 9f9a6b4f64a5c3c121de3982fe3f1fa39c247973 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:25:34 +0200 Subject: [PATCH 29/64] perf(fletcher): 32-bit byte loop for Fletcher-16 and Fletcher-32 The constant-evaluation loop, which also finishes unfinished blocks at run time, kept its sums in 64 bits; on Cortex-M4 this cost 150 bytes of code in the library. --- src/include/checksum/fletcher.hpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/include/checksum/fletcher.hpp b/src/include/checksum/fletcher.hpp index a3013f6..c097570 100644 --- a/src/include/checksum/fletcher.hpp +++ b/src/include/checksum/fletcher.hpp @@ -85,8 +85,11 @@ template inline constexpr unsigned block_size = Width / 16; // M = 2^(Width/2) - 1. template inline constexpr std::uint64_t modulus = (std::uint64_t{1} << (Width / 2)) - 1; +// Holds the sum of two sums and the checksum: 32 bits where they fit, so that 32-bit targets avoid 64-bit operations. +template using integer = std::conditional_t; + // value modulo M for value < 2M. -template constexpr std::uint64_t reduce_once(std::uint64_t value) noexcept; +template constexpr integer reduce_once(integer value) noexcept; // Folds data byte by byte; the constant-evaluation loop, also used at run time for the bytes of an unfinished block. template constexpr fletcher_state update_bytes(fletcher_state state, std::span data) noexcept; @@ -103,17 +106,17 @@ fletcher_state<64> sum_loop(fletcher_state<64> state, std::span namespace checksum::fletcher_detail { -template constexpr std::uint64_t reduce_once(std::uint64_t value) noexcept { - return value >= modulus ? value - modulus : value; +template constexpr integer reduce_once(integer value) noexcept { + return value >= modulus ? static_cast>(value - modulus) : value; } template constexpr fletcher_state update_bytes(fletcher_state state, std::span data) noexcept { using sum_type = fletcher_state::sum_type; - std::uint64_t sum1 = reduce_once(state.sum1); - std::uint64_t sum2 = reduce_once(state.sum2); + integer sum1 = reduce_once(state.sum1); + integer sum2 = reduce_once(state.sum2); unsigned offset = state.block_offset % block_size; for(std::byte const byte : data) { - sum1 = reduce_once(sum1 + (std::to_integer(byte) << (8 * offset))); + sum1 = reduce_once(sum1 + (std::to_integer>(byte) << (8 * offset))); if(++offset == block_size) { offset = 0; sum2 = reduce_once(sum2 + sum1); @@ -141,8 +144,8 @@ template constexpr fletcher_state flet template constexpr fletcher_state::value_type fletcher_finalize(fletcher_state state) noexcept { using value_type = fletcher_state::value_type; - std::uint64_t const sum1 = fletcher_detail::reduce_once(state.sum1); - std::uint64_t sum2 = fletcher_detail::reduce_once(state.sum2); + fletcher_detail::integer const sum1 = fletcher_detail::reduce_once(state.sum1); + fletcher_detail::integer sum2 = fletcher_detail::reduce_once(state.sum2); // The zero padding adds nothing to sum1, but the padded block still adds sum1 to sum2. if(state.block_offset % fletcher_detail::block_size != 0) { sum2 = fletcher_detail::reduce_once(sum2 + sum1); From 15aa0231d20d382ece29f3fd13549d2d19d9a4bf Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:46:27 +0200 Subject: [PATCH 30/64] perf(fletcher, adler32): no Cortex-M4 regressions from the shared loops The shared loops take the checksum's own state, adler32_state or a two-member sum_pair, so states of up to 4 bytes stay in one register on 32-bit Arm. Callers branch on runs_kernel() themselves, so that Adler-32 tail-calls the kernel path again, and Fletcher-32 and Fletcher-64 run the byte loop out of line and only for bytes of an unfinished block. nRF52840, MB/s at 64 B: Adler-32 9.1 -> 10.0, Fletcher-16 9.0 -> 9.7, Fletcher-64 12.3 -> 12.8. --- src/adler32/sum_loop.cpp | 7 +- src/fletcher/sum_loop.cpp | 30 ++++++-- .../checksum_private/fletcher_loops.hpp | 72 ++++++++++--------- 3 files changed, 65 insertions(+), 44 deletions(-) diff --git a/src/adler32/sum_loop.cpp b/src/adler32/sum_loop.cpp index c4bbd1c..4f767f1 100644 --- a/src/adler32/sum_loop.cpp +++ b/src/adler32/sum_loop.cpp @@ -10,9 +10,10 @@ namespace checksum::adler32_detail { adler32_state sum_loop(adler32_state state, std::span data) noexcept { - fletcher_detail::sum_pair const sums = - fletcher_detail::sum_values({.sum1 = reduce_once(state.sum1), .sum2 = reduce_once(state.sum2)}, data); - return {.sum1 = static_cast(sums.sum1), .sum2 = static_cast(sums.sum2)}; + if(fletcher_detail::runs_kernel(data.size())) { + return fletcher_detail::sum_long(state, data); + } + return fletcher_detail::sum_portable(state, data); } } // namespace checksum::adler32_detail diff --git a/src/fletcher/sum_loop.cpp b/src/fletcher/sum_loop.cpp index 9dbd3af..0322388 100644 --- a/src/fletcher/sum_loop.cpp +++ b/src/fletcher/sum_loop.cpp @@ -11,17 +11,33 @@ namespace checksum::fletcher_detail { namespace { +// update_bytes() out of line, so that the byte loop takes no registers from the block loops. +template [[gnu::noinline]] fletcher_state add_bytes(fletcher_state state, std::span data) noexcept { + return update_bytes(state, data); +} + // Finishes an unfinished block byte by byte, sums the whole blocks with the shared loops, and adds the bytes of a last -// unfinished block to sum1. +// unfinished block to sum1. The byte loop runs only where there are such bytes. template fletcher_state sum_any(fletcher_state state, std::span data) noexcept { using sum_type = fletcher_state::sum_type; constexpr unsigned size = block_size; - std::size_t const head = std::min(data.size(), (size - (state.block_offset % size)) % size); - state = update_bytes(state, data.first(head)); - data = data.subspan(head); - sum_pair const sums = sum_values>({.sum1 = state.sum1, .sum2 = state.sum2}, data); - state = {.sum1 = static_cast(sums.sum1), .sum2 = static_cast(sums.sum2), .block_offset = state.block_offset}; - return update_bytes(state, data.last(data.size() % size)); + sum_pair sums{.sum1 = state.sum1, .sum2 = state.sum2}; + if(state.block_offset % size != 0) { + std::size_t const head = std::min(data.size(), size - (state.block_offset % size)); + fletcher_state const finished = add_bytes(state, data.first(head)); + if(finished.block_offset != 0) { + return finished; + } + sums = {.sum1 = finished.sum1, .sum2 = finished.sum2}; + data = data.subspan(head); + } + sum_pair const result = + runs_kernel(data.size()) ? sum_long>(sums, data) : sum_portable>(sums, data); + std::size_t const tail = data.size() % size; + if(tail == 0) { + return {.sum1 = result.sum1, .sum2 = result.sum2, .block_offset = 0}; + } + return add_bytes({.sum1 = result.sum1, .sum2 = result.sum2, .block_offset = 0}, data.last(tail)); } } // namespace diff --git a/src/include_private/checksum_private/fletcher_loops.hpp b/src/include_private/checksum_private/fletcher_loops.hpp index 548610b..19c3078 100644 --- a/src/include_private/checksum_private/fletcher_loops.hpp +++ b/src/include_private/checksum_private/fletcher_loops.hpp @@ -17,10 +17,10 @@ namespace checksum::fletcher_detail { -// Both sums of a checksum, each below the modulus. -struct sum_pair { - std::uint64_t sum1 = 0; - std::uint64_t sum2 = 0; +// The two sums of a Fletcher checksum without its block offset: up to 4 bytes pass in one register on 32-bit Arm. +template struct sum_pair { + Sum sum1 = 0; + Sum sum2 = 0; }; // Internal linkage lets compilers inline these loops fully into each source; with external linkage they keep an @@ -44,21 +44,25 @@ template Word reduce_chunk(Word value) noexc // and elsewhere load single bytes instead of calling memcpy. template Value load(std::byte const *data) noexcept; -// Adds the whole kernel blocks at the start of data to sums, a chunk of at most max_blocks blocks per kernel call, each sum +// The loops take and return a sum_pair or an adler32_state, which has the same members: sums below 2 * Modulus in, below +// Modulus out. + +// Adds the whole kernel blocks at the start of data to the sums of state, a chunk of at most max_blocks blocks per kernel call, each sum // reduced after every chunk. Returns the number of bytes taken; inlined into its one caller. -template -[[gnu::always_inline]] inline std::size_t sum_chunks(sum_pair &sums, std::span data) noexcept; +template +[[gnu::always_inline]] inline std::size_t sum_chunks(State &state, std::span data) noexcept; // The portable loop over the whole Values of data. -template -[[gnu::always_inline]] inline sum_pair sum_portable(sum_pair sums, std::span data) noexcept; +template +[[gnu::always_inline]] inline State sum_portable(State state, std::span data) noexcept; -// The CPU kernel, then the portable loop over what it left. Not inlined, so that short inputs run sum_values() without a call. -template -[[gnu::noinline, maybe_unused]] sum_pair sum_long(sum_pair sums, std::span data) noexcept; +// The CPU kernel, then the portable loop over what it left. Not inlined, so that short inputs run sum_portable() without a call. +template +[[gnu::noinline, maybe_unused]] State sum_long(State state, std::span data) noexcept; -// Adds the whole Values of data to sums: the kernel from its minimum size, else the portable loop. -template sum_pair sum_values(sum_pair sums, std::span data) noexcept; +// Whether size bytes go to sum_long(): from the minimum size of the kernel, if there is one. Callers branch on it themselves, +// so that the call of sum_long() stays a tail call. +template constexpr bool runs_kernel(std::size_t size) noexcept; template constexpr std::size_t values_per_reduction(std::uint64_t largest_value) noexcept { constexpr std::uint64_t maximum = std::numeric_limits::max(); @@ -118,8 +122,8 @@ template Value load(std::byte const *data) noexcept { } } -template -[[gnu::always_inline]] inline std::size_t sum_chunks(sum_pair &sums, std::span data) noexcept { +template +[[gnu::always_inline]] inline std::size_t sum_chunks(State &state, std::span data) noexcept { constexpr unsigned bits = std::numeric_limits::digits; using chunk_kernel = kernel; constexpr std::uint64_t values_per_block = chunk_kernel::block_size / sizeof(Value); @@ -135,8 +139,8 @@ template using word = std::conditional_t; - auto sum1 = static_cast(sums.sum1); - auto sum2 = static_cast(sums.sum2); + auto sum1 = static_cast(state.sum1); + auto sum2 = static_cast(state.sum2); std::byte const *position = data.data(); std::size_t head = 0; if constexpr(bits == 8) { @@ -163,12 +167,13 @@ template blocks -= count; position += count * chunk_kernel::block_size; } - sums = {.sum1 = sum1, .sum2 = sum2}; + state.sum1 = static_cast(sum1); + state.sum2 = static_cast(sum2); return size; } -template -[[gnu::always_inline]] inline sum_pair sum_portable(sum_pair sums, std::span data) noexcept { +template +[[gnu::always_inline]] inline State sum_portable(State state, std::span data) noexcept { // The widest integer the target adds natively, or 64 bits for 32-bit values. using accumulator = std::conditional_t; // 32-bit targets sum 16-bit values as 32-bit words, two values each; 64-bit targets keep the 4-value formula on native words. @@ -178,8 +183,8 @@ template static_assert(run >= 8); // In a run of w words, previous is at most 2M * w(w - 1) / 2. static_assert(!sums_words || Modulus * (run / 2) * ((run / 2) - 1) <= std::numeric_limits::max()); - auto sum1 = static_cast(sums.sum1); - auto sum2 = static_cast(sums.sum2); + auto sum1 = static_cast(state.sum1 >= Modulus ? state.sum1 - Modulus : state.sum1); + auto sum2 = static_cast(state.sum2 >= Modulus ? state.sum2 - Modulus : state.sum2); std::byte const *position = data.data(); std::size_t values = data.size() / size; while(values != 0) { @@ -249,22 +254,21 @@ template sum1 = reduce(sum1); sum2 = reduce(sum2); } - return {.sum1 = sum1, .sum2 = sum2}; + return {.sum1 = static_cast(sum1), .sum2 = static_cast(sum2)}; } -template -[[gnu::noinline, maybe_unused]] sum_pair sum_long(sum_pair sums, std::span data) noexcept { - std::size_t const size = sum_chunks(sums, data); - return sum_portable(sums, data.subspan(size)); +template +[[gnu::noinline, maybe_unused]] State sum_long(State state, std::span data) noexcept { + std::size_t size = 0; + if constexpr(kernel::digits>::available) { + size = sum_chunks(state, data); + } + return sum_portable(state, data.subspan(size)); } -template sum_pair sum_values(sum_pair sums, std::span data) noexcept { +template constexpr bool runs_kernel(std::size_t size) noexcept { using value_kernel = kernel::digits>; - if constexpr(value_kernel::available) { - return data.size() >= value_kernel::minimum_size ? sum_long(sums, data) : sum_portable(sums, data); - } else { - return sum_portable(sums, data); - } + return value_kernel::available && size >= value_kernel::minimum_size; } } // namespace From 63c7b976741d87e68ead351287c2e1866a5ca4ad Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:15:31 +0200 Subject: [PATCH 31/64] refactor: each dispatch header selects its architecture directory --- doc/design/acceleration.md | 5 ++--- doc/design/principles.md | 2 +- src/include_private/checksum_private/arch.hpp | 19 ------------------- .../checksum_private/crc_arch.hpp | 11 ++++++----- .../checksum_private/fletcher4_arch.hpp | 10 +++++----- .../checksum_private/fletcher_arch.hpp | 10 +++++----- .../checksum_private/internet_arch.hpp | 11 ++++++----- .../checksum_private/xxh3_arch.hpp | 11 ++++++----- 8 files changed, 31 insertions(+), 48 deletions(-) delete mode 100644 src/include_private/checksum_private/arch.hpp diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index 95e917d..fe088d2 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -8,9 +8,8 @@ user guides ([CRC](../crc.md#8-performance), [Internet checksum](../internet.md# ## Rules -- **Compile time only.** `checksum_private/arch.hpp` selects one directory per architecture (`x86_64/`, `arm/`, - `riscv64/`, `generic/`), and each algorithm's dispatch header (`crc_arch.hpp`, `internet_arch.hpp`, `fletcher_arch.hpp`, `xxh3_arch.hpp`, - `fletcher4_arch.hpp`) includes its header from there. That header checks the macros the compiler predefines for the flags of each translation unit +- **Compile time only.** Each algorithm's dispatch header (`crc_arch.hpp`, `internet_arch.hpp`, `fletcher_arch.hpp`, `xxh3_arch.hpp`, + `fletcher4_arch.hpp`) selects one directory per architecture (`x86_64/`, `arm/`, `riscv64/`, `generic/`) and includes its header from there. That header checks the macros the compiler predefines for the flags of each translation unit (`__PCLMUL__`, `__ARM_FEATURE_CRC32`, `__riscv_vector`, ...); without them it uses no kernel, mostly by including the generic one. The generic directory also covers `CHECKSUM_ACCELERATION=OFF`. No run-time CPU detection, no target attributes, no static state; the build never adds instruction-set flags. diff --git a/doc/design/principles.md b/doc/design/principles.md index ecf6ac6..dfa9704 100644 --- a/doc/design/principles.md +++ b/doc/design/principles.md @@ -23,7 +23,7 @@ rules. `byte_range` concept, chunking of non-contiguous ranges) is in `checksum/byte_range.hpp`, with its details in `checksum::detail`. Headers shared only by `src/` go to `src/include_private/checksum_private/`. - Platform-specific code lives only in the architecture headers, one directory per architecture - (`checksum_private/x86_64/crc.hpp`, `arm/internet.hpp`, ...); `checksum_private/arch.hpp` selects the directory. + (`checksum_private/x86_64/crc.hpp`, `arm/internet.hpp`, ...); each `_arch.hpp` selects the directory. - `constexpr` first: parameter validation and table generation work at compile time, so named engines are constants in read-only data. - Bounded template bloat: no functions are instantiated per parameter set. Run-time loops are compiled once in diff --git a/src/include_private/checksum_private/arch.hpp b/src/include_private/checksum_private/arch.hpp deleted file mode 100644 index 6bfda42..0000000 --- a/src/include_private/checksum_private/arch.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef CHECKSUM_PRIVATE_ARCH_HPP -#define CHECKSUM_PRIVATE_ARCH_HPP - -// Selects the directory of CPU kernels: defines one of CHECKSUM_ARCH_X86_64, CHECKSUM_ARCH_ARM, CHECKSUM_ARCH_RISCV64 and -// CHECKSUM_ARCH_GENERIC. Each architecture header checks its instruction-set extensions: without them it uses no kernel. - -#if defined(CHECKSUM_ACCELERATION) && !CHECKSUM_ACCELERATION -#define CHECKSUM_ARCH_GENERIC 1 -#elif defined(__x86_64__) -#define CHECKSUM_ARCH_X86_64 1 -#elif defined(__aarch64__) || defined(__arm__) -#define CHECKSUM_ARCH_ARM 1 -#elif defined(__riscv) && __riscv_xlen == 64 && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -#define CHECKSUM_ARCH_RISCV64 1 -#else -#define CHECKSUM_ARCH_GENERIC 1 -#endif - -#endif // CHECKSUM_PRIVATE_ARCH_HPP diff --git a/src/include_private/checksum_private/crc_arch.hpp b/src/include_private/checksum_private/crc_arch.hpp index e2a76a4..78744cf 100644 --- a/src/include_private/checksum_private/crc_arch.hpp +++ b/src/include_private/checksum_private/crc_arch.hpp @@ -1,7 +1,7 @@ #ifndef CHECKSUM_PRIVATE_CRC_ARCH_HPP #define CHECKSUM_PRIVATE_CRC_ARCH_HPP -// CPU kernels of crc_lut_sliced and crc_lut_braided, from the directory arch.hpp selects; without the instruction-set +// CPU kernels of crc_lut_sliced and crc_lut_braided, from the directory of the target architecture; without the instruction-set // extensions, or with CHECKSUM_ACCELERATION defined to 0, no kernel is used. Each architecture header defines: // - folding_available; if true, fold_blocks() via fold_blocks_with() and its fold kernel // - crc32_instructions_available; where true, crc32_word() and crc32_instructions() @@ -9,7 +9,6 @@ // - wide_folding_minimum_size: shortest input for a loop wider than four 128-bit accumulators (max: none) #include -#include #include #include @@ -173,11 +172,13 @@ template } // namespace checksum::crc_detail -#if defined(CHECKSUM_ARCH_X86_64) +#if defined(CHECKSUM_ACCELERATION) && !CHECKSUM_ACCELERATION +#include +#elif defined(__x86_64__) #include -#elif defined(CHECKSUM_ARCH_ARM) +#elif defined(__aarch64__) || defined(__arm__) #include -#elif defined(CHECKSUM_ARCH_RISCV64) +#elif defined(__riscv) && __riscv_xlen == 64 && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #include #else #include diff --git a/src/include_private/checksum_private/fletcher4_arch.hpp b/src/include_private/checksum_private/fletcher4_arch.hpp index 0866852..edc64d7 100644 --- a/src/include_private/checksum_private/fletcher4_arch.hpp +++ b/src/include_private/checksum_private/fletcher4_arch.hpp @@ -1,13 +1,11 @@ #ifndef CHECKSUM_PRIVATE_FLETCHER4_ARCH_HPP #define CHECKSUM_PRIVATE_FLETCHER4_ARCH_HPP -// CPU kernel of the fletcher4 lane loop, from the directory arch.hpp selects; without the instruction-set extensions, or +// CPU kernel of the fletcher4 lane loop, from the directory of the target architecture; without the instruction-set extensions, or // with CHECKSUM_ACCELERATION defined to 0, the portable lanes sum everything. Each architecture header defines: // - lane_kernel_available; if true, lane_kernel() // - lane_kernel_minimum_size: shortest input for lane_kernel() (max: never) -#include - #include #include #include @@ -25,9 +23,11 @@ inline lane_sums lane_kernel(std::byte const *data, std::size_t groups) noexcept } // namespace checksum::fletcher4_detail -#if defined(CHECKSUM_ARCH_X86_64) +#if defined(CHECKSUM_ACCELERATION) && !CHECKSUM_ACCELERATION +#include +#elif defined(__x86_64__) #include -#elif defined(CHECKSUM_ARCH_ARM) +#elif defined(__aarch64__) || defined(__arm__) #include #else #include diff --git a/src/include_private/checksum_private/fletcher_arch.hpp b/src/include_private/checksum_private/fletcher_arch.hpp index ec1d4d6..e203ec1 100644 --- a/src/include_private/checksum_private/fletcher_arch.hpp +++ b/src/include_private/checksum_private/fletcher_arch.hpp @@ -1,7 +1,7 @@ #ifndef CHECKSUM_PRIVATE_FLETCHER_ARCH_HPP #define CHECKSUM_PRIVATE_FLETCHER_ARCH_HPP -// CPU kernels of the Fletcher checksums and Adler-32, from the directory arch.hpp selects; without the instruction-set +// CPU kernels of the Fletcher checksums and Adler-32, from the directory of the target architecture; without the instruction-set // extensions, or with CHECKSUM_ACCELERATION defined to 0, the portable loops sum everything. kernel sums // little-endian values of Bits bits (8 for Fletcher-16 and Adler-32, 16 for Fletcher-32, 32 for Fletcher-64), and each // architecture header specializes it with: @@ -11,8 +11,6 @@ // - for kernel<8> also alignment: sum_chunks() of fletcher_loops.hpp adds single bytes up to an address of that alignment // before the kernel -#include - #include namespace checksum::fletcher_detail { @@ -25,9 +23,11 @@ struct chunk_sums { } // namespace checksum::fletcher_detail -#if defined(CHECKSUM_ARCH_X86_64) +#if defined(CHECKSUM_ACCELERATION) && !CHECKSUM_ACCELERATION +#include +#elif defined(__x86_64__) #include -#elif defined(CHECKSUM_ARCH_ARM) +#elif defined(__aarch64__) || defined(__arm__) #include #else #include diff --git a/src/include_private/checksum_private/internet_arch.hpp b/src/include_private/checksum_private/internet_arch.hpp index 768edf1..52b4fcb 100644 --- a/src/include_private/checksum_private/internet_arch.hpp +++ b/src/include_private/checksum_private/internet_arch.hpp @@ -1,13 +1,12 @@ #ifndef CHECKSUM_PRIVATE_INTERNET_ARCH_HPP #define CHECKSUM_PRIVATE_INTERNET_ARCH_HPP -// CPU kernel of the Internet checksum, from the directory arch.hpp selects; without the instruction-set extensions, or +// CPU kernel of the Internet checksum, from the directory of the target architecture; without the instruction-set extensions, or // with CHECKSUM_ACCELERATION defined to 0, the portable loop sums everything. Each architecture header defines: // - block_sum_available; if true, block_sum() // - block_sum_minimum_size: shortest input for block_sum() (max: never) #include -#include #include #include @@ -26,11 +25,13 @@ inline block_total block_sum(std::span data) noexcept; } // namespace checksum::internet_detail -#if defined(CHECKSUM_ARCH_X86_64) +#if defined(CHECKSUM_ACCELERATION) && !CHECKSUM_ACCELERATION +#include +#elif defined(__x86_64__) #include -#elif defined(CHECKSUM_ARCH_ARM) +#elif defined(__aarch64__) || defined(__arm__) #include -#elif defined(CHECKSUM_ARCH_RISCV64) +#elif defined(__riscv) && __riscv_xlen == 64 && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #include #else #include diff --git a/src/include_private/checksum_private/xxh3_arch.hpp b/src/include_private/checksum_private/xxh3_arch.hpp index a5afc4b..daab24d 100644 --- a/src/include_private/checksum_private/xxh3_arch.hpp +++ b/src/include_private/checksum_private/xxh3_arch.hpp @@ -1,23 +1,24 @@ #ifndef CHECKSUM_PRIVATE_XXH3_ARCH_HPP #define CHECKSUM_PRIVATE_XXH3_ARCH_HPP -// CPU kernel of the XXH3 stripe loop, from the directory arch.hpp selects; without the instruction-set extensions, or with +// CPU kernel of the XXH3 stripe loop, from the directory of the target architecture; without the instruction-set extensions, or with // CHECKSUM_ACCELERATION defined to 0, the portable kernel folds everything. Each architecture header defines: // - stripe_kernel_available; if true, stripe_kernel with the members of portable_kernel // - stripe_kernel_minimum_size: shortest input for stripe_kernel (max: never) #include -#include // std::array of __m128i or uint64x2_t drops their __may_alias__ attribute, which arrays of accumulators do not need. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wignored-attributes" -#if defined(CHECKSUM_ARCH_X86_64) +#if defined(CHECKSUM_ACCELERATION) && !CHECKSUM_ACCELERATION +#include +#elif defined(__x86_64__) #include -#elif defined(CHECKSUM_ARCH_ARM) +#elif defined(__aarch64__) || defined(__arm__) #include -#elif defined(CHECKSUM_ARCH_RISCV64) +#elif defined(__riscv) && __riscv_xlen == 64 && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #include #else #include From 9fdaf885fc93f24280764ebad93d38075d2c333d Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:17:36 +0200 Subject: [PATCH 32/64] test: one pseudo-random data generator for tests and benchmarks --- tests/CMakeLists.txt | 3 ++ tests/benchmarks/CMakeLists.txt | 14 ++++----- tests/benchmarks/bench_adler32.cpp | 10 ++---- tests/benchmarks/bench_crc.cpp | 13 ++------ tests/benchmarks/bench_fletcher.cpp | 10 ++---- tests/benchmarks/bench_fletcher4.cpp | 10 ++---- tests/benchmarks/bench_internet.cpp | 10 ++---- tests/benchmarks/bench_murmur3.cpp | 10 ++---- tests/benchmarks/bench_xxhash.cpp | 10 ++---- tests/include/test_data.hpp | 31 +++++++++++++++++++ tests/unit_tests/CMakeLists.txt | 4 +-- tests/unit_tests/include/crc_test_support.hpp | 14 +-------- .../include/fletcher4_reference_vectors.hpp | 13 +------- .../include/murmur3_reference_vectors.hpp | 13 +------- .../include/xxh3_reference_vectors.hpp | 2 +- .../include/xxhash_reference_vectors.hpp | 13 +------- tests/unit_tests/ut_adler32.cpp | 21 ++----------- tests/unit_tests/ut_crc_acceleration.cpp | 2 +- tests/unit_tests/ut_crc_accumulator.cpp | 2 +- tests/unit_tests/ut_crc_engine.cpp | 14 ++++----- tests/unit_tests/ut_fletcher.cpp | 21 ++----------- tests/unit_tests/ut_fletcher4.cpp | 15 ++------- tests/unit_tests/ut_internet.cpp | 21 ++----------- tests/unit_tests/ut_murmur3.cpp | 5 +-- tests/unit_tests/ut_xxh3.cpp | 5 +-- tests/unit_tests/ut_xxhash.cpp | 5 +-- 26 files changed, 92 insertions(+), 199 deletions(-) create mode 100644 tests/include/test_data.hpp diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4bca78a..179e475 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,3 +1,6 @@ +add_library(checksum_test_data INTERFACE) +target_sources(checksum_test_data INTERFACE FILE_SET HEADERS BASE_DIRS include FILES include/test_data.hpp) + if (CHECKSUM_TESTS) add_subdirectory(unit_tests) add_subdirectory(compile_fail) diff --git a/tests/benchmarks/CMakeLists.txt b/tests/benchmarks/CMakeLists.txt index dab7687..af408ee 100644 --- a/tests/benchmarks/CMakeLists.txt +++ b/tests/benchmarks/CMakeLists.txt @@ -1,37 +1,37 @@ add_executable(checksum_bench bench_crc.cpp) target_compile_features(checksum_bench PRIVATE cxx_std_23) -target_link_libraries(checksum_bench PRIVATE checksum::checksum benchmark::benchmark checksum_bench_zlib_crc32) +target_link_libraries(checksum_bench PRIVATE checksum::checksum checksum_test_data benchmark::benchmark checksum_bench_zlib_crc32) # Smoke test: checks the baselines against the library and runs one tiny benchmark. Measurements use the native-*-bench presets. add_test(NAME benchmark_smoke COMMAND checksum_bench --benchmark_filter=^byte/crc32_iso_hdlc/16$ --benchmark_min_time=0.001s) add_executable(checksum_bench_internet bench_internet.cpp) target_compile_features(checksum_bench_internet PRIVATE cxx_std_23) -target_link_libraries(checksum_bench_internet PRIVATE checksum::checksum benchmark::benchmark) +target_link_libraries(checksum_bench_internet PRIVATE checksum::checksum checksum_test_data benchmark::benchmark) add_test(NAME benchmark_internet_smoke COMMAND checksum_bench_internet --benchmark_filter=^internet/20$ --benchmark_min_time=0.001s) add_executable(checksum_bench_fletcher bench_fletcher.cpp) target_compile_features(checksum_bench_fletcher PRIVATE cxx_std_23) -target_link_libraries(checksum_bench_fletcher PRIVATE checksum::checksum benchmark::benchmark) +target_link_libraries(checksum_bench_fletcher PRIVATE checksum::checksum checksum_test_data benchmark::benchmark) add_test(NAME benchmark_fletcher_smoke COMMAND checksum_bench_fletcher --benchmark_filter=^fletcher<16>/20/0$ --benchmark_min_time=0.001s) add_executable(checksum_bench_fletcher4 bench_fletcher4.cpp) target_compile_features(checksum_bench_fletcher4 PRIVATE cxx_std_23) -target_link_libraries(checksum_bench_fletcher4 PRIVATE checksum::checksum benchmark::benchmark) +target_link_libraries(checksum_bench_fletcher4 PRIVATE checksum::checksum checksum_test_data benchmark::benchmark) add_test(NAME benchmark_fletcher4_smoke COMMAND checksum_bench_fletcher4 --benchmark_filter=^fletcher4/20$ --benchmark_min_time=0.001s) add_executable(checksum_bench_adler32 bench_adler32.cpp) target_compile_features(checksum_bench_adler32 PRIVATE cxx_std_23) -target_link_libraries(checksum_bench_adler32 PRIVATE checksum::checksum benchmark::benchmark) +target_link_libraries(checksum_bench_adler32 PRIVATE checksum::checksum checksum_test_data benchmark::benchmark) add_test(NAME benchmark_adler32_smoke COMMAND checksum_bench_adler32 --benchmark_filter=^adler32/20/0$ --benchmark_min_time=0.001s) add_executable(checksum_bench_xxhash bench_xxhash.cpp) target_compile_features(checksum_bench_xxhash PRIVATE cxx_std_23) -target_link_libraries(checksum_bench_xxhash PRIVATE checksum::checksum benchmark::benchmark) +target_link_libraries(checksum_bench_xxhash PRIVATE checksum::checksum checksum_test_data benchmark::benchmark) add_test(NAME benchmark_xxhash_smoke COMMAND checksum_bench_xxhash --benchmark_filter=^xxhash64/20$ --benchmark_min_time=0.001s) add_executable(checksum_bench_murmur3 bench_murmur3.cpp) target_compile_features(checksum_bench_murmur3 PRIVATE cxx_std_23) -target_link_libraries(checksum_bench_murmur3 PRIVATE checksum::checksum benchmark::benchmark) +target_link_libraries(checksum_bench_murmur3 PRIVATE checksum::checksum checksum_test_data benchmark::benchmark) add_test(NAME benchmark_murmur3_smoke COMMAND checksum_bench_murmur3 --benchmark_filter=^murmur3_128/20$ --benchmark_min_time=0.001s) add_test(NAME benchmark_xxh3_smoke COMMAND checksum_bench_xxhash --benchmark_filter=^xxh3_128/20$ --benchmark_min_time=0.001s) diff --git a/tests/benchmarks/bench_adler32.cpp b/tests/benchmarks/bench_adler32.cpp index d82514d..87c59d2 100644 --- a/tests/benchmarks/bench_adler32.cpp +++ b/tests/benchmarks/bench_adler32.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -12,14 +13,7 @@ namespace { void adler32(benchmark::State &state) { - std::vector data(static_cast(state.range(0) + state.range(1))); - std::uint32_t seed = 0x12345678U; // xorshift32 - for(auto &byte : data) { - seed ^= seed << 13U; - seed ^= seed >> 17U; - seed ^= seed << 5U; - byte = static_cast(seed); - } + std::vector const data = random_bytes(static_cast(state.range(0) + state.range(1))); auto message = std::span(data).subspan(static_cast(state.range(1))); for(auto _ : state) { benchmark::DoNotOptimize(message); diff --git a/tests/benchmarks/bench_crc.cpp b/tests/benchmarks/bench_crc.cpp index c043d22..92a37ef 100644 --- a/tests/benchmarks/bench_crc.cpp +++ b/tests/benchmarks/bench_crc.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -22,17 +23,7 @@ using namespace checksum; constexpr std::array sizes{16, 32, 64, 256, 4096, std::size_t{1} << 20}; std::vector const &input() { - static std::vector const data = [] { - std::vector bytes(sizes.back()); - std::uint32_t state = 0x12345678U; // xorshift32: fixed, incompressible-looking content - for(auto &byte : bytes) { - state ^= state << 13U; - state ^= state >> 17U; - state ^= state << 5U; - byte = static_cast(state); - } - return bytes; - }(); + static std::vector const data = random_bytes(sizes.back()); return data; } diff --git a/tests/benchmarks/bench_fletcher.cpp b/tests/benchmarks/bench_fletcher.cpp index 27a7657..dc1b08c 100644 --- a/tests/benchmarks/bench_fletcher.cpp +++ b/tests/benchmarks/bench_fletcher.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -12,14 +13,7 @@ namespace { template void fletcher(benchmark::State &state) { - std::vector data(static_cast(state.range(0) + state.range(1))); - std::uint32_t seed = 0x12345678U; // xorshift32 - for(auto &byte : data) { - seed ^= seed << 13U; - seed ^= seed >> 17U; - seed ^= seed << 5U; - byte = static_cast(seed); - } + std::vector const data = random_bytes(static_cast(state.range(0) + state.range(1))); auto message = std::span(data).subspan(static_cast(state.range(1))); for(auto _ : state) { benchmark::DoNotOptimize(message); diff --git a/tests/benchmarks/bench_fletcher4.cpp b/tests/benchmarks/bench_fletcher4.cpp index 3800d68..e3d8310 100644 --- a/tests/benchmarks/bench_fletcher4.cpp +++ b/tests/benchmarks/bench_fletcher4.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -12,14 +13,7 @@ namespace { void fletcher4(benchmark::State &state) { - std::vector data(static_cast(state.range(0))); - std::uint32_t seed = 0x12345678U; // xorshift32 - for(auto &byte : data) { - seed ^= seed << 13U; - seed ^= seed >> 17U; - seed ^= seed << 5U; - byte = static_cast(seed); - } + std::vector const data = random_bytes(static_cast(state.range(0))); std::span message = data; for(auto _ : state) { benchmark::DoNotOptimize(message); diff --git a/tests/benchmarks/bench_internet.cpp b/tests/benchmarks/bench_internet.cpp index 0099d13..fb51ecb 100644 --- a/tests/benchmarks/bench_internet.cpp +++ b/tests/benchmarks/bench_internet.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -12,14 +13,7 @@ namespace { void internet(benchmark::State &state) { - std::vector data(static_cast(state.range(0))); - std::uint32_t seed = 0x12345678U; // xorshift32 - for(auto &byte : data) { - seed ^= seed << 13U; - seed ^= seed >> 17U; - seed ^= seed << 5U; - byte = static_cast(seed); - } + std::vector const data = random_bytes(static_cast(state.range(0))); std::span message = data; for(auto _ : state) { benchmark::DoNotOptimize(message); diff --git a/tests/benchmarks/bench_murmur3.cpp b/tests/benchmarks/bench_murmur3.cpp index 9cf0644..3fec256 100644 --- a/tests/benchmarks/bench_murmur3.cpp +++ b/tests/benchmarks/bench_murmur3.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -12,14 +13,7 @@ namespace { template void run(benchmark::State &state) { - std::vector data(static_cast(state.range(0))); - std::uint32_t seed = 0x12345678U; // xorshift32 - for(auto &byte : data) { - seed ^= seed << 13U; - seed ^= seed >> 17U; - seed ^= seed << 5U; - byte = static_cast(seed); - } + std::vector const data = random_bytes(static_cast(state.range(0))); std::span message = data; for(auto _ : state) { benchmark::DoNotOptimize(message); diff --git a/tests/benchmarks/bench_xxhash.cpp b/tests/benchmarks/bench_xxhash.cpp index b1dede2..f6c6cb9 100644 --- a/tests/benchmarks/bench_xxhash.cpp +++ b/tests/benchmarks/bench_xxhash.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -13,14 +14,7 @@ namespace { template void run(benchmark::State &state, Hash hash) { - std::vector data(static_cast(state.range(0))); - std::uint32_t seed = 0x12345678U; // xorshift32 - for(auto &byte : data) { - seed ^= seed << 13U; - seed ^= seed >> 17U; - seed ^= seed << 5U; - byte = static_cast(seed); - } + std::vector const data = random_bytes(static_cast(state.range(0))); std::span message = data; for(auto _ : state) { benchmark::DoNotOptimize(message); diff --git a/tests/include/test_data.hpp b/tests/include/test_data.hpp new file mode 100644 index 0000000..07aff32 --- /dev/null +++ b/tests/include/test_data.hpp @@ -0,0 +1,31 @@ +#ifndef CHECKSUM_TESTS_TEST_DATA_HPP +#define CHECKSUM_TESTS_TEST_DATA_HPP + +#include +#include +#include +#include + +// Fills data with the low byte of each xorshift32 step from 0x12345678 ^ seed. Seed 0 gives the message of the reference vectors. +constexpr void fill_random(std::span data, std::uint32_t seed = 0) noexcept; + +// size bytes of fill_random(). +inline std::vector random_bytes(std::size_t size, std::uint32_t seed = 0); + +constexpr void fill_random(std::span data, std::uint32_t seed) noexcept { + std::uint32_t state = 0x12345678U ^ seed; + for(auto &byte : data) { + state ^= state << 13U; + state ^= state >> 17U; + state ^= state << 5U; + byte = static_cast(state); + } +} + +inline std::vector random_bytes(std::size_t size, std::uint32_t seed) { + std::vector result(size); + fill_random(result, seed); + return result; +} + +#endif // CHECKSUM_TESTS_TEST_DATA_HPP diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt index 3ac1533..c0c9bcc 100644 --- a/tests/unit_tests/CMakeLists.txt +++ b/tests/unit_tests/CMakeLists.txt @@ -32,14 +32,14 @@ target_sources( include/xxhash_reference_vectors.hpp ) -target_link_libraries(checksum_ut PRIVATE checksum::checksum GTest::gtest_main) +target_link_libraries(checksum_ut PRIVATE checksum::checksum checksum_test_data GTest::gtest_main) # Built with NDEBUG to test behavior with precondition checks disabled. add_executable(checksum_ut_unchecked) target_compile_features(checksum_ut_unchecked PRIVATE cxx_std_23) target_sources(checksum_ut_unchecked PRIVATE ut_crc_unchecked.cpp PRIVATE FILE_SET HEADERS BASE_DIRS include FILES include/crc_test_support.hpp) target_compile_definitions(checksum_ut_unchecked PRIVATE NDEBUG) -target_link_libraries(checksum_ut_unchecked PRIVATE checksum::checksum GTest::gtest_main) +target_link_libraries(checksum_ut_unchecked PRIVATE checksum::checksum checksum_test_data GTest::gtest_main) include(GoogleTest) gtest_discover_tests(checksum_ut) diff --git a/tests/unit_tests/include/crc_test_support.hpp b/tests/unit_tests/include/crc_test_support.hpp index 2575769..7410841 100644 --- a/tests/unit_tests/include/crc_test_support.hpp +++ b/tests/unit_tests/include/crc_test_support.hpp @@ -7,11 +7,11 @@ #include #include +#include #include #include #include -#include #include #include #include @@ -184,9 +184,6 @@ inline std::uint64_t reference_crc(crc_model const &model, std::span reference_prefixes(crc_model const &model, std::span data); -// Reproducible for a given seed. -inline std::vector random_bytes(std::size_t size, std::uint64_t seed); - // Packs message bits [first, first + count) of data into bytes in message bit order, for bit-split tests. inline std::vector extract_bits(std::span data, bool reflect_input, std::size_t first, std::size_t count); @@ -265,15 +262,6 @@ inline std::vector reference_prefixes(crc_model const &model, std return result; } -inline std::vector random_bytes(std::size_t size, std::uint64_t seed) { - std::mt19937_64 generator(seed); - std::vector result(size); - for(auto &byte : result) { - byte = static_cast(generator() & 0xFFU); - } - return result; -} - inline std::vector extract_bits(std::span data, bool reflect_input, std::size_t first, std::size_t count) { std::vector result((count + 7) / 8); for(std::size_t index = 0; index < count; ++index) { diff --git a/tests/unit_tests/include/fletcher4_reference_vectors.hpp b/tests/unit_tests/include/fletcher4_reference_vectors.hpp index 198f798..b829619 100644 --- a/tests/unit_tests/include/fletcher4_reference_vectors.hpp +++ b/tests/unit_tests/include/fletcher4_reference_vectors.hpp @@ -1,7 +1,7 @@ #ifndef CHECKSUM_TESTS_FLETCHER4_REFERENCE_VECTORS_HPP #define CHECKSUM_TESTS_FLETCHER4_REFERENCE_VECTORS_HPP -// fletcher4 of every prefix of whole words of a 1024-byte message and of a long_message_size-byte one, both from fill_message(). +// fletcher4 of every prefix of whole words of a 1024-byte message and of a long_message_size-byte one, both from fill_random(). // Computed with fletcher_4_scalar_native of OpenZFS module/zcommon/zfs_fletcher.c on a little-endian host. #include @@ -17,17 +17,6 @@ inline constexpr std::size_t prefix_count = 257; inline constexpr std::size_t long_message_size = (std::size_t{1} << 20U) + 4U; -// Fills data with the message: the low byte of each xorshift32 step from 0x12345678. -constexpr void fill_message(std::span data) { - std::uint32_t state = 0x12345678U; - for(auto &byte : data) { - state ^= state << 13U; - state ^= state >> 17U; - state ^= state << 5U; - byte = static_cast(state); - } -} - // prefixes[words]: the checksum of the first 4 * words bytes. inline constexpr std::array prefixes{{ {0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000}, diff --git a/tests/unit_tests/include/murmur3_reference_vectors.hpp b/tests/unit_tests/include/murmur3_reference_vectors.hpp index c53a6cd..818dd14 100644 --- a/tests/unit_tests/include/murmur3_reference_vectors.hpp +++ b/tests/unit_tests/include/murmur3_reference_vectors.hpp @@ -2,7 +2,7 @@ #define CHECKSUM_TESTS_MURMUR3_REFERENCE_VECTORS_HPP // MurmurHash3_x86_32 and MurmurHash3_x64_128 of every prefix of a 300-byte message and of a long_message_size-byte one, both from -// fill_message(), for three seeds each. Computed with the reference implementation, src/MurmurHash3.cpp of github.com/aappleby/smhasher. +// fill_random(), for three seeds each. Computed with the reference implementation, src/MurmurHash3.cpp of github.com/aappleby/smhasher. #include #include @@ -15,17 +15,6 @@ inline constexpr std::size_t prefix_count = 301; inline constexpr std::size_t long_message_size = (std::size_t{1} << 20U) + 7U; -// Fills data with the message: the low byte of each xorshift32 step from 0x12345678. -constexpr void fill_message(std::span data) { - std::uint32_t state = 0x12345678U; - for(auto &byte : data) { - state ^= state << 13U; - state ^= state >> 17U; - state ^= state << 5U; - byte = static_cast(state); - } -} - template struct vector_set { std::uint32_t seed; std::array prefixes; // prefixes[size]: the hash of the first size bytes. diff --git a/tests/unit_tests/include/xxh3_reference_vectors.hpp b/tests/unit_tests/include/xxh3_reference_vectors.hpp index 5f323b0..833552e 100644 --- a/tests/unit_tests/include/xxh3_reference_vectors.hpp +++ b/tests/unit_tests/include/xxh3_reference_vectors.hpp @@ -1,7 +1,7 @@ #ifndef CHECKSUM_TESTS_XXH3_REFERENCE_VECTORS_HPP #define CHECKSUM_TESTS_XXH3_REFERENCE_VECTORS_HPP -// XXH3-64 and XXH3-128 of the message of fill_message(): every prefix up to 300 bytes, the block_sizes prefixes, a digest of the +// XXH3-64 and XXH3-128 of the message of fill_random(): every prefix up to 300 bytes, the block_sizes prefixes, a digest of the // prefixes of 301 to 1100 bytes, a split_message_size-byte message and a long_message_size-byte one for three seeds each, and the // edge_sizes prefixes for the edge seeds. Computed with XXH3_64bits_withSeed() and XXH3_128bits_withSeed() of the reference // implementation, xxhash.h 0.8.4 of github.com/Cyan4973/xxHash. diff --git a/tests/unit_tests/include/xxhash_reference_vectors.hpp b/tests/unit_tests/include/xxhash_reference_vectors.hpp index 812c530..f9b6f1f 100644 --- a/tests/unit_tests/include/xxhash_reference_vectors.hpp +++ b/tests/unit_tests/include/xxhash_reference_vectors.hpp @@ -1,7 +1,7 @@ #ifndef CHECKSUM_TESTS_XXHASH_REFERENCE_VECTORS_HPP #define CHECKSUM_TESTS_XXHASH_REFERENCE_VECTORS_HPP -// XXH32 and XXH64 of every prefix of a 300-byte message and of a long_message_size-byte one, both from fill_message(), for three +// XXH32 and XXH64 of every prefix of a 300-byte message and of a long_message_size-byte one, both from fill_random(), for three // seeds each. Computed with the reference implementation, xxhash.h 0.8.4 of github.com/Cyan4973/xxHash. #include @@ -15,17 +15,6 @@ inline constexpr std::size_t prefix_count = 301; inline constexpr std::size_t long_message_size = (std::size_t{1} << 20U) + 7U; -// Fills data with the message: the low byte of each xorshift32 step from 0x12345678. -constexpr void fill_message(std::span data) { - std::uint32_t state = 0x12345678U; - for(auto &byte : data) { - state ^= state << 13U; - state ^= state >> 17U; - state ^= state << 5U; - byte = static_cast(state); - } -} - template struct vector_set { Value seed; std::array prefixes; // prefixes[size]: the hash of the first size bytes. diff --git a/tests/unit_tests/ut_adler32.cpp b/tests/unit_tests/ut_adler32.cpp index bb4f66f..4cc8f73 100644 --- a/tests/unit_tests/ut_adler32.cpp +++ b/tests/unit_tests/ut_adler32.cpp @@ -3,12 +3,12 @@ #include #include +#include #include #include #include #include -#include #include #include #include @@ -37,15 +37,6 @@ std::uint32_t reference(std::span data, std::uint32_t sum1 = 1, return (sum2 << 16U) | sum1; } -std::vector random_bytes(std::size_t size, std::uint32_t seed) { - std::mt19937 generator(seed); - std::vector data(size); - for(auto &byte : data) { - byte = static_cast(generator()); - } - return data; -} - TEST(adler32, published_examples) { for(auto const text : {""sv, "a"sv, "abc"sv, "Wikipedia"sv, "123456789"sv}) { auto const message = std::as_bytes(std::span(text)); @@ -128,16 +119,10 @@ TEST(adler32, split_before_long_chunks) { // Every prefix of this size stays within the default step limit of Clang's constant evaluator. constexpr std::size_t constant_message_size = 200; -// Pseudo-random bytes the constant evaluator can produce (xorshift32). +// Pseudo-random bytes the constant evaluator can produce. constexpr std::array constant_message = [] { std::array result{}; - std::uint32_t state = 0x12345678U; - for(auto &byte : result) { - state ^= state << 13U; - state ^= state >> 17U; - state ^= state << 5U; - byte = static_cast(state); - } + fill_random(result); return result; }(); diff --git a/tests/unit_tests/ut_crc_acceleration.cpp b/tests/unit_tests/ut_crc_acceleration.cpp index 1031a81..2d28cdc 100644 --- a/tests/unit_tests/ut_crc_acceleration.cpp +++ b/tests/unit_tests/ut_crc_acceleration.cpp @@ -116,7 +116,7 @@ using folding_strategies = ::testing::Types; TYPED_TEST_SUITE(crc_acceleration_typed, folding_strategies); TYPED_TEST(crc_acceleration_typed, MatchesByteTableForEveryCatalogSet) { - auto const message = crc_test::random_bytes(longest + offsets.back(), 0x5EED); + auto const message = random_bytes(longest + offsets.back(), 0x5EED); auto const all = every_length(); auto const thresholds = threshold_lengths(); std::vector tested; diff --git a/tests/unit_tests/ut_crc_accumulator.cpp b/tests/unit_tests/ut_crc_accumulator.cpp index 5b5a32a..87c2629 100644 --- a/tests/unit_tests/ut_crc_accumulator.cpp +++ b/tests/unit_tests/ut_crc_accumulator.cpp @@ -70,7 +70,7 @@ static_assert(value_is_non_destructive()); // Every byte split of a 64-byte message, every bit split of its first 64 bits, and bit-by-bit updates equal compute(). TEST(CrcAccumulator, EqualsComputeForEverySplit) { - auto const message = crc_test::random_bytes(64, 99); + auto const message = random_bytes(64, 99); std::span const data(message); for(crc_model const &model : models) { for_each_engine(model, [&](auto const &engine) { diff --git a/tests/unit_tests/ut_crc_engine.cpp b/tests/unit_tests/ut_crc_engine.cpp index f60b940..fa0917f 100644 --- a/tests/unit_tests/ut_crc_engine.cpp +++ b/tests/unit_tests/ut_crc_engine.cpp @@ -150,7 +150,7 @@ TEST(CrcEngine, InitialAndFinalize) { // Every range kind gives the same result, including non-contiguous ranges, which are copied in 64-byte chunks. TEST(CrcEngine, ByteRangeAdapters) { - auto const bytes = crc_test::random_bytes(200, 7); + auto const bytes = random_bytes(200, 7); std::vector uchars; std::vector schars; std::list chars; @@ -181,7 +181,7 @@ TEST(CrcEngine, EquivalenceLengthsAndOffsets) { constexpr std::size_t max_length = 1024; constexpr std::size_t every_length = 320; constexpr std::size_t length_step = 37; - auto const message = crc_test::random_bytes(max_length, 42); + auto const message = random_bytes(max_length, 42); alignas(64) std::array buffer{}; for(crc_model const &model : models) { auto const expected = crc_test::reference_prefixes(model, message); @@ -201,7 +201,7 @@ TEST(CrcEngine, EquivalenceLengthsAndOffsets) { // Every byte split of a 64-byte message, every bit split of its first 64 bits, and bit-by-bit updates. TEST(CrcEngine, ChunkingInvariance) { - auto const message = crc_test::random_bytes(64, 99); + auto const message = random_bytes(64, 99); std::span const data(message); for(crc_model const &model : models) { auto const expected = crc_test::reference_crc(model, data); @@ -228,7 +228,7 @@ TEST(CrcEngine, ChunkingInvariance) { // Bit lengths 0..320 against the reference; multiples of 8 equal the byte overloads. TEST(CrcEngine, BitLengths) { - auto const message = crc_test::random_bytes(40, 5); + auto const message = random_bytes(40, 5); std::span const data(message); for(crc_model const &model : models) { for_each_engine(model, [&](auto const &engine) { @@ -266,7 +266,7 @@ TEST(CrcEngine, TailBitsUseOnlyMessageBits) { // variants use an all-ones initial value and final XOR. TEST(CrcEngine, AllWidthsAgainstReference) { std::mt19937_64 generator(2024); - auto const message = crc_test::random_bytes(40, 11); + auto const message = random_bytes(40, 11); std::span const data(message); for(unsigned width = 1; width <= 64; ++width) { auto const mask = crc_test::mask_of(width); @@ -297,7 +297,7 @@ TEST(CrcEngine, AllWidthsAgainstReference) { } TEST(CrcEngine, WiderRegisterSameResult) { - auto const message = crc_test::random_bytes(100, 3); + auto const message = random_bytes(100, 3); auto const narrow = *crc_engine::create(crc12_umts); auto const wide = *crc_engine::create(crc12_umts); EXPECT_EQ(narrow.compute(message), wide.compute(message)); @@ -372,7 +372,7 @@ TEST(CrcEngine, UserStrategy) { EXPECT_FALSE((crc_engine::create(crc15_can))); EXPECT_EQ(iso_hdlc->compute("123456789"sv), 0xCBF43926U); EXPECT_EQ(mpeg2->compute("123456789"sv), 0x0376E6E7U); - auto const message = crc_test::random_bytes(300, 8); + auto const message = random_bytes(300, 8); for(std::size_t bits = 0; bits <= message.size() * 8; bits += 7) { EXPECT_EQ(iso_hdlc->compute(message, bits), crc_test::reference_crc(models[9], message, bits)); EXPECT_EQ(mpeg2->compute(message, bits), crc_test::reference_crc(models[10], message, bits)); diff --git a/tests/unit_tests/ut_fletcher.cpp b/tests/unit_tests/ut_fletcher.cpp index 35dabd2..2696ad3 100644 --- a/tests/unit_tests/ut_fletcher.cpp +++ b/tests/unit_tests/ut_fletcher.cpp @@ -3,13 +3,13 @@ #include #include +#include #include #include #include #include #include -#include #include #include #include @@ -55,15 +55,6 @@ template std::uint64_t reference(std::span dat return (sum2 << (Width / 2)) | sum1; } -std::vector random_bytes(std::size_t size, std::uint32_t seed) { - std::mt19937 generator(seed); - std::vector data(size); - for(auto &byte : data) { - byte = static_cast(generator()); - } - return data; -} - template class fletcher : public testing::Test {}; using widths = testing::Types, std::integral_constant, std::integral_constant>; @@ -182,16 +173,10 @@ TYPED_TEST(fletcher, split_before_long_chunks) { // Every prefix of this size stays within the default step limit of Clang's constant evaluator. constexpr std::size_t constant_message_size = 200; -// Pseudo-random bytes the constant evaluator can produce (xorshift32). +// Pseudo-random bytes the constant evaluator can produce. constexpr std::array constant_message = [] { std::array result{}; - std::uint32_t state = 0x12345678U; - for(auto &byte : result) { - state ^= state << 13U; - state ^= state >> 17U; - state ^= state << 5U; - byte = static_cast(state); - } + fill_random(result); return result; }(); diff --git a/tests/unit_tests/ut_fletcher4.cpp b/tests/unit_tests/ut_fletcher4.cpp index 04c53cc..91df422 100644 --- a/tests/unit_tests/ut_fletcher4.cpp +++ b/tests/unit_tests/ut_fletcher4.cpp @@ -5,13 +5,13 @@ #include #include +#include #include #include #include #include #include -#include #include #include #include @@ -26,7 +26,7 @@ constexpr std::size_t constant_message_size = 200; constexpr std::array constant_message = [] { std::array result{}; - fletcher4_test::fill_message(result); + fill_random(result); return result; }(); @@ -55,18 +55,9 @@ fletcher4_value reference(std::span data) { return {a, b, c, d}; } -std::vector random_bytes(std::size_t size, std::uint32_t seed) { - std::mt19937 generator(seed); - std::vector data(size); - for(auto &byte : data) { - byte = static_cast(generator()); - } - return data; -} - TEST(fletcher4, reference_vectors) { std::vector data(fletcher4_test::long_message_size); - fletcher4_test::fill_message(data); + fill_random(data); auto const message = std::span(data); for(std::size_t words = 0; words < fletcher4_test::prefix_count; ++words) { ASSERT_EQ(fletcher4_compute(message.first(4 * words)), fletcher4_test::prefixes[words]) << "words " << words; diff --git a/tests/unit_tests/ut_internet.cpp b/tests/unit_tests/ut_internet.cpp index 678e308..1f5daa9 100644 --- a/tests/unit_tests/ut_internet.cpp +++ b/tests/unit_tests/ut_internet.cpp @@ -3,12 +3,12 @@ #include #include +#include #include #include #include #include -#include #include #include #include @@ -43,15 +43,6 @@ std::uint16_t reference(std::span data) { return static_cast(~sum); } -std::vector random_bytes(std::size_t size, std::uint32_t seed) { - std::mt19937 generator(seed); - std::vector data(size); - for(auto &byte : data) { - byte = static_cast(generator()); - } - return data; -} - static_assert(internet_finalize(internet_update({}, rfc1071_example)) == 0x220D); static_assert(internet_update({}, rfc1071_example) == internet_state{.sum = 0xDDF2, .odd = false}); static_assert(internet_compute(ipv4_header) == 0xB861); @@ -153,16 +144,10 @@ TEST(internet, split_before_long_chunks) { constexpr std::size_t constant_message_size = 300; -// Pseudo-random bytes the constant evaluator can produce (xorshift32). +// Pseudo-random bytes the constant evaluator can produce. constexpr std::array constant_message = [] { std::array result{}; - std::uint32_t state = 0x12345678U; - for(auto &byte : result) { - state ^= state << 13U; - state ^= state >> 17U; - state ^= state << 5U; - byte = static_cast(state); - } + fill_random(result); return result; }(); diff --git a/tests/unit_tests/ut_murmur3.cpp b/tests/unit_tests/ut_murmur3.cpp index 122ff12..588b62f 100644 --- a/tests/unit_tests/ut_murmur3.cpp +++ b/tests/unit_tests/ut_murmur3.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -26,7 +27,7 @@ using murmur3_test::murmur3_32_vectors; constexpr std::array message = [] { std::array result{}; - murmur3_test::fill_message(result); + fill_random(result); return result; }(); @@ -195,7 +196,7 @@ TEST(murmur3_aliases, match_generic_form) { TYPED_TEST(murmur3, long_message) { constexpr unsigned width = TypeParam::value; std::vector data(murmur3_test::long_message_size); - murmur3_test::fill_message(data); + fill_random(data); for(auto const &set : vectors()) { EXPECT_EQ(murmur3_compute(data, set.seed), set.long_message) << "seed " << set.seed; EXPECT_EQ(chunked(data, 4099, set.seed), set.long_message) << "seed " << set.seed; diff --git a/tests/unit_tests/ut_xxh3.cpp b/tests/unit_tests/ut_xxh3.cpp index 0bbfa93..64e364e 100644 --- a/tests/unit_tests/ut_xxh3.cpp +++ b/tests/unit_tests/ut_xxh3.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include @@ -34,7 +35,7 @@ constexpr std::size_t prefix_limit = xxhash_test::prefix_count - 1; // The first Size bytes of the message of the reference vectors. template constexpr std::array make_message() { std::array result{}; - xxhash_test::fill_message(result); + fill_random(result); return result; } @@ -303,7 +304,7 @@ TYPED_TEST(xxh3, byte_ranges) { TYPED_TEST(xxh3, long_message) { constexpr unsigned width = TypeParam::value; std::vector data(xxhash_test::long_message_size); - xxhash_test::fill_message(data); + fill_random(data); for(auto const &set : vectors()) { EXPECT_EQ(xxh3_compute(data, set.seed), set.long_message) << "seed " << set.seed; EXPECT_EQ(chunked(data, 4099, set.seed), set.long_message) << "seed " << set.seed; diff --git a/tests/unit_tests/ut_xxhash.cpp b/tests/unit_tests/ut_xxhash.cpp index ea5f02c..bd25a7b 100644 --- a/tests/unit_tests/ut_xxhash.cpp +++ b/tests/unit_tests/ut_xxhash.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -25,7 +26,7 @@ using xxhash_test::xxhash64_vectors; constexpr std::array message = [] { std::array result{}; - xxhash_test::fill_message(result); + fill_random(result); return result; }(); @@ -155,7 +156,7 @@ TYPED_TEST(xxhash, byte_ranges) { TYPED_TEST(xxhash, long_message) { constexpr unsigned width = TypeParam::value; std::vector data(xxhash_test::long_message_size); - xxhash_test::fill_message(data); + fill_random(data); for(auto const &set : vectors()) { EXPECT_EQ(xxhash_compute(data, set.seed), set.long_message) << "seed " << set.seed; EXPECT_EQ(chunked(data, 4099, set.seed), set.long_message) << "seed " << set.seed; From 19172820e3de49256f4506230a91496100d6911d Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:28:35 +0200 Subject: [PATCH 33/64] feat: checksum::hash128, one result type for 128-bit hashes --- src/CMakeLists.txt | 1 + src/include/checksum/hash128.hpp | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 src/include/checksum/hash128.hpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 513b866..ec65828 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -29,6 +29,7 @@ target_sources( include/checksum/crc_catalog.hpp include/checksum/fletcher.hpp include/checksum/fletcher4.hpp + include/checksum/hash128.hpp include/checksum/internet.hpp include/checksum/murmur3.hpp include/checksum/xxh3.hpp diff --git a/src/include/checksum/hash128.hpp b/src/include/checksum/hash128.hpp new file mode 100644 index 0000000..f871baa --- /dev/null +++ b/src/include/checksum/hash128.hpp @@ -0,0 +1,26 @@ +#ifndef CHECKSUM_HASH128_HPP +#define CHECKSUM_HASH128_HPP + +#include + +/** + * @addtogroup checksum + * @{ + */ + +namespace checksum { + +/// A 128-bit hash value, the result of XXH3-128 and MurmurHash3_x64_128. +struct hash128 { + std::uint64_t low = 0; ///< The lower 64 bits. + std::uint64_t high = 0; ///< The upper 64 bits. + + /// Equal if both halves are. + [[nodiscard]] constexpr bool operator==(hash128 const &) const noexcept = default; +}; + +} // namespace checksum + +///@} + +#endif // CHECKSUM_HASH128_HPP From d3b83b98a4654df2b6f0e5458d3a1346a68c9bbf Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:28:35 +0200 Subject: [PATCH 34/64] refactor(xxh3)!: XXH3-128 returns hash128, xxh3_hash128 removed --- doc/xxhash.md | 8 ++-- examples/xxh3/dedup_blocks.cpp | 6 +-- src/include/checksum/xxh3.hpp | 44 ++++++++----------- src/xxh3/stripe_loop.cpp | 2 +- .../include/xxh3_reference_vectors.hpp | 4 +- tests/unit_tests/ut_xxh3.cpp | 6 +-- 6 files changed, 31 insertions(+), 39 deletions(-) diff --git a/doc/xxhash.md b/doc/xxhash.md index e4b4650..843d5cb 100644 --- a/doc/xxhash.md +++ b/doc/xxhash.md @@ -17,7 +17,7 @@ using namespace std::literals; // One call, seed 0 or another seed. std::uint32_t small = checksum::xxh32_compute(key); std::uint64_t hash = checksum::xxh3_64_compute(key, 1234); -checksum::xxh3_hash128 wide = checksum::xxh3_128_compute(key); +checksum::hash128 wide = checksum::xxh3_128_compute(key); // Incremental: a message may be split anywhere. checksum::xxh3_64_state state{.seed = 1234}; @@ -30,7 +30,7 @@ static_assert(checksum::xxh32_compute("abc"sv) == 0x32D153FF); static_assert(checksum::xxh64_compute("abc"sv) == 0x44BC2CF5AD770999); static_assert(checksum::xxh3_64_compute("abc"sv) == 0x78AF5F94892F3950); static_assert(checksum::xxh3_128_compute("abc"sv) == - checksum::xxh3_hash128{.low = 0x78AF5F94892F3950, .high = 0x06B05AB6733A6185}); + checksum::hash128{.low = 0x78AF5F94892F3950, .high = 0x06B05AB6733A6185}); ``` `examples/xxh3` has complete programs: the XXH3-64 hash of a file read in chunks, deduplication of blocks by their @@ -78,11 +78,11 @@ a cache keyed by the hash of its input. | `xxh3_update(state, data)` | Folds `data` into `state` and returns the new state. | | `xxh3_finalize(state)` | The hash of the message folded into `state`; the state is unchanged. | | `xxh3_compute(data, seed = 0)` | `xxh3_finalize(xxh3_update(xxh3_state{.seed = seed}, data))`. | -| `xxh3_hash128` | The XXH3-128 hash: `low` and `high`, its lower and upper 64 bits, as `XXH128_hash_t` of the reference. Compares with `==`. | +| `hash128` | The XXH3-128 hash: `low` and `high`, its lower and upper 64 bits, as `XXH128_hash_t` of the reference. Compares with `==`. | | `xxh3_64_state`, `xxh3_128_state` | `xxh3_state<64>` and `xxh3_state<128>`. | | `xxh3_64_compute(data, seed = 0)`, `xxh3_128_compute(data, seed = 0)` | `xxh3_compute<64>` and `xxh3_compute<128>`. `xxh3_update` and `xxh3_finalize` take the width from the state. | -`xxh3_state::value_type` is `std::uint64_t` for Width 64 and `xxh3_hash128` for Width 128. The seed is a +`xxh3_state::value_type` is `std::uint64_t` for Width 64 and `hash128` for Width 128. The seed is a `std::uint64_t` for both. The hashes always use the default secret; a custom secret cannot be passed. The state keeps the last 1 to 256 bytes passed in its buffer and folds the rest into the accumulators, so it can diff --git a/examples/xxh3/dedup_blocks.cpp b/examples/xxh3/dedup_blocks.cpp index 0535eb4..c7c5543 100644 --- a/examples/xxh3/dedup_blocks.cpp +++ b/examples/xxh3/dedup_blocks.cpp @@ -14,11 +14,11 @@ using namespace std::literals; // The hash is uniformly distributed, so its lower half is a good bucket index. struct hash128_hasher { - std::size_t operator()(checksum::xxh3_hash128 const &hash) const noexcept { return static_cast(hash.low); } + std::size_t operator()(checksum::hash128 const &hash) const noexcept { return static_cast(hash.low); } }; // The XXH3-128 check value of "abc". -static_assert(checksum::xxh3_128_compute("abc"sv) == checksum::xxh3_hash128{.low = 0x78AF5F94892F3950, .high = 0x06B05AB6733A6185}); +static_assert(checksum::xxh3_128_compute("abc"sv) == checksum::hash128{.low = 0x78AF5F94892F3950, .high = 0x06B05AB6733A6185}); int main() { constexpr std::size_t block_size = 4096; @@ -33,7 +33,7 @@ int main() { } // Block number of the first copy of each content. - std::unordered_map first_copy; + std::unordered_map first_copy; for(std::size_t block = 0; block < block_count; ++block) { std::span const data = std::span(image).subspan(block * block_size, block_size); first_copy.try_emplace(checksum::xxh3_128_compute(data), block); diff --git a/src/include/checksum/xxh3.hpp b/src/include/checksum/xxh3.hpp index 3aaca2c..11deef4 100644 --- a/src/include/checksum/xxh3.hpp +++ b/src/include/checksum/xxh3.hpp @@ -2,6 +2,7 @@ #define CHECKSUM_XXH3_HPP #include +#include #include #include @@ -25,22 +26,13 @@ namespace checksum { -/// A 128-bit XXH3 hash. -struct xxh3_hash128 { - std::uint64_t low = 0; ///< The lower 64 bits. - std::uint64_t high = 0; ///< The upper 64 bits. - - /// Equal if both halves are. - [[nodiscard]] constexpr bool operator==(xxh3_hash128 const &) const noexcept = default; -}; - /// Running XXH3-64 (Width 64) or XXH3-128 (Width 128) hash, 336 bytes. Every value is valid; the default is the empty message with seed 0, and /// xxh3_state{.seed = seed} starts one with another seed. template requires(Width == 64 || Width == 128) struct xxh3_state { - /// The hash type: std::uint64_t or xxh3_hash128. - using value_type = std::conditional_t; + /// The hash type: std::uint64_t or hash128. + using value_type = std::conditional_t; /// Lane accumulators of the folded input: all but the last 1 to 256 bytes, rounded down to a multiple of 256. std::array accumulators{0xC2B2AE3DU, 0x9E3779B185EBCA87U, 0xC2B2AE3D27D4EB4FU, 0x165667B19E3779F9U, @@ -80,7 +72,7 @@ using xxh3_128_state = xxh3_state<128>; template [[nodiscard]] constexpr std::uint64_t xxh3_64_compute(Range &&data, std::uint64_t seed = 0) noexcept; /// The XXH3-128 hash of data: xxh3_compute<128>(data, seed). -template [[nodiscard]] constexpr xxh3_hash128 xxh3_128_compute(Range &&data, std::uint64_t seed = 0) noexcept; +template [[nodiscard]] constexpr hash128 xxh3_128_compute(Range &&data, std::uint64_t seed = 0) noexcept; } // namespace checksum @@ -136,10 +128,10 @@ inline constexpr std::array default_secret_words 0x49DAF0B751DD0D17U, 0x9E68D429265516D3U, 0xFCA1477D58BE162BU, 0xCE31D07AD1B8F88FU, 0x280416958F3ACB45U, 0x7E404BBBCAFBD7AFU}; // The full product of two 64-bit values, from four 32-bit products. -constexpr xxh3_hash128 multiply_portable(std::uint64_t left, std::uint64_t right) noexcept; +constexpr hash128 multiply_portable(std::uint64_t left, std::uint64_t right) noexcept; // multiply_portable(), or a native 128-bit multiplication at run time where the compiler has one. -constexpr xxh3_hash128 multiply(std::uint64_t left, std::uint64_t right) noexcept; +constexpr hash128 multiply(std::uint64_t left, std::uint64_t right) noexcept; // The exclusive or of the two Integer words at secret. template constexpr Integer secret_xor(std::byte const *secret) noexcept; @@ -163,14 +155,14 @@ template constexpr auto with_secret(std::uint64_t seed, Functio constexpr std::uint64_t mix_step(std::byte const *data, std::byte const *secret, std::uint64_t seed) noexcept; // Mixes two 16-byte chunks into both halves of a 128-bit accumulator. -constexpr void mix_two_chunks(xxh3_hash128 &accumulator, std::byte const *first, std::byte const *second, std::byte const *secret, +constexpr void mix_two_chunks(hash128 &accumulator, std::byte const *first, std::byte const *second, std::byte const *secret, std::uint64_t seed) noexcept; // The hash of 0 to 16 bytes. template constexpr value hash_small(std::span data, std::uint64_t seed) noexcept; // The 128-bit hash of 17 to 240 bytes from its accumulator. -constexpr xxh3_hash128 finish_medium(xxh3_hash128 const &accumulator, std::uint64_t length, std::uint64_t seed) noexcept; +constexpr hash128 finish_medium(hash128 const &accumulator, std::uint64_t length, std::uint64_t seed) noexcept; // The hash of 17 to 128 bytes. template constexpr value hash_medium(std::span data, std::uint64_t seed) noexcept; @@ -234,7 +226,7 @@ template constexpr void update(xxh3_state &state, std::s namespace checksum::xxh3_detail { -constexpr xxh3_hash128 multiply_portable(std::uint64_t left, std::uint64_t right) noexcept { +constexpr hash128 multiply_portable(std::uint64_t left, std::uint64_t right) noexcept { std::uint64_t const low_low = (left & low_half_mask) * (right & low_half_mask); std::uint64_t const high_low = (left >> 32U) * (right & low_half_mask); std::uint64_t const low_high = (left & low_half_mask) * (right >> 32U); @@ -243,7 +235,7 @@ constexpr xxh3_hash128 multiply_portable(std::uint64_t left, std::uint64_t right return {.low = (cross << 32U) | (low_low & low_half_mask), .high = (high_low >> 32U) + (cross >> 32U) + high_high}; } -constexpr xxh3_hash128 multiply(std::uint64_t left, std::uint64_t right) noexcept { +constexpr hash128 multiply(std::uint64_t left, std::uint64_t right) noexcept { #ifdef __SIZEOF_INT128__ if !consteval { __extension__ typedef unsigned __int128 wide_type; // NOLINT(modernize-use-using): __extension__ silences -Wpedantic only on a typedef. @@ -264,7 +256,7 @@ constexpr std::uint64_t multiply_fold(std::uint64_t left, std::uint64_t right) n return run_time_multiply_fold(left, right); } #endif - xxh3_hash128 const product = multiply(left, right); + hash128 const product = multiply(left, right); return product.low ^ product.high; } @@ -300,7 +292,7 @@ constexpr std::uint64_t mix_step(std::byte const *data, std::byte const *secret, load(data + 8) ^ (load(secret + 8) - seed)); } -constexpr void mix_two_chunks(xxh3_hash128 &accumulator, std::byte const *first, std::byte const *second, std::byte const *secret, +constexpr void mix_two_chunks(hash128 &accumulator, std::byte const *first, std::byte const *second, std::byte const *secret, std::uint64_t seed) noexcept { accumulator.low += mix_step(first, secret, seed); accumulator.low ^= load(second) + load(second + 8); @@ -324,11 +316,11 @@ template constexpr value hash_small(std::span(secret + offset) - seed) ^ first ^ last; std::uint64_t const mixed_last = (secret_xor(secret + offset + 16) + seed) ^ last; - xxh3_hash128 product = multiply(mixed_first, primes_64::prime_1); + hash128 product = multiply(mixed_first, primes_64::prime_1); product.low += (length - 1) << length_shift; product.high += mixed_last + ((mixed_last & low_half_mask) * (primes_32::prime_2 - 1)); product.low ^= std::byteswap(product.high); - xxh3_hash128 const result = multiply(product.low, primes_64::prime_2); + hash128 const result = multiply(product.low, primes_64::prime_2); return {.low = avalanche(result.low), .high = avalanche(result.high + (product.high * primes_64::prime_2))}; } } @@ -345,7 +337,7 @@ template constexpr value hash_small(std::span> mix_shifts[1]); } else { std::uint64_t const mixed = (secret_xor(secret + 16) + modified_seed) ^ (first | (last << 32U)); - xxh3_hash128 const product = multiply(mixed, primes_64::prime_1 + (length << 2U)); + hash128 const product = multiply(mixed, primes_64::prime_1 + (length << 2U)); std::uint64_t const high = product.high + (product.low << 1U); std::uint64_t low = product.low ^ (high >> 3U); low ^= low >> mix_shifts[0]; @@ -373,7 +365,7 @@ template constexpr value hash_small(std::span constexpr value hash_midsize(std::span constexpr std::uint64_t xxh3_64_compute(Range &&data return xxh3_compute<64>(std::forward(data), seed); } -template constexpr xxh3_hash128 xxh3_128_compute(Range &&data, std::uint64_t seed) noexcept { +template constexpr hash128 xxh3_128_compute(Range &&data, std::uint64_t seed) noexcept { return xxh3_compute<128>(std::forward(data), seed); } diff --git a/src/xxh3/stripe_loop.cpp b/src/xxh3/stripe_loop.cpp index d65d6d2..3c9daa8 100644 --- a/src/xxh3/stripe_loop.cpp +++ b/src/xxh3/stripe_loop.cpp @@ -21,7 +21,7 @@ void stripe_loop(accumulator_array &accumulators, std::span dat } std::uint64_t run_time_multiply_fold(std::uint64_t left, std::uint64_t right) noexcept { - xxh3_hash128 const product = multiply_portable(left, right); + hash128 const product = multiply_portable(left, right); return product.low ^ product.high; } diff --git a/tests/unit_tests/include/xxh3_reference_vectors.hpp b/tests/unit_tests/include/xxh3_reference_vectors.hpp index 833552e..e152adb 100644 --- a/tests/unit_tests/include/xxh3_reference_vectors.hpp +++ b/tests/unit_tests/include/xxh3_reference_vectors.hpp @@ -58,7 +58,7 @@ inline constexpr std::array, 3> xxh3_64_edge_s 0xAA054F72CD253F11, 0xA8C1ED0FEF73898C, 0x442AB2B676166827, 0x8D1974D205576572, 0x3C12DF4D1A497E65, 0xEEE7096E77F42C05}}}, }}; -inline constexpr std::array, 3> xxh3_128_edge_seeds{{ +inline constexpr std::array, 3> xxh3_128_edge_seeds{{ {.seed = 0xFFFFFFFFFFFFFFFF, .hashes{{{.low = 0x2D10110A247D19DD, .high = 0x5334EC22748B5FCD}, {.low = 0xCFEEB3D75B3964DD, .high = 0xCA2BC6ABFBC14CC0}, @@ -301,7 +301,7 @@ inline constexpr std::array, 3> xxh3_64_vectors{{ .split_message = 0x85C10E7BDC91BC71}, }}; -inline constexpr std::array, 3> xxh3_128_vectors{{ +inline constexpr std::array, 3> xxh3_128_vectors{{ {.seed = 0x0000000000000000, .prefixes{{ {.low = 0x6001C324468D497F, .high = 0x99AA06D3014798D8}, {.low = 0x40F22CE7CA17BD07, .high = 0x71D3B97D97EE0755}, diff --git a/tests/unit_tests/ut_xxh3.cpp b/tests/unit_tests/ut_xxh3.cpp index 64e364e..4f843be 100644 --- a/tests/unit_tests/ut_xxh3.cpp +++ b/tests/unit_tests/ut_xxh3.cpp @@ -93,7 +93,7 @@ using namespace std::literals; static_assert(xxh3_compute<64>(""sv) == 0x2D06800538D394C2U); static_assert(xxh3_compute<64>("abc"sv) == 0x78AF5F94892F3950U); -static_assert(xxh3_compute<128>("abc"sv) == xxh3_hash128{.low = 0x78AF5F94892F3950U, .high = 0x06B05AB6733A6185U}); +static_assert(xxh3_compute<128>("abc"sv) == hash128{.low = 0x78AF5F94892F3950U, .high = 0x06B05AB6733A6185U}); static_assert(xxh3_finalize(xxh3_state<128>{}) == xxh3_128_vectors[0].prefixes[0]); // Every length class up to the first medium one. static_assert(prefix_mismatches<64>(20) == 0); @@ -106,9 +106,9 @@ static_assert(chunked<128>(std::span(message).first(prefix_limit), 7, xxh3_128_v static_assert(chunked<64>(std::span(message).first(block_sizes[2]), 100, xxh3_64_vectors[1].seed) == xxh3_64_vectors[1].blocks[2]); static_assert(edge_seed_mismatches<64>(513) == 0); static_assert(edge_seed_mismatches<128>(513) == 0); -static_assert(xxh3_detail::multiply_portable(~std::uint64_t{0}, ~std::uint64_t{0}) == xxh3_hash128{.low = 1, .high = ~std::uint64_t{1}}); +static_assert(xxh3_detail::multiply_portable(~std::uint64_t{0}, ~std::uint64_t{0}) == hash128{.low = 1, .high = ~std::uint64_t{1}}); static_assert(xxh3_detail::multiply_portable(0x9E3779B185EBCA87U, 0xC2B2AE3D27D4EB4FU) == - xxh3_hash128{.low = 0xDEF35B010F796CA9U, .high = 0x7854787AA57880A8U}); + hash128{.low = 0xDEF35B010F796CA9U, .high = 0x7854787AA57880A8U}); static_assert(xxh3_64_compute("abc"sv) == 0x78AF5F94892F3950U); static_assert(xxh3_128_compute(std::span(message).first(241), xxh3_128_vectors[1].seed) == xxh3_128_vectors[1].prefixes[241]); static_assert(std::same_as> && std::same_as>); From 3e81fbc128119b8a5039abac7ae7db8953854391 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:28:43 +0200 Subject: [PATCH 35/64] refactor(murmur3)!: MurmurHash3_x64_128 returns hash128 low is h1 and high is h2, so the value is the 128-bit number the reference writes out little-endian; hashes are unchanged. Generated code is identical on x86-64 and Cortex-M4. --- doc/murmur3.md | 14 +++++++------- doc/xxhash.md | 2 +- examples/murmur3/deduplicate.cpp | 14 +++++++++----- src/include/checksum/murmur3.hpp | 7 ++++--- .../include/murmur3_reference_vectors.hpp | 6 +++--- tests/unit_tests/ut_murmur3.cpp | 7 +++---- 6 files changed, 27 insertions(+), 23 deletions(-) diff --git a/doc/murmur3.md b/doc/murmur3.md index 223d178..721a9a3 100644 --- a/doc/murmur3.md +++ b/doc/murmur3.md @@ -16,13 +16,13 @@ using namespace std::literals; // One call, seed 0 or another seed. std::string_view key = "user:42"; std::uint32_t hash = checksum::murmur3_32_compute(key); -std::array wide = checksum::murmur3_128_compute(key, 1234); +checksum::hash128 wide = checksum::murmur3_128_compute(key, 1234); // Incremental: a message may be split anywhere. checksum::murmur3_128_state state{.seed = 1234}; state = checksum::murmur3_update(state, first_part); state = checksum::murmur3_update(state, second_part); -std::array value = checksum::murmur3_finalize(state); +checksum::hash128 value = checksum::murmur3_finalize(state); // Compile time. static_assert(checksum::murmur3_32_compute("Hello, world!"sv, 1234) == 0xFAF6CDB3); @@ -44,9 +44,9 @@ deduplication of records by their 128-bit hash. | `murmur3_32_state`, `murmur3_128_state` | `murmur3_state<32>` and `murmur3_state<128>`. | | `murmur3_32_compute(data, seed = 0)`, `murmur3_128_compute(data, seed = 0)` | `murmur3_compute<32>(data, seed)` and `murmur3_compute<128>(data, seed)`. | -`murmur3_state::value_type` is the hash: `std::uint32_t` for Width 32, and for Width 128 a -`std::array` holding the two halves h1 and h2 in the order the reference implementation stores -them. All functions are `constexpr` and `noexcept`. `data` is a `std::span` or any range of +`murmur3_state::value_type` is the hash: `std::uint32_t` for Width 32, and `hash128` for Width 128, the same +type as XXH3-128 returns. Its `low` half is h1 and its `high` half h2, so it is the 128-bit number the reference +implementation writes out least significant byte first. All functions are `constexpr` and `noexcept`. `data` is a `std::span` or any range of `std::byte`, `char`, `unsigned char`, `signed char` or `char8_t`, as for the other algorithms. At run time `murmur3_compute` hashes contiguous ranges directly, without the state's buffer; other ranges are folded in 64-byte chunks. Arrays of `char` are rejected, so the `'\0'` of a string literal is never hashed: pass text as @@ -61,8 +61,8 @@ the unused bytes of the buffer are ignored. - **Seed:** different seeds give unrelated hashes; the empty message with seed 0 hashes to 0 (and to {0, 0} for Width 128). - **Byte order:** blocks are read little-endian on every target, so a big-endian target gives the same hashes. The - result is a number or a pair of numbers; serializing the 128-bit hash as the reference does means writing h1, then - h2, each least significant byte first. + result is a number; serializing the 128-bit hash as the reference does means writing `low`, then `high`, each least + significant byte first. - **Long messages:** MurmurHash3_x86_32 mixes in the length modulo 2^32, MurmurHash3_x64_128 the 64-bit length. The reference implementation takes the length as an `int`, so it cannot hash messages of 2 GiB or more. diff --git a/doc/xxhash.md b/doc/xxhash.md index 843d5cb..41b1df6 100644 --- a/doc/xxhash.md +++ b/doc/xxhash.md @@ -78,7 +78,7 @@ a cache keyed by the hash of its input. | `xxh3_update(state, data)` | Folds `data` into `state` and returns the new state. | | `xxh3_finalize(state)` | The hash of the message folded into `state`; the state is unchanged. | | `xxh3_compute(data, seed = 0)` | `xxh3_finalize(xxh3_update(xxh3_state{.seed = seed}, data))`. | -| `hash128` | The XXH3-128 hash: `low` and `high`, its lower and upper 64 bits, as `XXH128_hash_t` of the reference. Compares with `==`. | +| `hash128` | The XXH3-128 hash: `low` and `high`, its lower and upper 64 bits, as `XXH128_hash_t` of the reference. Compares with `==`. MurmurHash3_x64_128 returns the same type. | | `xxh3_64_state`, `xxh3_128_state` | `xxh3_state<64>` and `xxh3_state<128>`. | | `xxh3_64_compute(data, seed = 0)`, `xxh3_128_compute(data, seed = 0)` | `xxh3_compute<64>` and `xxh3_compute<128>`. `xxh3_update` and `xxh3_finalize` take the width from the state. | diff --git a/examples/murmur3/deduplicate.cpp b/examples/murmur3/deduplicate.cpp index b965dca..441ef23 100644 --- a/examples/murmur3/deduplicate.cpp +++ b/examples/murmur3/deduplicate.cpp @@ -4,10 +4,9 @@ #include #include -#include #include -#include #include +#include using namespace std::literals; @@ -19,7 +18,7 @@ struct record { }; // The fields are folded one after another; a separator keeps {"ab", "c"} and {"a", "bc"} apart. -std::array record_hash(record const &value) { +checksum::hash128 record_hash(record const &value) { checksum::murmur3_128_state state{.seed = 0x5EED}; state = checksum::murmur3_update(state, value.name); state = checksum::murmur3_update(state, "\037"sv); @@ -27,6 +26,11 @@ std::array record_hash(record const &value) { return checksum::murmur3_finalize(state); } +// The hash is uniformly distributed, so its lower half is a good bucket index. +struct hash128_hasher { + std::size_t operator()(checksum::hash128 const &hash) const noexcept { return static_cast(hash.low); } +}; + } // namespace int main() { @@ -34,13 +38,13 @@ int main() { record{"sensor-1", "21.5 C"}, record{"sensor-2", "19.0 C"}, record{"sensor-1", "21.5 C"}, record{"sensor-1", "21.6 C"}, record{"sensor-2", "19.0 C"}, }; - std::set> seen; + std::unordered_set seen; std::size_t duplicates = 0; for(record const &value : records) { auto const hash = record_hash(value); bool const is_new = seen.insert(hash).second; duplicates += is_new ? 0 : 1; - std::println("{:016x}{:016x} {} {}{}", hash[0], hash[1], value.name, value.payload, is_new ? "" : " (duplicate)"); + std::println("{:016x}{:016x} {} {}{}", hash.high, hash.low, value.name, value.payload, is_new ? "" : " (duplicate)"); } std::println("{} unique, {} duplicates", seen.size(), duplicates); // The streamed hash equals the hash of the whole record in one call. diff --git a/src/include/checksum/murmur3.hpp b/src/include/checksum/murmur3.hpp index 9a3175d..4abd877 100644 --- a/src/include/checksum/murmur3.hpp +++ b/src/include/checksum/murmur3.hpp @@ -2,6 +2,7 @@ #define CHECKSUM_MURMUR3_HPP #include +#include #include #include @@ -29,8 +30,8 @@ namespace checksum { template requires(Width == 32 || Width == 128) struct murmur3_state { - /// The hash: std::uint32_t, or the two 64-bit halves h1 and h2 in the order the reference implementation stores them. - using value_type = std::conditional_t>; + /// The hash: std::uint32_t, or hash128 with low = h1 and high = h2, the 128-bit number the reference implementation stores little-endian. + using value_type = std::conditional_t; /// Hash lanes: h1, and h2 for Width 128. Set from the seed when the first block is folded. std::array, Width == 32 ? 1 : 2> lanes{}; @@ -238,7 +239,7 @@ constexpr murmur3_state::value_type finish(lane_array lanes, std:: high = avalanche(high); low += high; high += low; - return {low, high}; + return {.low = low, .high = high}; } } diff --git a/tests/unit_tests/include/murmur3_reference_vectors.hpp b/tests/unit_tests/include/murmur3_reference_vectors.hpp index 818dd14..b8d57fb 100644 --- a/tests/unit_tests/include/murmur3_reference_vectors.hpp +++ b/tests/unit_tests/include/murmur3_reference_vectors.hpp @@ -4,6 +4,8 @@ // MurmurHash3_x86_32 and MurmurHash3_x64_128 of every prefix of a 300-byte message and of a long_message_size-byte one, both from // fill_random(), for three seeds each. Computed with the reference implementation, src/MurmurHash3.cpp of github.com/aappleby/smhasher. +#include + #include #include #include @@ -21,8 +23,6 @@ template struct vector_set { Value long_message; }; -using hash128 = std::array; - inline constexpr std::array, 3> murmur3_32_vectors{{ {.seed = 0x00000000, .prefixes{ @@ -122,7 +122,7 @@ inline constexpr std::array, 3> murmur3_32_vectors{{ .long_message = 0x7D7507E9}, }}; -inline constexpr std::array, 3> murmur3_128_vectors{{ +inline constexpr std::array, 3> murmur3_128_vectors{{ {.seed = 0x00000000, .prefixes{{ {0x0000000000000000, 0x0000000000000000}, {0x423F7F073F326663, 0x3052809291243D6D}, {0x1AF1B4A8CA015AE9, 0x23568FC2EC89F92A}, diff --git a/tests/unit_tests/ut_murmur3.cpp b/tests/unit_tests/ut_murmur3.cpp index 588b62f..c90ff9d 100644 --- a/tests/unit_tests/ut_murmur3.cpp +++ b/tests/unit_tests/ut_murmur3.cpp @@ -21,7 +21,6 @@ namespace { using namespace checksum; -using murmur3_test::hash128; using murmur3_test::murmur3_128_vectors; using murmur3_test::murmur3_32_vectors; @@ -64,8 +63,8 @@ using namespace std::literals; static_assert(murmur3_compute<32>(""sv) == 0); static_assert(murmur3_compute<32>(""sv, 1) == 0x514E28B7U); static_assert(murmur3_compute<32>("Hello, world!"sv, 1234) == 0xFAF6CDB3U); -static_assert(murmur3_compute<128>(""sv) == hash128{0, 0}); -static_assert(murmur3_compute<128>("Hello, world!"sv, 1234) == hash128{0x61130E64AA0AC6FEU, 0x51F9046D087E1B56U}); +static_assert(murmur3_compute<128>(""sv) == hash128{}); +static_assert(murmur3_compute<128>("Hello, world!"sv, 1234) == hash128{.low = 0x61130E64AA0AC6FEU, .high = 0x51F9046D087E1B56U}); static_assert(murmur3_finalize(murmur3_state<32>{.seed = 1}) == 0x514E28B7U); static_assert(murmur3_compute<32>(std::span(message), murmur3_32_vectors[2].seed) == murmur3_32_vectors[2].prefixes[300]); static_assert(murmur3_compute<128>(std::span(message).first(33), murmur3_128_vectors[2].seed) == murmur3_128_vectors[2].prefixes[33]); @@ -75,7 +74,7 @@ static_assert(chunked<32>(message, 3, murmur3_32_vectors[1].seed) == murmur3_32_ static_assert(prefix_mismatches<32>(70) == 0); static_assert(prefix_mismatches<128>(70) == 0); static_assert(murmur3_32_compute("Hello, world!"sv, 1234) == 0xFAF6CDB3U); -static_assert(murmur3_128_compute("Hello, world!"sv, 1234) == hash128{0x61130E64AA0AC6FEU, 0x51F9046D087E1B56U}); +static_assert(murmur3_128_compute("Hello, world!"sv, 1234) == hash128{.low = 0x61130E64AA0AC6FEU, .high = 0x51F9046D087E1B56U}); static_assert(std::same_as> && std::same_as>); template class murmur3 : public testing::Test {}; From b92aac325345330c236dda0d17b1e5d15d05ce19 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:24:45 +0200 Subject: [PATCH 36/64] feat(adler32, internet, fletcher): continue from a stored checksum adler32_update, internet_update and fletcher_update take the checksum in place of a state and return the new checksum. The checksum must have exactly its type (std::uint32_t, std::uint16_t, or the Fletcher width's type), so {} still means the empty state and no other integer picks a width. An Internet checksum continues only after an even number of bytes, a Fletcher-32/64 checksum only after whole blocks. --- src/include/checksum/adler32.hpp | 28 +++++++++++++++++--- src/include/checksum/fletcher.hpp | 31 ++++++++++++++++++++++ src/include/checksum/internet.hpp | 17 ++++++++++++ tests/unit_tests/ut_adler32.cpp | 36 ++++++++++++++++++++++++++ tests/unit_tests/ut_fletcher.cpp | 43 +++++++++++++++++++++++++++++++ tests/unit_tests/ut_internet.cpp | 42 ++++++++++++++++++++++++++++++ 6 files changed, 193 insertions(+), 4 deletions(-) diff --git a/src/include/checksum/adler32.hpp b/src/include/checksum/adler32.hpp index dcc2e3b..75a8c21 100644 --- a/src/include/checksum/adler32.hpp +++ b/src/include/checksum/adler32.hpp @@ -3,6 +3,7 @@ #include +#include #include #include #include @@ -35,13 +36,22 @@ struct adler32_state { /// Folds a byte range into state. Contiguous ranges are passed on as one span, others in 64-byte chunks. template [[nodiscard]] constexpr adler32_state adler32_update(adler32_state state, Range &&data) noexcept; +/// Folds data into the message whose checksum is checksum and returns the new checksum, like zlib's adler32(adler, buf, len). +/// The checksum must be a std::uint32_t, so that {} still means the empty adler32_state. +template Checksum> +[[nodiscard]] constexpr std::uint32_t adler32_update(Checksum checksum, std::span data) noexcept; + +/// Folds a byte range into the message whose checksum is checksum and returns the new checksum. +template Checksum, byte_range Range> +[[nodiscard]] constexpr std::uint32_t adler32_update(Checksum checksum, Range &&data) noexcept; + /// The checksum of state. [[nodiscard]] constexpr std::uint32_t adler32_finalize(adler32_state state) noexcept; -/// adler32_finalize(adler32_update({}, data)). +/// adler32_finalize(adler32_update(adler32_state{}, data)). [[nodiscard]] constexpr std::uint32_t adler32_compute(std::span data) noexcept; -/// adler32_finalize(adler32_update({}, data)) for a byte range. +/// adler32_finalize(adler32_update(adler32_state{}, data)) for a byte range. template [[nodiscard]] constexpr std::uint32_t adler32_compute(Range &&data) noexcept; } // namespace checksum @@ -101,10 +111,20 @@ constexpr std::uint32_t adler32_finalize(adler32_state state) noexcept { return (adler32_detail::reduce_once(state.sum2) << 16U) | adler32_detail::reduce_once(state.sum1); } -constexpr std::uint32_t adler32_compute(std::span data) noexcept { return adler32_finalize(adler32_update({}, data)); } +template Checksum> constexpr std::uint32_t adler32_update(Checksum checksum, std::span data) noexcept { + adler32_state const state{.sum1 = static_cast(checksum), .sum2 = static_cast(checksum >> 16U)}; + return adler32_finalize(adler32_update(state, data)); +} + +template Checksum, byte_range Range> constexpr std::uint32_t adler32_update(Checksum checksum, Range &&data) noexcept { + adler32_state const state{.sum1 = static_cast(checksum), .sum2 = static_cast(checksum >> 16U)}; + return adler32_finalize(adler32_update(state, std::forward(data))); +} + +constexpr std::uint32_t adler32_compute(std::span data) noexcept { return adler32_finalize(adler32_update(adler32_state{}, data)); } template constexpr std::uint32_t adler32_compute(Range &&data) noexcept { - return adler32_finalize(adler32_update({}, std::forward(data))); + return adler32_finalize(adler32_update(adler32_state{}, std::forward(data))); } } // namespace checksum diff --git a/src/include/checksum/fletcher.hpp b/src/include/checksum/fletcher.hpp index c097570..1fc1646 100644 --- a/src/include/checksum/fletcher.hpp +++ b/src/include/checksum/fletcher.hpp @@ -3,8 +3,10 @@ #include +#include #include #include +#include #include #include #include @@ -47,6 +49,17 @@ template template [[nodiscard]] constexpr fletcher_state fletcher_update(fletcher_state state, Range &&data) noexcept; +/// Folds data into the message whose checksum is checksum and returns the new checksum; the type of checksum selects Fletcher-16, -32 +/// or -64. That message must end on a whole block, since a checksum does not record an unfinished block. +template + requires(std::same_as || std::same_as || std::same_as) +[[nodiscard]] constexpr Checksum fletcher_update(Checksum checksum, std::span data) noexcept; + +/// Folds a byte range into the message whose checksum is checksum and returns the new checksum; that message ends on a whole block. +template + requires(std::same_as || std::same_as || std::same_as) +[[nodiscard]] constexpr Checksum fletcher_update(Checksum checksum, Range &&data) noexcept; + /// The checksum of state, an unfinished block padded with zero bytes. template [[nodiscard]] constexpr fletcher_state::value_type fletcher_finalize(fletcher_state state) noexcept; @@ -153,6 +166,24 @@ template constexpr fletcher_state::value_type fletcher_f return static_cast((sum2 << (Width / 2)) | sum1); } +template + requires(std::same_as || std::same_as || std::same_as) +constexpr Checksum fletcher_update(Checksum checksum, std::span data) noexcept { + using state_type = fletcher_state::digits>; + using sum_type = state_type::sum_type; + state_type const state{.sum1 = static_cast(checksum), .sum2 = static_cast(checksum >> (sizeof(sum_type) * 8))}; + return fletcher_finalize(fletcher_update(state, data)); +} + +template + requires(std::same_as || std::same_as || std::same_as) +constexpr Checksum fletcher_update(Checksum checksum, Range &&data) noexcept { + using state_type = fletcher_state::digits>; + using sum_type = state_type::sum_type; + state_type const state{.sum1 = static_cast(checksum), .sum2 = static_cast(checksum >> (sizeof(sum_type) * 8))}; + return fletcher_finalize(fletcher_update(state, std::forward(data))); +} + template constexpr fletcher_state::value_type fletcher_compute(std::span data) noexcept { return fletcher_finalize(fletcher_update(fletcher_state{}, data)); } diff --git a/src/include/checksum/internet.hpp b/src/include/checksum/internet.hpp index 55a194e..7417452 100644 --- a/src/include/checksum/internet.hpp +++ b/src/include/checksum/internet.hpp @@ -36,6 +36,15 @@ struct internet_state { /// Folds a byte range into state. Contiguous ranges are passed on as one span, others in 64-byte chunks. template [[nodiscard]] constexpr internet_state internet_update(internet_state state, Range &&data) noexcept; +/// Folds data into the message whose checksum is checksum and returns the new checksum. That message must have an even number of +/// bytes, since a checksum does not record an odd last byte. +template Checksum> +[[nodiscard]] constexpr std::uint16_t internet_update(Checksum checksum, std::span data) noexcept; + +/// Folds a byte range into the message whose checksum is checksum and returns the new checksum; that message has an even length. +template Checksum, byte_range Range> +[[nodiscard]] constexpr std::uint16_t internet_update(Checksum checksum, Range &&data) noexcept; + /// The checksum of state: the one's complement of the sum, a last odd byte padded with zero. Store it most significant byte first. [[nodiscard]] constexpr std::uint16_t internet_finalize(internet_state state) noexcept; @@ -111,6 +120,14 @@ template constexpr internet_state internet_update(internet_st constexpr std::uint16_t internet_finalize(internet_state state) noexcept { return static_cast(~state.sum); } +template Checksum> constexpr std::uint16_t internet_update(Checksum checksum, std::span data) noexcept { + return internet_finalize(internet_update(internet_state{.sum = static_cast(~checksum)}, data)); +} + +template Checksum, byte_range Range> constexpr std::uint16_t internet_update(Checksum checksum, Range &&data) noexcept { + return internet_finalize(internet_update(internet_state{.sum = static_cast(~checksum)}, std::forward(data))); +} + constexpr std::uint16_t internet_compute(std::span data) noexcept { return internet_finalize(internet_update(internet_state{}, data)); } diff --git a/tests/unit_tests/ut_adler32.cpp b/tests/unit_tests/ut_adler32.cpp index 4cc8f73..5dfefeb 100644 --- a/tests/unit_tests/ut_adler32.cpp +++ b/tests/unit_tests/ut_adler32.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -188,4 +189,39 @@ TEST(adler32, edge_states) { } } +template +concept resumable = requires(Checksum checksum, std::span data) { adler32_update(checksum, data); }; + +// Only a std::uint32_t is a checksum; {} stays the empty state. +static_assert(resumable && !resumable && !resumable && !resumable); +static_assert(std::same_as{})), adler32_state>); +static_assert(adler32_update(adler32_compute("12345"sv), "6789"sv) == 0x091E01DE); + +// A stored checksum continues the message after any number of bytes, at compile time and at run time. +TEST(adler32, resume_from_checksum) { + constexpr std::size_t constant_size = 64; + static constexpr auto resumed = [] { + auto const message = std::span(constant_message).first(constant_size); + std::array result{}; + for(std::size_t first = 0; first <= constant_size; ++first) { + result[first] = adler32_update(adler32_compute(message.first(first)), message.subspan(first)); + } + return result; + }(); + for(std::uint32_t const value : resumed) { + ASSERT_EQ(value, adler32_compute(std::span(constant_message).first(constant_size))); + } + + auto const data = random_bytes(1100, 8); + auto const message = std::span(data); + auto const whole = reference(message); + for(std::size_t first = 0; first <= data.size(); ++first) { + ASSERT_EQ(adler32_update(adler32_compute(message.first(first)), message.subspan(first)), whole) << "split at " << first; + } + std::list const tail(data.begin() + 100, data.end()); + EXPECT_EQ(adler32_update(adler32_compute(message.first(100)), tail), whole); + // Sums from 65521 count modulo 65521, as in the state. + EXPECT_EQ(adler32_update(std::uint32_t{0xFFFFFFFF}, message), reference(message, 0xFFFF, 0xFFFF)); +} + } // namespace diff --git a/tests/unit_tests/ut_fletcher.cpp b/tests/unit_tests/ut_fletcher.cpp index 2696ad3..63fca86 100644 --- a/tests/unit_tests/ut_fletcher.cpp +++ b/tests/unit_tests/ut_fletcher.cpp @@ -208,6 +208,49 @@ TYPED_TEST(fletcher, constant_evaluation_matches_run_time) { } } +template +concept resumable = requires(Checksum checksum, std::span data) { fletcher_update(checksum, data); }; + +// The checksum type selects the width; other integers are rejected rather than converted. +static_assert(resumable && resumable && resumable); +static_assert(!resumable && !resumable && !resumable); +static_assert(std::same_as && + std::same_as && + std::same_as); +static_assert(fletcher_update(fletcher32_compute("abcd"sv), "e"sv) == 0xF04FC729); + +// A stored checksum continues the message after any number of whole blocks, at compile time and at run time. After an unfinished +// block it does not: the checksum already counts the block as padded. +TYPED_TEST(fletcher, resume_from_checksum) { + constexpr unsigned width = TypeParam::value; + using value_type = fletcher_state::value_type; + constexpr std::size_t block_size = width / 16; + constexpr std::size_t constant_size = 64; + static constexpr auto resumed = [] { + auto const message = std::span(constant_message).first(constant_size); + std::array result{}; + for(std::size_t block = 0; block < result.size(); ++block) { + result[block] = fletcher_update(fletcher_compute(message.first(block * block_size)), message.subspan(block * block_size)); + } + return result; + }(); + for(value_type const value : resumed) { + ASSERT_EQ(value, fletcher_compute(std::span(constant_message).first(constant_size))); + } + + auto const data = random_bytes(1100, 8); + auto const message = std::span(data); + auto const whole = fletcher_compute(message); + for(std::size_t first = 0; first <= data.size(); first += block_size) { + ASSERT_EQ(fletcher_update(fletcher_compute(message.first(first)), message.subspan(first)), whole) << "split at " << first; + } + std::list const tail(data.begin() + 100, data.end()); + EXPECT_EQ(fletcher_update(fletcher_compute(message.first(100)), tail), whole); + if constexpr(block_size > 1) { + EXPECT_NE(fletcher_update(fletcher_compute(message.first(1)), message.subspan(1)), whole); + } +} + TYPED_TEST(fletcher, byte_ranges) { constexpr unsigned width = TypeParam::value; constexpr std::string_view text = "123456789"; diff --git a/tests/unit_tests/ut_internet.cpp b/tests/unit_tests/ut_internet.cpp index 1f5daa9..000ecd8 100644 --- a/tests/unit_tests/ut_internet.cpp +++ b/tests/unit_tests/ut_internet.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -169,6 +170,47 @@ TEST(internet, constant_evaluation_matches_run_time) { EXPECT_EQ(split, internet_compute(message)); } +template +concept resumable = requires(Checksum checksum, std::span data) { internet_update(checksum, data); }; + +// Only a std::uint16_t is a checksum; {} stays the empty state. +static_assert(resumable && !resumable && !resumable && !resumable); +static_assert(std::same_as); +static_assert(internet_update(internet_compute(std::span(rfc1071_example).first(4)), std::span(rfc1071_example).subspan(4)) == 0x220D); + +// A stored checksum continues the message after any even number of bytes, at compile time and at run time. After an odd number it +// does not: the checksum does not record that the next byte is the low byte of a word. +TEST(internet, resume_from_checksum) { + constexpr std::size_t constant_size = 64; + static constexpr auto resumed = [] { + auto const message = std::span(constant_message).first(constant_size); + std::array result{}; + for(std::size_t word = 0; word < result.size(); ++word) { + result[word] = internet_update(internet_compute(message.first(2 * word)), message.subspan(2 * word)); + } + return result; + }(); + for(std::uint16_t const value : resumed) { + ASSERT_EQ(value, internet_compute(std::span(constant_message).first(constant_size))); + } + + auto const data = random_bytes(1101, 8); + auto const message = std::span(data); + std::uint16_t const whole = reference(message); + for(std::size_t first = 0; first <= data.size(); first += 2) { + ASSERT_EQ(internet_update(internet_compute(message.first(first)), message.subspan(first)), whole) << "split at " << first; + } + std::list const tail(data.begin() + 100, data.end()); + EXPECT_EQ(internet_update(internet_compute(message.first(100)), tail), whole); + EXPECT_NE(internet_update(internet_compute(message.first(1)), message.subspan(1)), whole); + + // Both zeros of one's complement: 0xFFFF after only zero bytes, 0 after a message that sums to 0xFFFF. + std::array const zeros{}; + EXPECT_EQ(internet_update(internet_compute(zeros), message), whole); + EXPECT_EQ(internet_update(std::uint16_t{0}, zeros), 0); + EXPECT_EQ(internet_update(std::uint16_t{0xFFFF}, zeros), 0xFFFF); +} + TEST(internet, byte_ranges) { constexpr std::string_view text = "123456789"; std::uint16_t const expected = internet_compute(std::as_bytes(std::span(text))); From 5754684c6cc3320b864ef9df24dd561aca2675e6 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:25:57 +0200 Subject: [PATCH 37/64] docs(adler32, internet, fletcher): continuing from a stored checksum --- doc/adler32.md | 11 +++++++++-- doc/fletcher.md | 13 +++++++++++-- doc/internet.md | 11 +++++++++-- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/doc/adler32.md b/doc/adler32.md index 17d520d..b27b507 100644 --- a/doc/adler32.md +++ b/doc/adler32.md @@ -21,6 +21,9 @@ state = checksum::adler32_update(state, first_part); state = checksum::adler32_update(state, second_part); std::uint32_t stream_checksum = checksum::adler32_finalize(state); +// Continue from a stored checksum. +std::uint32_t extended = checksum::adler32_update(stream_checksum, third_part); + // Compile time. static_assert(checksum::adler32_compute("123456789"sv) == 0x091E01DE); static_assert(checksum::adler32_compute("Wikipedia"sv) == 0x11E60398); @@ -41,6 +44,7 @@ starts at 0 and adds `sum1` after each byte. The checksum is `(sum2 << 16) | sum | --- | --- | | `adler32_state` | The two sums, `sum1` and `sum2`. A plain value: copy it, compare it, store it. The default (`sum1 = 1`, `sum2 = 0`) is the empty message. | | `adler32_update(state, data)` | Folds `data` into `state` and returns the new state. | +| `adler32_update(checksum, data)` | Folds `data` into the message whose checksum is `checksum`, a `std::uint32_t`, and returns the new checksum. | | `adler32_finalize(state)` | The checksum. | | `adler32_compute(data)` | `adler32_finalize(adler32_update({}, data))`. | @@ -55,10 +59,13 @@ Every state value is valid, so nothing has preconditions: sums from 65521 up cou - **Splits:** a message may be split anywhere; the result is the same as for one call. - **Empty message:** gives 1. -- **Resuming from a checksum:** `adler32_state{.sum1 = value & 0xFFFF, .sum2 = value >> 16}` continues a message whose - checksum is `value`, for example one computed by zlib. - **Byte order:** the result is a number; zlib stores it most significant byte first. +**Continuing from a stored checksum.** The checksum holds both sums, so `adler32_update(value, data)` continues a +message whose checksum is `value`, for example one computed by zlib, after any number of bytes, and returns the new +checksum, as zlib's `adler32(adler, buf, len)` does. `value` must be a `std::uint32_t`: another integer type does not +compile, so that `adler32_update({}, data)` still starts from the empty state, not from checksum 0. + ## 5. CPU acceleration The portable loop adds bytes into `std::size_t` sums and reduces them only when an overflow could otherwise happen: diff --git a/doc/fletcher.md b/doc/fletcher.md index b18f06f..51fcc83 100644 --- a/doc/fletcher.md +++ b/doc/fletcher.md @@ -47,13 +47,14 @@ A last incomplete block is padded with zero bytes. The values match the examples ## 3. API -`Width` is 16, 32 or 64. `fletcher_update` and `fletcher_finalize` take the width from the state, so only the state -and `fletcher_compute` have aliases per width. +`Width` is 16, 32 or 64. `fletcher_update` and `fletcher_finalize` take the width from the state or the checksum +type, so only the state and `fletcher_compute` have aliases per width. | Name | What it does | | --- | --- | | `fletcher_state` | `sum1`, `sum2` and `block_offset`, the bytes of an unfinished block already in `sum1`. A plain value: copy it, compare it, store it. The default is the empty message. | | `fletcher_update(state, data)` | Folds `data` into `state` and returns the new state. | +| `fletcher_update(checksum, data)` | Folds `data` into the message whose checksum is `checksum` and returns the new checksum; `std::uint16_t`, `std::uint32_t` or `std::uint64_t` selects the width. That message must end on a whole block. | | `fletcher_finalize(state)` | The checksum, an unfinished block padded with zero bytes. | | `fletcher_compute(data)` | `fletcher_finalize(fletcher_update(fletcher_state{}, data))`. | | `fletcher16_state`, `fletcher32_state`, `fletcher64_state` | `fletcher_state<16>`, `fletcher_state<32>`, `fletcher_state<64>`. | @@ -77,6 +78,14 @@ modulo the block size. - **Byte order:** words are read little-endian on every target, and the result is a number; the protocol decides how it goes into a frame. +**Continuing from a stored checksum.** `fletcher_update(value, data)` continues a message whose checksum is `value` +and returns the new checksum. The type of `value` selects the width: `std::uint16_t` for Fletcher-16, `std::uint32_t` +for Fletcher-32, `std::uint64_t` for Fletcher-64. Other integer types, `int` and `unsigned char` included, do not +compile rather than pick a width, so write `std::uint32_t{0xF04FC729}` for a literal; `{}` does not compile either, +name the state type (`fletcher32_state{}`). Fletcher-32 and Fletcher-64 continue correctly only after whole blocks, +an even length or a multiple of 4: the checksum already counts an unfinished block as padded with zeros, so after such +a length keep the state instead. Fletcher-16 continues after any length. + ## 5. CPU acceleration The portable loop adds blocks into the widest native integer and reduces modulo M only when an overflow could diff --git a/doc/internet.md b/doc/internet.md index 45e9147..2099a22 100644 --- a/doc/internet.md +++ b/doc/internet.md @@ -43,6 +43,7 @@ complement arithmetic, each carry out of bit 15 added back into bit 0, and the c | --- | --- | | `internet_state` | The running sum (`sum`) and whether an odd number of bytes was folded (`odd`). A plain value: copy it, compare it, store it. The default is the empty message. | | `internet_update(state, data)` | Folds `data` into `state` and returns the new state. | +| `internet_update(checksum, data)` | Folds `data` into the message whose checksum is `checksum`, a `std::uint16_t`, and returns the new checksum. That message must have an even length. | | `internet_finalize(state)` | The checksum: `~state.sum`. | | `internet_compute(data)` | `internet_finalize(internet_update({}, data))`. | @@ -65,6 +66,12 @@ Every `internet_state` value is valid, so nothing has preconditions. - **Byte order:** the result is a number; write it into the packet most significant byte first. The library reads the message the same way on little- and big-endian targets. +**Continuing from a stored checksum.** `internet_update(value, data)` continues a message whose checksum is `value` +and returns the new checksum; the running sum is `~value`. It is correct only if that message has an even number of +bytes: the checksum does not record an odd last byte, which `internet_state` keeps in `odd`, so after an odd length +keep the state instead. `value` must be a `std::uint16_t`: another integer type does not compile, so that +`internet_update({}, data)` still starts from the empty state. + ## 5. CPU acceleration The portable loop adds the widest native word (`std::size_t`) with two independent carry chains. It runs at every @@ -161,8 +168,8 @@ RISC-V has not been measured on hardware; the vector kernel is tested in QEMU wi ## 7. Limitations - **No in-place update helper:** RFC 1624 updates a checksum after one 16-bit-aligned field changes. The public API - already does it: start from `internet_state{.sum = static_cast(~old_checksum)}`, fold the bitwise - complement of the old field, then the new field, and finalize, as `examples/internet/ttl_decrement.cpp` does. + already does it: continue from the old checksum with the bitwise complement of the old field, then with the new + field, as `examples/internet/ttl_decrement.cpp` does. - **UDP zero:** the UDP rule of sending 0xFFFF instead of a computed 0 is protocol logic and stays in the caller. - **No verification helper:** to verify a packet, compute over it, checksum included, and compare the result with 0. - **Code size:** a build with a kernel adds 290-810 bytes; `CHECKSUM_ACCELERATION=OFF` keeps the portable loop alone. From 661779a12eee4933c3e8f448152ea28f2b97f905 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:30:46 +0200 Subject: [PATCH 38/64] examples(adler32, internet): continue from the stored checksum --- examples/adler32/resume.cpp | 8 +++----- examples/internet/ttl_decrement.cpp | 8 +++----- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/examples/adler32/resume.cpp b/examples/adler32/resume.cpp index 957205d..3df67f9 100644 --- a/examples/adler32/resume.cpp +++ b/examples/adler32/resume.cpp @@ -12,12 +12,10 @@ int main() { // The checksum of the first part, e.g. kept next to a log file. std::uint32_t const stored = checksum::adler32_compute("12345"sv); - // Later, more data is appended: resume from the stored value. - checksum::adler32_state state{.sum1 = static_cast(stored & 0xFFFFU), .sum2 = static_cast(stored >> 16U)}; - state = checksum::adler32_update(state, "6789"sv); - std::uint32_t const extended = checksum::adler32_finalize(state); + // Later, more data is appended: continue from the stored checksum. + std::uint32_t const extended = checksum::adler32_update(stored, "6789"sv); std::uint32_t const whole = checksum::adler32_compute("123456789"sv); - std::println("resumed 0x{:08X}, whole 0x{:08X}", extended, whole); + std::println("extended 0x{:08X}, whole 0x{:08X}", extended, whole); return extended == whole && whole == 0x091E01DE ? 0 : 1; } diff --git a/examples/internet/ttl_decrement.cpp b/examples/internet/ttl_decrement.cpp index 8cc28ff..91b8aa9 100644 --- a/examples/internet/ttl_decrement.cpp +++ b/examples/internet/ttl_decrement.cpp @@ -1,5 +1,5 @@ // A router decrements the TTL of an IPv4 header and updates its checksum without summing the header again (RFC 1624). -// The update starts from the complemented old checksum, folds the complemented old field, then the new field. +// It continues from the old checksum with the complemented old field, then with the new field. #include @@ -17,10 +17,8 @@ void decrement_ttl(std::span header) { auto const old_checksum = static_cast((std::to_integer(header[10]) << 8U) | std::to_integer(header[11])); header[8] = static_cast(std::to_integer(header[8]) - 1U); - checksum::internet_state state{.sum = static_cast(~old_checksum)}; - state = checksum::internet_update(state, old_field); - state = checksum::internet_update(state, header.subspan<8, 2>()); - std::uint16_t const value = checksum::internet_finalize(state); + std::uint16_t const without_old_field = checksum::internet_update(old_checksum, old_field); + std::uint16_t const value = checksum::internet_update(without_old_field, header.subspan<8, 2>()); header[10] = static_cast(value >> 8U); header[11] = static_cast(value & 0xFFU); } From 81fbab0a4e9eb07df25a7c221c699beb1a6c82be Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:30:51 +0200 Subject: [PATCH 39/64] examples: one structure in every directory compile_time first, then the file example, in every CMakeLists.txt; results checked before returning 0; states declared without {}; xxh3's dedup_blocks becomes deduplicate, like murmur3's. --- examples/adler32/CMakeLists.txt | 2 +- examples/fletcher/compile_time.cpp | 9 +++++-- examples/fletcher4/CMakeLists.txt | 2 +- examples/xxh3/CMakeLists.txt | 2 +- .../{dedup_blocks.cpp => deduplicate.cpp} | 0 examples/xxh3/file_hash.cpp | 2 +- examples/xxhash/cache_key.cpp | 19 +++++++------- examples/xxhash/compile_time.cpp | 26 ++++++++----------- examples/xxhash/file_hash.cpp | 2 +- 9 files changed, 32 insertions(+), 32 deletions(-) rename examples/xxh3/{dedup_blocks.cpp => deduplicate.cpp} (100%) diff --git a/examples/adler32/CMakeLists.txt b/examples/adler32/CMakeLists.txt index b692f84..70fc2e2 100644 --- a/examples/adler32/CMakeLists.txt +++ b/examples/adler32/CMakeLists.txt @@ -1,4 +1,4 @@ -foreach (example zlib_trailer resume) +foreach (example resume zlib_trailer) add_executable(checksum_example_adler32_${example} ${example}.cpp) target_link_libraries(checksum_example_adler32_${example} PRIVATE checksum::checksum) endforeach () diff --git a/examples/fletcher/compile_time.cpp b/examples/fletcher/compile_time.cpp index 4ef2b91..da66531 100644 --- a/examples/fletcher/compile_time.cpp +++ b/examples/fletcher/compile_time.cpp @@ -4,6 +4,7 @@ #include #include +#include #include using namespace std::literals; @@ -13,9 +14,13 @@ static_assert(checksum::fletcher16_compute("abcde"sv) == 0xC8F0); static_assert(checksum::fletcher32_compute("abcde"sv) == 0xF04FC729); static_assert(checksum::fletcher64_compute("abcde"sv) == 0xC8C6C527646362C6); +// A constant in read-only data: no code computes it at run time. constexpr std::uint32_t version_checksum = checksum::fletcher32_compute("firmware 1.4.2"sv); int main() { - std::println("Fletcher-32 of \"firmware 1.4.2\" = 0x{:08X}", version_checksum); - return 0; + // The same text at run time gives the same checksum. + std::string const version = "firmware 1.4.2"; + std::uint32_t const value = checksum::fletcher32_compute(version); + std::println("Fletcher-32 of \"{}\" 0x{:08X}, expected 0x{:08X}", version, value, version_checksum); + return value == version_checksum ? 0 : 1; } diff --git a/examples/fletcher4/CMakeLists.txt b/examples/fletcher4/CMakeLists.txt index 0cc7904..7233bdf 100644 --- a/examples/fletcher4/CMakeLists.txt +++ b/examples/fletcher4/CMakeLists.txt @@ -1,4 +1,4 @@ -foreach (example zfs_block file_checksum) +foreach (example file_checksum zfs_block) add_executable(checksum_example_fletcher4_${example} ${example}.cpp) target_link_libraries(checksum_example_fletcher4_${example} PRIVATE checksum::checksum) endforeach () diff --git a/examples/xxh3/CMakeLists.txt b/examples/xxh3/CMakeLists.txt index 91f9a28..7bcb0b6 100644 --- a/examples/xxh3/CMakeLists.txt +++ b/examples/xxh3/CMakeLists.txt @@ -1,4 +1,4 @@ -foreach (example file_hash dedup_blocks hash_table) +foreach (example file_hash deduplicate hash_table) add_executable(checksum_example_xxh3_${example} ${example}.cpp) target_link_libraries(checksum_example_xxh3_${example} PRIVATE checksum::checksum) endforeach () diff --git a/examples/xxh3/dedup_blocks.cpp b/examples/xxh3/deduplicate.cpp similarity index 100% rename from examples/xxh3/dedup_blocks.cpp rename to examples/xxh3/deduplicate.cpp diff --git a/examples/xxh3/file_hash.cpp b/examples/xxh3/file_hash.cpp index a6d0829..0258130 100644 --- a/examples/xxh3/file_hash.cpp +++ b/examples/xxh3/file_hash.cpp @@ -21,7 +21,7 @@ int main(int argument_count, char **arguments) { } // The state is a 336-byte value passed in and out of each update: large chunks keep that copy negligible. - checksum::xxh3_64_state state{}; + checksum::xxh3_64_state state; std::array buffer{}; while(file.read(buffer.data(), buffer.size()) || file.gcount() > 0) { state = checksum::xxh3_update(state, std::span{buffer}.first(static_cast(file.gcount()))); diff --git a/examples/xxhash/cache_key.cpp b/examples/xxhash/cache_key.cpp index 992ef34..3d77adc 100644 --- a/examples/xxhash/cache_key.cpp +++ b/examples/xxhash/cache_key.cpp @@ -19,22 +19,21 @@ std::uint64_t cache_key(std::string_view source, std::string_view options) { } // namespace -int main() { - // XXH64("abc") of the reference implementation. - if(checksum::xxh64_compute("abc"sv) != 0x44BC2CF5AD770999) { - std::println("XXH64 mismatch"); - return 1; - } +// The compiler verifies XXH64("abc") of the reference implementation. +static_assert(checksum::xxh64_compute("abc"sv) == 0x44BC2CF5AD770999); +int main() { std::unordered_map cache; + // Returns whether the step had to run. auto const build = [&](std::string_view source, std::string_view options) { std::uint64_t const key = cache_key(source, options); auto const [entry, inserted] = cache.try_emplace(key, std::string(options) + " build of " + std::string(source)); std::println("{:016x} {}: {}", key, inserted ? "built" : "cached", entry->second); + return inserted; }; - build("int main() {}", "-O2"); - build("int main() {}", "-O0"); - build("int main() {}", "-O2"); - return 0; + bool const first = build("int main() {}", "-O2"); + bool const other_options = build("int main() {}", "-O0"); + bool const repeated = build("int main() {}", "-O2"); + return first && other_options && !repeated ? 0 : 1; } diff --git a/examples/xxhash/compile_time.cpp b/examples/xxhash/compile_time.cpp index 9f16b45..8482a90 100644 --- a/examples/xxhash/compile_time.cpp +++ b/examples/xxhash/compile_time.cpp @@ -11,6 +11,8 @@ using namespace std::literals; // The compiler verifies the reference value of XXH32("abc"). static_assert(checksum::xxh32_compute("abc"sv) == 0x32D153FF); +namespace { + // The seed keeps these IDs apart from hashes of the same names elsewhere. constexpr std::uint32_t message_id(std::string_view name) { return checksum::xxh32_compute(name, 0x4D534731); } @@ -18,29 +20,23 @@ constexpr std::uint32_t temperature_id = message_id("sensor/temperature"); constexpr std::uint32_t humidity_id = message_id("sensor/humidity"); static_assert(temperature_id != humidity_id); -namespace { - -void handle(std::string_view name) { - // A run-time hash of the same text matches the constant. +// The handler of a message; a run-time hash of the same text matches the constant. +std::string_view handler(std::string_view name) { switch(message_id(name)) { case temperature_id: - std::println("{}: temperature handler", name); - break; + return "temperature handler"; case humidity_id: - std::println("{}: humidity handler", name); - break; + return "humidity handler"; default: - std::println("{}: unknown message", name); - break; + return "unknown message"; } } } // namespace int main() { - std::println("ID of sensor/temperature = 0x{:08X}", temperature_id); - handle("sensor/temperature"); - handle("sensor/humidity"); - handle("sensor/pressure"); - return 0; + for(std::string_view const name : {"sensor/temperature"sv, "sensor/humidity"sv, "sensor/pressure"sv}) { + std::println("{:18} 0x{:08X} -> {}", name, message_id(name), handler(name)); + } + return handler("sensor/humidity") == "humidity handler" && handler("sensor/pressure") == "unknown message" ? 0 : 1; } diff --git a/examples/xxhash/file_hash.cpp b/examples/xxhash/file_hash.cpp index 9f7725f..0babf06 100644 --- a/examples/xxhash/file_hash.cpp +++ b/examples/xxhash/file_hash.cpp @@ -21,7 +21,7 @@ int main(int argument_count, char **arguments) { } // The state is a plain value: each update returns it with one more chunk folded in. - checksum::xxh64_state state{}; + checksum::xxh64_state state; std::array buffer{}; while(file.read(buffer.data(), buffer.size()) || file.gcount() > 0) { state = checksum::xxhash_update(state, std::span{buffer}.first(static_cast(file.gcount()))); From 587e85d4d91c79db2f0e27700db16b6db42e259f Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:30:55 +0200 Subject: [PATCH 40/64] examples(adler32, fletcher4, internet, xxh3): compile-time examples --- README.md | 10 +++--- doc/adler32.md | 4 +-- doc/fletcher4.md | 4 +-- doc/internet.md | 5 +-- doc/xxhash.md | 4 +-- examples/adler32/CMakeLists.txt | 2 +- examples/adler32/compile_time.cpp | 27 ++++++++++++++++ examples/fletcher4/CMakeLists.txt | 2 +- examples/fletcher4/compile_time.cpp | 39 +++++++++++++++++++++++ examples/internet/CMakeLists.txt | 2 +- examples/internet/compile_time.cpp | 43 ++++++++++++++++++++++++++ examples/xxh3/CMakeLists.txt | 2 +- examples/xxh3/compile_time.cpp | 48 +++++++++++++++++++++++++++++ 13 files changed, 175 insertions(+), 17 deletions(-) create mode 100644 examples/adler32/compile_time.cpp create mode 100644 examples/fletcher4/compile_time.cpp create mode 100644 examples/internet/compile_time.cpp create mode 100644 examples/xxh3/compile_time.cpp diff --git a/README.md b/README.md index ed3d2bf..4c52e96 100644 --- a/README.md +++ b/README.md @@ -69,13 +69,13 @@ CPU acceleration follows your compiler flags (for example `-march=native` or `-m - [MurmurHash3 user guide](doc/murmur3.md): the API, seeds, byte order, measured performance and limitations. - [examples/crc](examples/crc): compile-time CRC, a file checksum, a custom CRC, run-time parameters, a MODBUS frame and a strategy driving an MCU CRC peripheral. -- [examples/internet](examples/internet): an IPv4 header, a UDP datagram with its pseudo-header and an incremental - update after a TTL decrement. +- [examples/internet](examples/internet): a header checksum computed at compile time, an IPv4 header, a UDP + datagram with its pseudo-header and an incremental update after a TTL decrement. - [examples/fletcher](examples/fletcher) and [examples/adler32](examples/adler32): compile-time checksums, a file checksum, a frame check, a zlib trailer and extending a stored Adler-32. -- [examples/fletcher4](examples/fletcher4): verifying a ZFS block and a file checksum. -- [examples/xxhash](examples/xxhash) and [examples/xxh3](examples/xxh3): compile-time IDs, file hashes, a cache key, - block deduplication and a seeded hash table. +- [examples/fletcher4](examples/fletcher4): a compile-time checksum, a file checksum and verifying a ZFS block. +- [examples/xxhash](examples/xxhash) and [examples/xxh3](examples/xxh3): compile-time message and asset IDs, file + hashes, a cache key, block deduplication and a seeded hash table. - [examples/murmur3](examples/murmur3): command dispatch, a Bloom filter and record deduplication. ## Contributing diff --git a/doc/adler32.md b/doc/adler32.md index b27b507..e134c18 100644 --- a/doc/adler32.md +++ b/doc/adler32.md @@ -29,8 +29,8 @@ static_assert(checksum::adler32_compute("123456789"sv) == 0x091E01DE); static_assert(checksum::adler32_compute("Wikipedia"sv) == 0x11E60398); ``` -`examples/adler32` has complete programs: checking the Adler-32 trailer of a zlib stream, and extending a stored -checksum when data is appended. +`examples/adler32` has complete programs: the checksum of default settings computed at compile time, checking the +Adler-32 trailer of a zlib stream, and extending a stored checksum when data is appended. ## 2. Definition diff --git a/doc/fletcher4.md b/doc/fletcher4.md index 3f48c11..a22b52e 100644 --- a/doc/fletcher4.md +++ b/doc/fletcher4.md @@ -27,8 +27,8 @@ static_assert(checksum::fletcher4_compute("abcdefgh"sv) == checksum::fletcher4_value{0xCCCAC8C6, 0x1312E2B27, 0x195918D88, 0x1F9F4EFE9}); ``` -`examples/fletcher4` has complete programs: verifying a 4 KiB block against its stored checksum as ZFS does, and the -checksum of a file read in chunks. +`examples/fletcher4` has complete programs: the checksum of a constant block computed at compile time, the checksum of +a file read in chunks, and verifying a 4 KiB block against its stored checksum as ZFS does. ## 2. Definition diff --git a/doc/internet.md b/doc/internet.md index 2099a22..ebe83de 100644 --- a/doc/internet.md +++ b/doc/internet.md @@ -28,8 +28,9 @@ std::uint16_t udp_checksum = checksum::internet_finalize(state); static_assert(checksum::internet_compute(std::string_view("123456789")) == 0xF62A); ``` -`examples/internet` has complete programs: an IPv4 header checksum filled in and verified, a UDP checksum summed from -the pseudo-header, the header and the payload, and the RFC 1624 update of a header after a TTL decrement. +`examples/internet` has complete programs: an IPv4 header template with its checksum filled in at compile time, an +IPv4 header checksum filled in and verified, a UDP checksum summed from the pseudo-header, the header and the payload, +and the RFC 1624 update of a header after a TTL decrement. ## 2. Definition diff --git a/doc/xxhash.md b/doc/xxhash.md index 41b1df6..56a979a 100644 --- a/doc/xxhash.md +++ b/doc/xxhash.md @@ -33,8 +33,8 @@ static_assert(checksum::xxh3_128_compute("abc"sv) == checksum::hash128{.low = 0x78AF5F94892F3950, .high = 0x06B05AB6733A6185}); ``` -`examples/xxh3` has complete programs: the XXH3-64 hash of a file read in chunks, deduplication of blocks by their -XXH3-128 hash, and a hash table with seeded XXH3-64. +`examples/xxh3` has complete programs: asset IDs hashed at compile time, the XXH3-64 hash of a file read in chunks, +deduplication of blocks by their XXH3-128 hash, and a hash table with seeded XXH3-64. ## 2. API diff --git a/examples/adler32/CMakeLists.txt b/examples/adler32/CMakeLists.txt index 70fc2e2..ee2ef44 100644 --- a/examples/adler32/CMakeLists.txt +++ b/examples/adler32/CMakeLists.txt @@ -1,4 +1,4 @@ -foreach (example resume zlib_trailer) +foreach (example compile_time resume zlib_trailer) add_executable(checksum_example_adler32_${example} ${example}.cpp) target_link_libraries(checksum_example_adler32_${example} PRIVATE checksum::checksum) endforeach () diff --git a/examples/adler32/compile_time.cpp b/examples/adler32/compile_time.cpp new file mode 100644 index 0000000..629f61a --- /dev/null +++ b/examples/adler32/compile_time.cpp @@ -0,0 +1,27 @@ +// Computes the Adler-32 of built-in default settings at compile time; at run time a copy of the settings is checked against +// that constant. + +#include + +#include +#include +#include +#include + +using namespace std::literals; + +// The compiler verifies the example of the Wikipedia article "Adler-32". +static_assert(checksum::adler32_compute("Wikipedia"sv) == 0x11E60398); + +constexpr std::string_view default_settings = "baud=115200\nparity=none\nstop_bits=1\n"sv; + +// A constant in read-only data: no code computes it at run time. +constexpr std::uint32_t default_settings_checksum = checksum::adler32_compute(default_settings); + +int main() { + // The settings as loaded into RAM, e.g. after a reset to defaults. + std::string const settings(default_settings); + std::uint32_t const value = checksum::adler32_compute(settings); + std::println("Adler-32 of the settings 0x{:08X}, expected 0x{:08X}", value, default_settings_checksum); + return value == default_settings_checksum ? 0 : 1; +} diff --git a/examples/fletcher4/CMakeLists.txt b/examples/fletcher4/CMakeLists.txt index 7233bdf..c059964 100644 --- a/examples/fletcher4/CMakeLists.txt +++ b/examples/fletcher4/CMakeLists.txt @@ -1,4 +1,4 @@ -foreach (example file_checksum zfs_block) +foreach (example compile_time file_checksum zfs_block) add_executable(checksum_example_fletcher4_${example} ${example}.cpp) target_link_libraries(checksum_example_fletcher4_${example} PRIVATE checksum::checksum) endforeach () diff --git a/examples/fletcher4/compile_time.cpp b/examples/fletcher4/compile_time.cpp new file mode 100644 index 0000000..99cbd01 --- /dev/null +++ b/examples/fletcher4/compile_time.cpp @@ -0,0 +1,39 @@ +// Computes the fletcher4 checksum of a constant 4 KiB block at compile time, the expected value a run-time check compares +// with. + +#include + +#include +#include +#include +#include + +using namespace std::literals; + +// The compiler verifies a value computed with fletcher_4_scalar_native of OpenZFS. +static_assert(checksum::fletcher4_compute("abcdefgh"sv) == checksum::fletcher4_value{0xCCCAC8C6, 0x1312E2B27, 0x195918D88, 0x1F9F4EFE9}); + +namespace { + +// A test pattern written to a disk, e.g. by a self-test. +constexpr std::array make_pattern() { + std::array block{}; + for(std::size_t index = 0; index < block.size(); ++index) { + block[index] = static_cast((index * 31) + 7); + } + return block; +} + +// The checksum of the pattern is a constant in read-only data; the block itself is not stored. +constexpr checksum::fletcher4_value pattern_checksum = checksum::fletcher4_compute(make_pattern()); +static_assert(pattern_checksum == checksum::fletcher4_value{0x1F9FE020400, 0x3F56A75807600, 0x54A3344A4A66000, 0x4E81CF973F7DBB00}); + +} // namespace + +int main() { + // The block as read back at run time. + std::array const block = make_pattern(); + checksum::fletcher4_value const value = checksum::fletcher4_compute(block); + std::println("{:x}:{:x}:{:x}:{:x}", value[0], value[1], value[2], value[3]); + return value == pattern_checksum ? 0 : 1; +} diff --git a/examples/internet/CMakeLists.txt b/examples/internet/CMakeLists.txt index 1810840..d23cfed 100644 --- a/examples/internet/CMakeLists.txt +++ b/examples/internet/CMakeLists.txt @@ -1,4 +1,4 @@ -foreach (example ipv4_header udp_datagram ttl_decrement) +foreach (example compile_time ipv4_header udp_datagram ttl_decrement) add_executable(checksum_example_internet_${example} ${example}.cpp) target_link_libraries(checksum_example_internet_${example} PRIVATE checksum::checksum) endforeach () diff --git a/examples/internet/compile_time.cpp b/examples/internet/compile_time.cpp new file mode 100644 index 0000000..c1a1ae1 --- /dev/null +++ b/examples/internet/compile_time.cpp @@ -0,0 +1,43 @@ +// Builds an IPv4 header template with its checksum filled in at compile time, for a device that always sends the same header. + +#include + +#include +#include +#include +#include +#include + +using namespace std::literals; + +// The compiler verifies the check value of "123456789". +static_assert(checksum::internet_compute("123456789"sv) == 0xF62A); + +namespace { + +// Returns header with its checksum, bytes 10 and 11, filled in most significant byte first. +constexpr std::array with_checksum(std::array header) { + header[10] = std::byte{0}; + header[11] = std::byte{0}; + std::uint16_t const value = checksum::internet_compute(header); + header[10] = static_cast(value >> 8U); + header[11] = static_cast(value & 0xFFU); + return header; +} + +// Version 4, total length 0x73, TTL 64, UDP, 192.168.0.1 to 192.168.0.199; a constant in read-only data. +constexpr std::array header_template = + with_checksum({std::byte{0x45}, std::byte{0x00}, std::byte{0x00}, std::byte{0x73}, std::byte{0x00}, std::byte{0x00}, std::byte{0x40}, + std::byte{0x00}, std::byte{0x40}, std::byte{0x11}, std::byte{0x00}, std::byte{0x00}, std::byte{0xC0}, std::byte{0xA8}, + std::byte{0x00}, std::byte{0x01}, std::byte{0xC0}, std::byte{0xA8}, std::byte{0x00}, std::byte{0xC7}}); +static_assert(header_template[10] == std::byte{0xB8} && header_template[11] == std::byte{0x61}); + +} // namespace + +int main() { + // A receiver sums the header with its checksum at run time and gets 0. + bool const valid = checksum::internet_compute(header_template) == 0; + std::println("IPv4 header checksum = 0x{:02X}{:02X}, header valid: {}", std::to_integer(header_template[10]), + std::to_integer(header_template[11]), valid ? "yes" : "no"); + return valid ? 0 : 1; +} diff --git a/examples/xxh3/CMakeLists.txt b/examples/xxh3/CMakeLists.txt index 7bcb0b6..0422964 100644 --- a/examples/xxh3/CMakeLists.txt +++ b/examples/xxh3/CMakeLists.txt @@ -1,4 +1,4 @@ -foreach (example file_hash deduplicate hash_table) +foreach (example compile_time file_hash deduplicate hash_table) add_executable(checksum_example_xxh3_${example} ${example}.cpp) target_link_libraries(checksum_example_xxh3_${example} PRIVATE checksum::checksum) endforeach () diff --git a/examples/xxh3/compile_time.cpp b/examples/xxh3/compile_time.cpp new file mode 100644 index 0000000..a9bd2f3 --- /dev/null +++ b/examples/xxh3/compile_time.cpp @@ -0,0 +1,48 @@ +// Hashes asset paths into 64-bit IDs at compile time, so that the program refers to assets by ID; the compiler rejects colliding +// IDs. + +#include + +#include +#include +#include +#include +#include + +using namespace std::literals; + +// The compiler verifies the XXH3-64 check value of "abc". +static_assert(checksum::xxh3_64_compute("abc"sv) == 0x78AF5F94892F3950); + +namespace { + +struct asset { + std::string_view path; + std::uint64_t id; +}; + +constexpr asset make_asset(std::string_view path) { return {.path = path, .id = checksum::xxh3_64_compute(path)}; } + +// The table is a constant in read-only data, sorted by ID for a binary search. +constexpr auto assets = [] { + std::array table{make_asset("textures/stone.png"), make_asset("textures/grass.png"), make_asset("sounds/step.wav"), make_asset("levels/intro.map")}; + std::ranges::sort(table, {}, &asset::id); + return table; +}(); +static_assert(std::ranges::adjacent_find(assets, {}, &asset::id) == assets.end(), "two paths have the same ID"); + +// The path of an ID, or an empty view for an unknown ID. +std::string_view find_path(std::uint64_t id) { + auto const found = std::ranges::lower_bound(assets, id, {}, &asset::id); + return found != assets.end() && found->id == id ? found->path : std::string_view{}; +} + +} // namespace + +int main() { + // A path read at run time, e.g. from a level file, hashes to the same ID. + std::uint64_t const id = checksum::xxh3_64_compute("sounds/step.wav"sv); + std::string_view const path = find_path(id); + std::println("ID 0x{:016X} -> {}", id, path); + return path == "sounds/step.wav" ? 0 : 1; +} From a9846e000f7955d1b23d3ed445cb8f97277708d8 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 15:55:41 +0200 Subject: [PATCH 41/64] docs, examples: review fixes (NDEBUG note, fletcher4 continuation, one hash per Bloom key) --- doc/crc.md | 2 +- doc/fletcher4.md | 2 ++ examples/murmur3/bloom_filter.cpp | 13 +++++++------ 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/doc/crc.md b/doc/crc.md index 922fcfd..6912643 100644 --- a/doc/crc.md +++ b/doc/crc.md @@ -154,7 +154,7 @@ std::uint16_t crc = can.compute(bits, 83); // bits: std::array A state passed to `update` or `finalize` must be below 2^width, and `bit_length` must not exceed `8 * data.size()`. Both are checked with `assert`. With `NDEBUG` the state is masked and the bit length clamped, -so a violation gives a wrong CRC but never undefined behavior. During constant evaluation a failed `assert` is a +so a violation gives a wrong CRC but never undefined behavior. Without `NDEBUG`, a failed `assert` during constant evaluation is a compile error. ## 6. Strategies diff --git a/doc/fletcher4.md b/doc/fletcher4.md index a22b52e..9b1c41e 100644 --- a/doc/fletcher4.md +++ b/doc/fletcher4.md @@ -144,6 +144,8 @@ The figures scale with the clock: the STM32L4A6 at 80 MHz runs the same cycles p message stay small. Use a CRC where errors must be detected reliably. - **Little-endian words only:** the equivalent of `fletcher_4_native` on a big-endian host needs its words swapped first. +- **No continuation from a stored checksum:** unlike Adler-32 and Fletcher, continuing needs the state, since a + checksum does not record an unfinished word. - **No verification helper:** compute the checksum and compare it with the stored one. - **No RISC-V or big-endian kernels.** - Code size has not been measured. diff --git a/examples/murmur3/bloom_filter.cpp b/examples/murmur3/bloom_filter.cpp index e4f0dc2..888e91c 100644 --- a/examples/murmur3/bloom_filter.cpp +++ b/examples/murmur3/bloom_filter.cpp @@ -15,15 +15,17 @@ namespace { class bloom_filter { public: void insert(std::string_view key) { + auto const hash = checksum::murmur3_128_compute(key); for(std::size_t index = 0; index < hash_count; ++index) { - bits.set(position(key, index)); + bits.set(position(hash, index)); } } // False means the key was never inserted; true means it probably was. [[nodiscard]] bool may_contain(std::string_view key) const { + auto const hash = checksum::murmur3_128_compute(key); for(std::size_t index = 0; index < hash_count; ++index) { - if(!bits.test(position(key, index))) { + if(!bits.test(position(hash, index))) { return false; } } @@ -34,10 +36,9 @@ class bloom_filter { static constexpr std::size_t bit_count = 1024; static constexpr std::size_t hash_count = 5; - // The halves h1 and h2 combine into hash_count positions as h1 + index * h2, double hashing. - static std::size_t position(std::string_view key, std::size_t index) { - auto const [h1, h2] = checksum::murmur3_128_compute(key); - return static_cast((h1 + (index * h2)) % bit_count); + // The halves h1 (low) and h2 (high) combine into hash_count positions as h1 + index * h2, double hashing. + static std::size_t position(checksum::hash128 hash, std::size_t index) { + return static_cast((hash.low + (index * hash.high)) % bit_count); } std::bitset bits; From 3668b359f7a2629b589d1eac00a647ad1163983f Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 15:56:12 +0200 Subject: [PATCH 42/64] fix(xxh3, fletcher4): portable XXH3 without SSE2, fletcher4_arch.hpp includes what it uses --- src/include_private/checksum_private/fletcher4_arch.hpp | 2 ++ src/include_private/checksum_private/x86_64/xxh3.hpp | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/src/include_private/checksum_private/fletcher4_arch.hpp b/src/include_private/checksum_private/fletcher4_arch.hpp index edc64d7..5e926f7 100644 --- a/src/include_private/checksum_private/fletcher4_arch.hpp +++ b/src/include_private/checksum_private/fletcher4_arch.hpp @@ -6,6 +6,8 @@ // - lane_kernel_available; if true, lane_kernel() // - lane_kernel_minimum_size: shortest input for lane_kernel() (max: never) +#include + #include #include #include diff --git a/src/include_private/checksum_private/x86_64/xxh3.hpp b/src/include_private/checksum_private/x86_64/xxh3.hpp index 48c88b6..f3e6ff3 100644 --- a/src/include_private/checksum_private/x86_64/xxh3.hpp +++ b/src/include_private/checksum_private/x86_64/xxh3.hpp @@ -4,6 +4,10 @@ // SSE2 and AVX2 kernels of the XXH3 stripe loop: SSE2 is part of x86-64, AVX2 runs where the flags enable it. Included only by // xxh3_arch.hpp. +#if !defined(__SSE2__) +#include +#else + #include #include @@ -119,4 +123,6 @@ inline void avx2_kernel::scramble(lanes &values, std::byte const *secret) noexce } // namespace checksum::xxh3_detail +#endif + #endif // CHECKSUM_PRIVATE_X86_64_XXH3_HPP From e688377707138b1e6035e503ab945a65b64aca2b Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 16:18:12 +0200 Subject: [PATCH 43/64] perf(xxh3): AArch64 kernel keeps its lanes in registers at -O2 At -O2 GCC did not unroll the scalar lane and scramble loops of the NEON kernel and kept the lanes in memory: the kernel ran 25 % slower than the portable loop on a Cortex-A72. Spelled out per vector and lane it beats the portable loop from the first stripe, so the threshold drops from 448 bytes to 0. --- .../checksum_private/arm/xxh3.hpp | 127 +++++++++++------- 1 file changed, 78 insertions(+), 49 deletions(-) diff --git a/src/include_private/checksum_private/arm/xxh3.hpp b/src/include_private/checksum_private/arm/xxh3.hpp index 2a7a142..ba86dc7 100644 --- a/src/include_private/checksum_private/arm/xxh3.hpp +++ b/src/include_private/checksum_private/arm/xxh3.hpp @@ -12,27 +12,21 @@ #include #include #include +#include +#include namespace checksum::xxh3_detail { inline constexpr bool stripe_kernel_available = true; -#if defined(__aarch64__) +// With GCC on a Cortex-A72 the kernel beats or ties the portable loop from 256 bytes, the shortest input that reaches it. +inline constexpr std::size_t stripe_kernel_minimum_size = 0; -// On a Cortex-A72 four lanes in NEON and four scalar ones beat both all eight in NEON and the portable loop. +#if defined(__aarch64__) +// On a Cortex-A72 four lanes in NEON and four scalar ones beat six and two, all eight in NEON, and the portable loop. inline constexpr std::size_t vector_count = 2; - -// With GCC on a Cortex-A72 the kernel ties the portable loop at 512-byte messages, 448 bytes of whole stripes, and is 2 % faster -// from 1500 bytes (4698 against 4602 MB/s at 4096); at 256 bytes it was 2 % slower. -inline constexpr std::size_t stripe_kernel_minimum_size = 448; - #else - inline constexpr std::size_t vector_count = 4; - -// With GCC on a Cortex-A72 in AArch32 the kernel beats the portable loop 1.4 to 1.55 times from 256 bytes, the shortest size measured. -inline constexpr std::size_t stripe_kernel_minimum_size = 0; - #endif // The first lanes in 128-bit vectors of two, on AArch64 the rest in scalars. An empty scalar array would keep GCC on AArch32 @@ -53,11 +47,70 @@ struct stripe_kernel { // The 16 bytes at data as two little-endian 64-bit lanes. inline uint64x2_t load_vector(std::byte const *data) noexcept; +// Mixes the vectors Index and Index + 1 of one stripe into their lanes: one unzip gives the low and the high 32-bit halves of +// data ^ secret for four lanes. +template void accumulate_vector_pair(stripe_kernel::lanes &values, std::byte const *stripe, std::byte const *secret) noexcept; + +// Scrambles vector Index. The 32-bit products with the prime in the high halves give the high word of the 64-bit product; the low +// halves add their full product. +template void scramble_vector(stripe_kernel::lanes &values, std::byte const *secret) noexcept; + +#if defined(__aarch64__) +// Mixes scalar lane Index of one stripe into the scalars, as accumulate_lane() does. +template void accumulate_scalar(stripe_kernel::lanes &values, std::byte const *stripe, std::byte const *secret) noexcept; + +// Scrambles scalar lane Index, as portable_kernel::scramble() does. +template void scramble_scalar(stripe_kernel::lanes &values, std::byte const *secret) noexcept; +#endif + inline uint64x2_t load_vector(std::byte const *data) noexcept { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): byte view for the vector load. return vreinterpretq_u64_u8(vld1q_u8(reinterpret_cast(data))); } +template +[[gnu::always_inline]] inline void accumulate_vector_pair(stripe_kernel::lanes &values, std::byte const *stripe, std::byte const *secret) noexcept { + uint64x2_t const first = load_vector(stripe + (16 * Index)); + uint64x2_t const second = load_vector(stripe + (16 * Index) + 16); + uint64x2_t const first_key = veorq_u64(first, load_vector(secret + (16 * Index))); + uint64x2_t const second_key = veorq_u64(second, load_vector(secret + (16 * Index) + 16)); + uint32x4x2_t const halves = vuzpq_u32(vreinterpretq_u32_u64(first_key), vreinterpretq_u32_u64(second_key)); + uint64x2_t const first_sum = vmlal_u32(vextq_u64(first, first, 1), vget_low_u32(halves.val[0]), vget_low_u32(halves.val[1])); +#if defined(__aarch64__) + uint64x2_t const second_sum = vmlal_high_u32(vextq_u64(second, second, 1), halves.val[0], halves.val[1]); +#else + uint64x2_t const second_sum = vmlal_u32(vextq_u64(second, second, 1), vget_high_u32(halves.val[0]), vget_high_u32(halves.val[1])); +#endif + std::get(values.vectors) = vaddq_u64(std::get(values.vectors), first_sum); + std::get(values.vectors) = vaddq_u64(std::get(values.vectors), second_sum); +} + +template [[gnu::always_inline]] inline void scramble_vector(stripe_kernel::lanes &values, std::byte const *secret) noexcept { + uint32x2_t const prime = vdup_n_u32(primes_32::prime_1); + uint32x4_t const prime_high = vreinterpretq_u32_u64(vdupq_n_u64(std::uint64_t{primes_32::prime_1} << 32U)); + uint64x2_t &vector = std::get(values.vectors); + uint64x2_t const key = veorq_u64(veorq_u64(vector, vshrq_n_u64(vector, scramble_shift)), load_vector(secret + (16 * Index))); + uint32x4_t const high = vmulq_u32(vreinterpretq_u32_u64(key), prime_high); + vector = vmlal_u32(vreinterpretq_u64_u32(high), vmovn_u64(key), prime); +} + +#if defined(__aarch64__) +template +[[gnu::always_inline]] inline void accumulate_scalar(stripe_kernel::lanes &values, std::byte const *stripe, std::byte const *secret) noexcept { + constexpr std::size_t lane = (2 * vector_count) + Index; + auto const word = xxh3_detail::load(stripe + (8 * lane)); + std::uint64_t const key = word ^ xxh3_detail::load(secret + (8 * lane)); + std::get(values.scalars) += word; + std::get(values.scalars) += (key & low_half_mask) * (key >> 32U); +} + +template [[gnu::always_inline]] inline void scramble_scalar(stripe_kernel::lanes &values, std::byte const *secret) noexcept { + constexpr std::size_t lane = (2 * vector_count) + Index; + std::uint64_t &scalar = std::get(values.scalars); + scalar = (scalar ^ (scalar >> scramble_shift) ^ xxh3_detail::load(secret + (8 * lane))) * primes_32::prime_1; +} +#endif + inline stripe_kernel::lanes stripe_kernel::load(accumulator_array const &accumulators) noexcept { lanes values{}; for(std::size_t index = 0; index < vector_count; ++index) { @@ -82,50 +135,26 @@ inline void stripe_kernel::store(accumulator_array &accumulators, lanes const &v #endif } -// Two vectors at a time: one unzip gives the low and the high 32-bit halves of data ^ secret for four lanes. +// Spelled out per vector and lane: at -O2, GCC keeps the lanes of a loop that it does not unroll in memory. inline void stripe_kernel::accumulate(lanes &values, std::byte const *stripe, std::byte const *secret) noexcept { - for(std::size_t index = 0; index < vector_count; index += 2) { - uint64x2_t const first = load_vector(stripe + (16 * index)); - uint64x2_t const second = load_vector(stripe + (16 * index) + 16); - uint64x2_t const first_key = veorq_u64(first, load_vector(secret + (16 * index))); - uint64x2_t const second_key = veorq_u64(second, load_vector(secret + (16 * index) + 16)); - uint32x4x2_t const halves = vuzpq_u32(vreinterpretq_u32_u64(first_key), vreinterpretq_u32_u64(second_key)); - uint64x2_t const first_sum = vmlal_u32(vextq_u64(first, first, 1), vget_low_u32(halves.val[0]), vget_low_u32(halves.val[1])); + [&] [[gnu::always_inline]] (std::index_sequence) { + (accumulate_vector_pair<2 * Pair>(values, stripe, secret), ...); + }(std::make_index_sequence{}); #if defined(__aarch64__) - uint64x2_t const second_sum = vmlal_high_u32(vextq_u64(second, second, 1), halves.val[0], halves.val[1]); -#else - uint64x2_t const second_sum = vmlal_u32(vextq_u64(second, second, 1), vget_high_u32(halves.val[0]), vget_high_u32(halves.val[1])); -#endif - values.vectors[index] = vaddq_u64(values.vectors[index], first_sum); - values.vectors[index + 1] = vaddq_u64(values.vectors[index + 1], second_sum); - } -#if defined(__aarch64__) - for(std::size_t index = 0; index < values.scalars.size(); ++index) { - std::size_t const lane = (2 * vector_count) + index; - auto const word = xxh3_detail::load(stripe + (8 * lane)); - std::uint64_t const key = word ^ xxh3_detail::load(secret + (8 * lane)); - values.scalars[index ^ 1U] += word; - values.scalars[index] += (key & low_half_mask) * (key >> 32U); - } + [&] [[gnu::always_inline]] (std::index_sequence) { + (accumulate_scalar(values, stripe, secret), ...); + }(std::make_index_sequence>{}); #endif } -// The 32-bit products with the prime in the high halves give the high word of the 64-bit product; the low halves add their full product. inline void stripe_kernel::scramble(lanes &values, std::byte const *secret) noexcept { - uint32x2_t const prime = vdup_n_u32(primes_32::prime_1); - uint32x4_t const prime_high = vreinterpretq_u32_u64(vdupq_n_u64(std::uint64_t{primes_32::prime_1} << 32U)); - for(std::size_t index = 0; index < vector_count; ++index) { - uint64x2_t const mixed = veorq_u64(values.vectors[index], vshrq_n_u64(values.vectors[index], scramble_shift)); - uint64x2_t const key = veorq_u64(mixed, load_vector(secret + (16 * index))); - uint32x4_t const high = vmulq_u32(vreinterpretq_u32_u64(key), prime_high); - values.vectors[index] = vmlal_u32(vreinterpretq_u64_u32(high), vmovn_u64(key), prime); - } + [&] [[gnu::always_inline]] (std::index_sequence) { + (scramble_vector(values, secret), ...); + }(std::make_index_sequence{}); #if defined(__aarch64__) - for(std::size_t index = 0; index < values.scalars.size(); ++index) { - std::size_t const lane = (2 * vector_count) + index; - std::uint64_t const accumulator = values.scalars[index] ^ (values.scalars[index] >> scramble_shift); - values.scalars[index] = (accumulator ^ xxh3_detail::load(secret + (8 * lane))) * primes_32::prime_1; - } + [&] [[gnu::always_inline]] (std::index_sequence) { + (scramble_scalar(values, secret), ...); + }(std::make_index_sequence>{}); #endif } From c1f1d53552c7cd81e50da0103d24c73b71d7092d Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 16:18:39 +0200 Subject: [PATCH 44/64] perf(xxhash): one-shot XXH64 keeps its lanes in locals on 64-bit targets The one-shot XXH64 now runs the same out-of-line function as XXH32, with the lanes in registers and converge() spelled out: 0.88 to 1.0 of xxHash 0.8.4 at 64 bytes on x86-64 with GCC 16, and 1.3 at 20 bytes. A compiler barrier keeps GCC from folding the last stripe multiplication into converge(), which slowed the stripe loop. 32-bit targets keep the stripe loop: on Cortex-M4 the 64-bit lanes do not fit the registers. --- src/include/checksum/xxhash.hpp | 19 +++++++++++-------- src/xxhash/stripe_loop.cpp | 22 ++++++++++++++++------ 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/src/include/checksum/xxhash.hpp b/src/include/checksum/xxhash.hpp index fd2441e..5b4eae9 100644 --- a/src/include/checksum/xxhash.hpp +++ b/src/include/checksum/xxhash.hpp @@ -142,9 +142,9 @@ template constexpr word avalanche(word hash) noex template constexpr word finish(word converged, word seed, std::uint64_t length, std::span tail) noexcept; -// The XXH32 hash of data of at least one stripe, defined in src/xxhash/stripe_loop.cpp. Its lanes are locals, which GCC and Clang -// keep in scalar registers: on Cortex-M4 a stripe takes 24.5 cycles, against 28.6 through stripe_loop(). -std::uint32_t run_time_xxh32(std::span data, std::uint32_t seed) noexcept; +// The hash of data of at least one stripe, defined in src/xxhash/stripe_loop.cpp for both widths. Its lanes are locals, which GCC +// and Clang keep in scalar registers: on Cortex-M4 an XXH32 stripe takes 24.5 cycles, against 28.6 through stripe_loop(). +template word run_time_hash(std::span data, word seed) noexcept; } // namespace checksum::xxhash_detail @@ -169,9 +169,11 @@ template constexpr word converge(lane_array const word hash = std::rotl(lanes[0], convergence_rotations[0]) + std::rotl(lanes[1], convergence_rotations[1]) + std::rotl(lanes[2], convergence_rotations[2]) + std::rotl(lanes[3], convergence_rotations[3]); if constexpr(Width == 64) { - for(word const lane : lanes) { - hash = ((hash ^ round(0, lane)) * constants::prime_1) + constants::prime_4; - } + // Spelled out: GCC keeps the lanes of a loop here in memory. + auto const merge = [](word value, word lane) { + return ((value ^ round(0, lane)) * constants::prime_1) + constants::prime_4; + }; + hash = merge(merge(merge(merge(hash, lanes[0]), lanes[1]), lanes[2]), lanes[3]); } return hash; } @@ -280,10 +282,11 @@ template constexpr xxhash_state::value_type xxhash_final template constexpr xxhash_state::value_type xxhash_compute(std::span data, typename xxhash_state::value_type seed) noexcept { std::size_t const whole = data.size() - (data.size() % xxhash_detail::stripe_size); - if constexpr(Width == 32) { + // On 32-bit targets the four lanes of XXH64 do not fit the registers: as locals they ran 18 % slower on Cortex-M4. + if constexpr(sizeof(std::size_t) >= sizeof(xxhash_detail::word)) { if !consteval { if(whole != 0) { - return xxhash_detail::run_time_xxh32(data, seed); + return xxhash_detail::run_time_hash(data, seed); } } } diff --git a/src/xxhash/stripe_loop.cpp b/src/xxhash/stripe_loop.cpp index 96cd2bc..c348a37 100644 --- a/src/xxhash/stripe_loop.cpp +++ b/src/xxhash/stripe_loop.cpp @@ -1,4 +1,4 @@ -// Run-time stripe loop of XXH32 and XXH64, and the run-time XXH32 hash. +// Run-time stripe loop of XXH32 and XXH64, and the run-time hashes. #include @@ -15,14 +15,24 @@ template return converged ? converge(lanes) : 0; } -std::uint32_t run_time_xxh32(std::span data, std::uint32_t seed) noexcept { - std::size_t const whole = data.size() - (data.size() % stripe_size<32>); - lane_array<32> lanes = initial_lanes<32>(seed); - fold_stripes<32>(lanes, data.first(whole)); - return finish<32>(converge<32>(lanes), seed, data.size(), data.subspan(whole)); +template word run_time_hash(std::span data, word seed) noexcept { + std::size_t const whole = data.size() - (data.size() % stripe_size); + lane_array lanes = initial_lanes(seed); + fold_stripes(lanes, data.first(whole)); + if constexpr(Width == 64) { + // Hides how the lanes were computed: GCC otherwise merges the last multiplication of each stripe with the first one of converge(), + // which keeps two values per lane in the stripe loop and made XXH64 7 % slower at 1 to 2 KiB on x86-64. + asm("" : "+r"(lanes[0])); + asm("" : "+r"(lanes[1])); + asm("" : "+r"(lanes[2])); + asm("" : "+r"(lanes[3])); + } + return finish(converge(lanes), seed, data.size(), data.subspan(whole)); } template std::uint32_t stripe_loop<32>(lane_array<32> &, std::span, bool) noexcept; template std::uint64_t stripe_loop<64>(lane_array<64> &, std::span, bool) noexcept; +template std::uint32_t run_time_hash<32>(std::span, std::uint32_t) noexcept; +template std::uint64_t run_time_hash<64>(std::span, std::uint64_t) noexcept; } // namespace checksum::xxhash_detail From 61d09189fa761d9381e2c7b01f6498b99d1a9b5c Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 16:18:44 +0200 Subject: [PATCH 45/64] perf(murmur3): one-shot x86_32 keeps its lane in a register The one-shot MurmurHash3_x86_32 runs one out-of-line function instead of passing its lane through memory to block_loop(): on a Cortex-A72 0.81 to 1.0 of SMHasher at 20 bytes and 0.92 to 0.98 at 64 bytes. On Cortex-M4 the loop is the same. --- src/include/checksum/murmur3.hpp | 11 +++++++++++ src/murmur3/block_loop.cpp | 8 +++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/include/checksum/murmur3.hpp b/src/include/checksum/murmur3.hpp index 4abd877..2e13cb3 100644 --- a/src/include/checksum/murmur3.hpp +++ b/src/include/checksum/murmur3.hpp @@ -139,6 +139,10 @@ template constexpr void fold(lane_array &lanes, std::spa template constexpr murmur3_state::value_type finish(lane_array lanes, std::uint64_t length, std::span tail) noexcept; +// The x86_32 hash of data of at least one block, defined in src/murmur3/block_loop.cpp. Its lane is a local, which stays in a register: +// through block_loop() it goes through memory. +std::uint32_t run_time_hash_32(std::span data, std::uint32_t seed) noexcept; + } // namespace checksum::murmur3_detail ///@} @@ -285,6 +289,13 @@ template constexpr murmur3_state::value_type murmur3_fin template constexpr murmur3_state::value_type murmur3_compute(std::span data, std::uint32_t seed) noexcept { std::size_t const whole = data.size() - (data.size() % murmur3_detail::block_size); + if constexpr(Width == 32) { + if !consteval { + if(whole != 0) { + return murmur3_detail::run_time_hash_32(data, seed); + } + } + } murmur3_detail::lane_array lanes = murmur3_detail::initial_lanes(seed); if(whole != 0) { murmur3_detail::fold(lanes, data.first(whole)); diff --git a/src/murmur3/block_loop.cpp b/src/murmur3/block_loop.cpp index 52b3cd8..bef8af1 100644 --- a/src/murmur3/block_loop.cpp +++ b/src/murmur3/block_loop.cpp @@ -1,8 +1,9 @@ -// Run-time block loop of MurmurHash3_x86_32 and MurmurHash3_x64_128. +// Run-time block loop of MurmurHash3_x86_32 and MurmurHash3_x64_128, and the run-time x86_32 hash. #include #include +#include #include namespace checksum::murmur3_detail { @@ -12,6 +13,11 @@ template void block_loop(lane_array &lanes, std::span(lanes, data); } +std::uint32_t run_time_hash_32(std::span data, std::uint32_t seed) noexcept { + std::size_t const whole = data.size() - (data.size() % block_size<32>); + return finish<32>(fold_blocks<32>(initial_lanes<32>(seed), data.first(whole)), data.size(), data.subspan(whole)); +} + template void block_loop<32>(lane_array<32> &, std::span) noexcept; template void block_loop<128>(lane_array<128> &, std::span) noexcept; From 785870ebd4fe033146724c06086eb4580a46e683 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 16:26:27 +0200 Subject: [PATCH 46/64] docs(xxhash, murmur3): -O2 measurements on the A72, AArch64 kernel from the first stripe The Cortex-A72 tables were measured at -O3, which hid the slow AArch64 kernel; they now come from the -O2 benchmark builds. Adds one-line comparisons with xxHash v0.8.4 and SMHasher. --- doc/design/acceleration.md | 19 ++++++++++++--- doc/murmur3.md | 18 ++++++++------ doc/xxhash.md | 50 ++++++++++++++++++++------------------ 3 files changed, 52 insertions(+), 35 deletions(-) diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index fe088d2..6181cda 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -195,6 +195,12 @@ The stripe loop is compiled once per width in `src/xxhash/stripe_loop.cpp` and i lanes may alias the data, which keeps compilers from packing them into one vector register. The four lanes converge in spelled-out code; as a loop, GCC reloaded the lanes it had just stored as one vector, which stalls. +The one-shot hash keeps the lanes in local variables, in one out-of-line function per width: XXH32 on every target, +XXH64 only on 64-bit targets, since on Cortex-M4 its 64-bit lanes spilled and ran 18 % slower. XXH64 went from 0.88 +to 1.0× xxHash v0.8.4 at 64 B on x86-64. An empty `asm` statement on the lanes after the stripe loop keeps GCC from +merging the last multiplication of each lane into the convergence, which kept two values per lane in the loop and cost +7 % at 1-2 KiB. + ## XXH3 Inputs up to 240 bytes run straight-line code (0-16, 17-128 and 129-240 bytes, each separately) and never reach a @@ -209,8 +215,8 @@ halves of data XOR secret, plus the neighbor lane's data, and a scramble after e | x86-64 AVX2 | Yes, every stripe loop | GCC 16: 48 994 MB/s at 1 MiB (3.5× the portable loop), 2.6× at 256 B; Clang 21: 46 907. The reference runs 47 996. | | x86-64 AVX-512 | Not measured | No AVX-512 hardware available. | | AArch64 NEON, all eight lanes | No | Cortex-A72: slower than the portable loop from 256 B on, 2.21 against 2.57 GiB/s at 256 B and 3.64 against 3.93 at 4 KiB. | -| AArch64 NEON, four lanes in NEON and four scalar | Yes, from 448 B of whole stripes | A72: 4 315 against 4 239 MB/s at 1500 B, 4 698 against 4 602 at 4 KiB, a tie at 512 B, 2 % slower at 256 B. Six NEON lanes and two scalar ones, and all eight in NEON, were slower than four and four. | -| 32-bit Arm NEON, little-endian | Yes, every stripe loop | A72 in AArch32: 1 596 against 1 144 MB/s at 256 B, 2 826 against 1 827 at 4 KiB (1.55×), where the portable loop builds 64-bit additions from 32-bit ones. | +| AArch64 NEON, four lanes in NEON and four scalar | Yes, every stripe loop | A72, GCC `-O2`: 2 643 against 2 238 MB/s at 256 B, 4 704 against 3 771 at 4 KiB (1.25×); at `-O3` it ties the portable loop at 256 B and is 2 % faster at 4 KiB. Six NEON lanes and two scalar ones (the reference's split) ran 4 374 MB/s at 4 KiB and 3 807 at 1 MiB against 4 719 and 4 029; all eight in NEON were slower too. | +| 32-bit Arm NEON, little-endian | Yes, every stripe loop | A72 in AArch32, GCC `-O2`: 1 544 against 921 MB/s at 256 B, 2 807 against 1 341 at 4 KiB (2.1×), where the portable loop builds 64-bit additions from 32-bit ones. | | Big-endian NEON | No | The kernels read vector lanes as little-endian values; big-endian targets run the portable loop. | | RISC-V V extension, VLEN ≥ 128 | Implemented, unproven | The eight accumulators in one register group (`vuint64m4_t`); about ten vector instructions per stripe instead of about fifty scalar ones. Tested in QEMU only. | | Cortex-M | No kernel | No vector unit; the portable loop runs. | @@ -218,8 +224,13 @@ halves of data XOR secret, plus the neighbor lane's data, and a scramble after e Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cortex-A72): - Kernel thresholds: x86-64 and AArch32 NEON from the first stripe, since both kernels beat the portable loop at - 256 B, the shortest input that reaches them. AArch64 from 448 bytes of whole stripes, messages from 512 bytes, where - the four-plus-four kernel overtakes the portable loop (3.31 against 3.25 GiB/s at 512 B). + 256 B, the shortest input that reaches them; so does AArch64, where the four-plus-four kernel is 1.18× the portable + loop at 256 B with `-O2` and ties it with `-O3`. +- The AArch64 kernel spells out its vector and scalar lanes: as loops, GCC at `-O2` did not unroll them and kept the + lanes in memory, which made the kernel 25 % slower than the portable loop (2 831 against 3 798 MB/s at 4 KiB). + Builds at `-O3` unrolled them, which hid the problem. +- Software prefetch 384 bytes ahead, as the reference does, gained 7 % at 1 MiB on the A72 and lost 1-3 % from 1 to + 4 KiB; the kernel does not prefetch. - AArch32 keeps all eight lanes in NEON: an empty scalar array kept GCC from holding the lanes in registers. - The RVV kernel requires `__riscv_v_min_vlen >= 128` and 64-bit elements: at VLEN 64 the register group holds only four lanes. diff --git a/doc/murmur3.md b/doc/murmur3.md index 721a9a3..6881186 100644 --- a/doc/murmur3.md +++ b/doc/murmur3.md @@ -70,9 +70,10 @@ the unused bytes of the buffer are ignored. MurmurHash3 has no kernel, on any target. Every block updates the hash lanes through a rotation, a multiplication and an addition of their previous values, and in MurmurHash3_x64_128 the second lane also takes the first lane of the same -block. Blocks cannot be processed in parallel, so vector instructions have nothing to work on. The one run-time -function, the block loop, is compiled once per width in `src/murmur3/block_loop.cpp`; MurmurHash3_x64_128 inputs under -256 bytes fold inline instead, which saves the call. +block. Blocks cannot be processed in parallel, so vector instructions have nothing to work on. The block loop is +compiled once per width in `src/murmur3/block_loop.cpp`; MurmurHash3_x64_128 inputs under 256 bytes fold inline +instead, which saves the call, and the one-shot MurmurHash3_x86_32 runs a function there that keeps its lane in a +register. MurmurHash3_x64_128 needs 64-bit multiplications, which 32-bit targets build from several 32-bit ones. On 32-bit targets MurmurHash3_x86_32 is the faster of the two; on 64-bit targets MurmurHash3_x64_128 is at least as fast at 20 @@ -82,8 +83,8 @@ bytes and faster from 64 bytes. ### 5.1 x86-64: Core Ultra 7 155H -GCC, `-O2 -march=native`: MurmurHash3_x86_32 runs 5 388 MB/s at 20 bytes and 4 233 at 1 MiB, MurmurHash3_x64_128 -6 140 and 10 006. +GCC, `-O2 -march=native`: MurmurHash3_x86_32 runs 5 850 MB/s at 20 bytes and 4 499 at 1 MiB, MurmurHash3_x64_128 +6 140 and 10 006. Both are at least as fast as SMHasher's MurmurHash3.cpp with the same flags. ### 5.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz @@ -91,11 +92,14 @@ GCC 14.3, `-O2`, one core. MB/s (10⁶ bytes per second): | Hash, mode | 20 B | 64 B | 256 B | 1500 B | 4 KiB | 1 MiB | | --- | --- | --- | --- | --- | --- | --- | -| x86_32, AArch64 | 646 | 951 | 1 078 | 1 168 | 1 181 | 1 142 | +| x86_32, AArch64 | 720 | 981 | 1 084 | 1 169 | 1 182 | 1 143 | | x64_128, AArch64 | 646 | 1 081 | 1 430 | 1 634 | 1 672 | 1 619 | -| x86_32, AArch32 | 653 | 952 | 1 063 | 1 166 | 1 180 | 1 093 | +| x86_32, AArch32 | 618 | 902 | 1 066 | 1 167 | 1 180 | 1 098 | | x64_128, AArch32 | 278 | 408 | 536 | 595 | 604 | 599 | +On AArch64 MurmurHash3_x86_32 runs 0.95 to 1.0× as fast as SMHasher's MurmurHash3.cpp at every size, with `-O2` or +`-O2 -mcpu=cortex-a72`. + ### 5.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz GCC 14.3, `-O2`, code in flash and data in RAM, measured with the cycle counter. At 4 KiB MurmurHash3_x86_32 takes diff --git a/doc/xxhash.md b/doc/xxhash.md index 56a979a..7b0c408 100644 --- a/doc/xxhash.md +++ b/doc/xxhash.md @@ -115,7 +115,8 @@ rotation per word; the scalar loop already keeps four of them in flight. A NEON Cortex-A72 at 4 KiB against 2 333 for the scalar loop, and Clang vectorizing the lanes on its own lost 38 % on x86-64. XXH64 needs 64-bit multiplications per lane, which SSE2, AVX2 and NEON do not have. The stripe loop is compiled once per width in `src/xxhash/stripe_loop.cpp`, out of line, so that compilers keep the lanes scalar; the -one-shot XXH32 of a message of at least 16 bytes runs a function there that keeps them in local variables. +one-shot hash of a message of at least one stripe runs a function there that keeps them in local variables, for XXH32 +on every target and for XXH64 on 64-bit targets. ### 4.2 XXH3 @@ -126,14 +127,14 @@ Inputs up to 240 bytes run straight-line code with no loop and no kernel. Longer | --- | --- | | x86-64 with AVX2 (`-mavx2`, or a `-march` that includes it) | Two 256-bit vectors, every stripe. | | x86-64 without AVX2 (SSE2 is always there) | Four 128-bit vectors, every stripe. | -| AArch64, little-endian | Four lanes in NEON and four in scalar registers, from 448 bytes of whole stripes in one fold: one-shot messages from 512 bytes, and `xxh3_update` calls that fold that much past the state's 256-byte buffer. | +| AArch64, little-endian | Four lanes in NEON and four in scalar registers, every stripe. | | 32-bit Arm with NEON, little-endian | All eight lanes in NEON, every stripe. | | RISC-V RV64 with the V extension, VLEN ≥ 128 | One register group of eight 64-bit lanes, every stripe. Tested in QEMU, not measured on hardware. | | everything else (Cortex-M, 32-bit Arm without NEON, big-endian, RISC-V without V), or `CHECKSUM_ACCELERATION=OFF` | Portable loop. | The kernel is selected at compile time from the compiler flags; there is no run-time CPU detection. Constant -evaluation always runs the portable code with the same result. On AArch64 the portable loop is faster below -512 bytes, and four NEON lanes with four scalar ones beat all eight in NEON. The measurements behind each choice are in +evaluation always runs the portable code with the same result. On AArch64 four NEON lanes with four scalar ones +beat six and two, and all eight in NEON. The measurements behind each choice are in [design/acceleration.md](design/acceleration.md#xxh3). ## 5. Performance @@ -151,32 +152,33 @@ default x86-64 flags, AVX2 a build with AVX2 enabled. With Clang 21 at 1 MiB: 20 107 MB/s portable, 32 658 SSE2, 46 907 AVX2. Up to 240 bytes the three builds run the same code, and 64 bytes are faster than 256 because they need no stripe loop. At 1 MiB AVX2 is 3.5× the -portable loop and SSE2 1.6×. With `-march=native` (AVX2), MB/s at 20 B and 1 MiB: XXH32 6 831 and 8 743, XXH64 7 371 and 17 689, XXH3-128 7 827 and -50 172. +portable loop and SSE2 1.6×. With `-march=native` (AVX2), MB/s at 20 B and 1 MiB: XXH32 6 831 and 8 743, XXH64 8 186 and +18 364, XXH3-128 7 827 and 50 172. With the same flags all four hashes match xxHash v0.8.4 from 64 bytes, except XXH3 +at 256 bytes (0.92×), and are faster at 20 bytes. ### 5.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz -GCC 14.3, `-O2`, one core, MB/s: +GCC 14.3, `-O2` (the benchmark presets), one core, MB/s; AArch32 with `-march=armv8-a+crc -mfpu=neon-fp-armv8`: | Hash, build | 20 B | 64 B | 256 B | 1500 B | 4 KiB | 1 MiB | | --- | --- | --- | --- | --- | --- | --- | -| XXH32, AArch64 | 857 | 1 730 | 2 521 | 2 808 | 2 916 | 2 656 | -| XXH64, AArch64 | 862 | 942 | 1 553 | 1 874 | 1 949 | 1 891 | -| XXH3-64, AArch64 portable | 1 239 | 2 440 | 2 799 | 4 239 | 4 602 | 4 134 | -| XXH3-64, AArch64 NEON | 1 239 | 2 440 | 2 799 | 4 315 | 4 698 | 4 148 | -| XXH3-128, AArch64 portable | 804 | 1 795 | 2 035 | 3 865 | 4 431 | 4 129 | -| XXH3-128, AArch64 NEON | 804 | 1 796 | 2 014 | 3 867 | 4 452 | 4 156 | -| XXH32, AArch32 | 646 | 1 419 | 2 161 | 2 491 | 2 589 | 2 326 | -| XXH64, AArch32 | 323 | 370 | 594 | 699 | 730 | 724 | -| XXH3-64, AArch32 portable | 712 | 1 275 | 1 144 | 1 687 | 1 827 | 1 772 | -| XXH3-64, AArch32 NEON | 712 | 1 275 | 1 596 | 2 561 | 2 826 | 2 640 | -| XXH3-128, AArch32 portable | 448 | 883 | 928 | 1 588 | 1 783 | 1 778 | -| XXH3-128, AArch32 NEON | 450 | 877 | 1 214 | 2 355 | 2 703 | 2 642 | - -On AArch64 the NEON kernel runs from 512 bytes and gains 2 % at 4 KiB over a portable loop that the compiler already -schedules well; on AArch32 NEON is 1.5× faster from 1500 bytes. XXH64 needs 64-bit multiplications, which AArch32 -builds from 32-bit ones; there XXH32 is the fastest of the four up to 64 bytes and from 256 bytes on a par with -XXH3-64 NEON. +| XXH32, AArch64 | 775 | 1 730 | 2 521 | 2 787 | 2 914 | 2 635 | +| XXH64, AArch64 | 812 | 915 | 1 535 | 1 868 | 1 948 | 1 889 | +| XXH3-64, AArch64 portable | 911 | 1 884 | 2 238 | 3 446 | 3 771 | 3 394 | +| XXH3-64, AArch64 NEON | 910 | 1 885 | 2 643 | 4 280 | 4 704 | 4 113 | +| XXH3-128, AArch64 portable | 875 | 1 866 | 1 864 | 3 275 | 3 699 | 3 415 | +| XXH3-128, AArch64 NEON | 874 | 1 866 | 2 229 | 4 055 | 4 598 | 4 109 | +| XXH32, AArch32 | 633 | 1 460 | 2 352 | 2 767 | 2 904 | 2 580 | +| XXH64, AArch32 | 286 | 367 | 596 | 698 | 731 | 723 | +| XXH3-64, AArch32 portable | 522 | 1 057 | 921 | 1 235 | 1 341 | 1 308 | +| XXH3-64, AArch32 NEON | 522 | 1 057 | 1 544 | 2 494 | 2 807 | 2 652 | +| XXH3-128, AArch32 portable | 442 | 881 | 794 | 1 192 | 1 321 | 1 307 | +| XXH3-128, AArch32 NEON | 441 | 881 | 1 224 | 2 332 | 2 728 | 2 655 | + +On AArch64 the NEON kernel is 1.18× the portable loop at 256 bytes and 1.25× at 4 KiB; on AArch32 NEON is 2× faster +from 1500 bytes. XXH64 needs 64-bit multiplications, which AArch32 builds from 32-bit ones; there XXH32 is the fastest +of the four up to 4 KiB. Against xxHash v0.8.4 built the same way, with `-O2` or `-O2 -mcpu=cortex-a72`, XXH3 is 1.0 +to 1.15× from 1500 bytes and 0.95 to 1.05× at 256 bytes; XXH32 and XXH64 match it from 256 bytes. ### 5.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz From 73212abeb6f6f11bb09961465a528619843b546c Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 16:29:42 +0200 Subject: [PATCH 47/64] test: -Og Debug builds, fewer Fletcher/Adler-32 offsets, VPCLMULQDQ and EOR3 in the test presets --- CMakePresets.json | 1 + cmake/common_presets.json | 4 ++-- cmake/emulator_presets.json | 12 ++++++++---- cmake/x86_64_presets.json | 6 +++--- doc/design/testing.md | 3 ++- tests/unit_tests/ut_adler32.cpp | 6 +++--- tests/unit_tests/ut_fletcher.cpp | 6 +++--- 7 files changed, 22 insertions(+), 16 deletions(-) diff --git a/CMakePresets.json b/CMakePresets.json index 732c9f7..3996cac 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -28,6 +28,7 @@ "CMAKE_EXE_LINKER_FLAGS": "-fsanitize=address,undefined -Wl,--gc-sections" }, "environment": { + "CHECKSUM_GCC_WARNINGS": "", "CHECKSUM_EXTRA_CFLAGS": "-fsanitize=address,undefined -fno-sanitize-recover=all -g -O1", "CHECKSUM_EXTRA_CXXFLAGS": "-fsanitize=address,undefined -fno-sanitize-recover=all -g -O1" } diff --git a/cmake/common_presets.json b/cmake/common_presets.json index 6b32b40..09e32f2 100644 --- a/cmake/common_presets.json +++ b/cmake/common_presets.json @@ -21,8 +21,8 @@ "hidden": true, "inherits": "common", "cacheVariables": { - "CMAKE_C_FLAGS_DEBUG": "-g -D_GLIBCXX_ASSERTIONS -fstack-protector-strong -ftrivial-auto-var-init=pattern", - "CMAKE_CXX_FLAGS_DEBUG": "-g -D_GLIBCXX_ASSERTIONS -fstack-protector-strong -ftrivial-auto-var-init=pattern" + "CMAKE_C_FLAGS_DEBUG": "-g -Og -D_GLIBCXX_ASSERTIONS -fstack-protector-strong -ftrivial-auto-var-init=pattern", + "CMAKE_CXX_FLAGS_DEBUG": "-g -Og -D_GLIBCXX_ASSERTIONS -fstack-protector-strong -ftrivial-auto-var-init=pattern" }, "environment": { "CHECKSUM_WARNINGS": "-Wall -Wextra -Wpedantic -Wunused-parameter -Winit-self -Wcast-align -Wconversion -Wnull-dereference -Wsign-conversion -Wno-psabi $env{CHECKSUM_GCC_WARNINGS}", diff --git a/cmake/emulator_presets.json b/cmake/emulator_presets.json index 91446e4..1d1f32c 100644 --- a/cmake/emulator_presets.json +++ b/cmake/emulator_presets.json @@ -63,11 +63,11 @@ { "name": "cross-aarch64-pmull", "displayName": "AArch64 Linux in QEMU (PMULL and CRC32)", - "description": "AArch64 cross build with -march=armv8-a+crc+crypto: PMULL folding and CRC32 instructions (aarch64 header); tests run in QEMU", + "description": "AArch64 cross build with -march=armv8.2-a+crc+crypto+sha3: PMULL folding with EOR3 and CRC32 instructions (aarch64 header); tests run in QEMU", "inherits": "cross-aarch64-base", "environment": { - "CHECKSUM_EXTRA_CFLAGS": "-march=armv8-a+crc+crypto", - "CHECKSUM_EXTRA_CXXFLAGS": "-march=armv8-a+crc+crypto" + "CHECKSUM_EXTRA_CFLAGS": "-march=armv8.2-a+crc+crypto+sha3", + "CHECKSUM_EXTRA_CXXFLAGS": "-march=armv8.2-a+crc+crypto+sha3" } }, { @@ -113,8 +113,12 @@ { "name": "cross-arm-portable", "displayName": "32-bit Arm Linux in QEMU (no NEON)", - "description": "32-bit Arm (hard float) cross build with -mfpu=vfpv3-d16: portable CRC loops and the ldm + adcs Internet checksum kernel on a 32-bit target; tests run in QEMU. CHECKSUM_TEST_ARM_DSP enables the M-profile DSP kernel of Fletcher-16 and Adler-32, which QEMU user mode cannot run on an M-profile core", + "description": "32-bit Arm (hard float) cross build with -mfpu=vfpv3-d16: portable CRC loops and the ldm + adcs Internet checksum kernel on a 32-bit target; tests run in QEMU. CHECKSUM_TEST_ARM_DSP enables the M-profile DSP kernel of Fletcher-16 and Adler-32, which QEMU user mode cannot run on an M-profile core. Debug stays at -O0 here so that the inline assembly is built without optimization", "inherits": "cross-arm-base", + "cacheVariables": { + "CMAKE_C_FLAGS_DEBUG": "-g -O0 -D_GLIBCXX_ASSERTIONS -fstack-protector-strong -ftrivial-auto-var-init=pattern", + "CMAKE_CXX_FLAGS_DEBUG": "-g -O0 -D_GLIBCXX_ASSERTIONS -fstack-protector-strong -ftrivial-auto-var-init=pattern" + }, "environment": { "CHECKSUM_EXTRA_CFLAGS": "-mfpu=vfpv3-d16", "CHECKSUM_EXTRA_CXXFLAGS": "-mfpu=vfpv3-d16 -DCHECKSUM_TEST_ARM_DSP" diff --git a/cmake/x86_64_presets.json b/cmake/x86_64_presets.json index 39b85a8..8f5b01a 100644 --- a/cmake/x86_64_presets.json +++ b/cmake/x86_64_presets.json @@ -7,11 +7,11 @@ { "name": "x86_64-gcc-pclmul", "displayName": "x86-64 (GCC, PCLMULQDQ, SSE4.2 and AVX2 at compile time)", - "description": "Native Linux build using GCC with -mpclmul -msse4.2 -mavx2: CRC folding with PCLMULQDQ, the SSE4.2 crc32 instruction and the AVX2 Internet checksum kernel", + "description": "Native Linux build using GCC with -mpclmul -mvpclmulqdq -msse4.2 -mavx2: CRC folding with PCLMULQDQ and 256-byte VPCLMULQDQ, the SSE4.2 crc32 instruction and the AVX2 Internet checksum kernel", "inherits": "gcc", "environment": { - "CHECKSUM_EXTRA_CFLAGS": "-mpclmul -msse4.2 -mavx2", - "CHECKSUM_EXTRA_CXXFLAGS": "-mpclmul -msse4.2 -mavx2" + "CHECKSUM_EXTRA_CFLAGS": "-mpclmul -mvpclmulqdq -msse4.2 -mavx2", + "CHECKSUM_EXTRA_CXXFLAGS": "-mpclmul -mvpclmulqdq -msse4.2 -mavx2" } } ], diff --git a/doc/design/testing.md b/doc/design/testing.md index b6a398b..6060b0a 100644 --- a/doc/design/testing.md +++ b/doc/design/testing.md @@ -25,7 +25,8 @@ Run benchmarks and the full cross matrix only when the change needs them, filter Test presets build one configuration (Debug) and run `ctest` with 8 jobs; the negative compile tests share a resource lock because each runs the build tool on the same tree. Keep a whole run fast: about 2 s of tests natively -and 20 s in QEMU user mode. +and 20 s in QEMU user mode. Debug test builds use `-Og`; `cross-arm-portable` keeps `-O0` so the inline assembly is built +without optimization. ## Coverage expectations diff --git a/tests/unit_tests/ut_adler32.cpp b/tests/unit_tests/ut_adler32.cpp index 5dfefeb..72eca40 100644 --- a/tests/unit_tests/ut_adler32.cpp +++ b/tests/unit_tests/ut_adler32.cpp @@ -50,10 +50,10 @@ TEST(adler32, published_examples) { EXPECT_EQ(adler32_compute("123456789"sv), 0x091E01DEU); } -// All lengths past the kernel thresholds and a few kernel blocks, at every alignment of a vector. +// All lengths past the kernel thresholds and a few kernel blocks, at every alignment of a word and two vector misalignments. TEST(adler32, matches_model) { auto const data = random_bytes(2100 + 16, 32); - for(std::size_t offset = 0; offset < 16; ++offset) { + for(std::size_t const offset : {0U, 1U, 2U, 3U, 7U, 15U}) { for(std::size_t size = 0; size <= 2100; ++size) { auto const message = std::span(data).subspan(offset, size); ASSERT_EQ(adler32_compute(message), reference(message)) << "offset " << offset << ", size " << size; @@ -64,7 +64,7 @@ TEST(adler32, matches_model) { // The largest bytes from the largest canonical sums, over many deferred reductions of 5'552 bytes on 32-bit targets. TEST(adler32, all_ones) { adler32_state const largest{.sum1 = 65520, .sum2 = 65520}; - for(std::size_t const size : {(std::size_t{6} << 20), (std::size_t{6} << 20) + 1, (std::size_t{6} << 20) + 7, std::size_t{5552 * 1000}}) { + for(std::size_t const size : {(std::size_t{600} << 10), (std::size_t{600} << 10) + 1, (std::size_t{600} << 10) + 7, std::size_t{5552 * 120}}) { std::vector const data(size, std::byte{0xFF}); ASSERT_EQ(adler32_compute(data), reference(data)) << "size " << size; ASSERT_EQ(adler32_finalize(adler32_update(largest, data)), reference(data, 65520, 65520)) << "size " << size; diff --git a/tests/unit_tests/ut_fletcher.cpp b/tests/unit_tests/ut_fletcher.cpp index 63fca86..1b39900 100644 --- a/tests/unit_tests/ut_fletcher.cpp +++ b/tests/unit_tests/ut_fletcher.cpp @@ -89,11 +89,11 @@ TEST(fletcher_vectors, aliases) { EXPECT_EQ(fletcher64_compute("123456789"sv), fletcher_compute<64>("123456789"sv)); } -// All lengths past the kernel thresholds and a few kernel blocks, at every alignment of a vector. +// All lengths past the kernel thresholds and a few kernel blocks, at every alignment of a word and two vector misalignments. TYPED_TEST(fletcher, matches_model) { constexpr unsigned width = TypeParam::value; auto const data = random_bytes(2100 + 16, width); - for(std::size_t offset = 0; offset < 16; ++offset) { + for(std::size_t const offset : {0U, 1U, 2U, 3U, 7U, 15U}) { for(std::size_t size = 0; size <= 2100; ++size) { auto const message = std::span(data).subspan(offset, size); ASSERT_EQ(fletcher_compute(message), reference(message)) << "offset " << offset << ", size " << size; @@ -104,7 +104,7 @@ TYPED_TEST(fletcher, matches_model) { // The largest blocks over several deferred reductions; the tail sizes leave an unfinished block. TYPED_TEST(fletcher, all_ones) { constexpr unsigned width = TypeParam::value; - for(std::size_t const size : {(std::size_t{4} << 20), (std::size_t{4} << 20) + 1, (std::size_t{4} << 20) + 3}) { + for(std::size_t const size : {(std::size_t{600} << 10), (std::size_t{600} << 10) + 1, (std::size_t{600} << 10) + 3}) { std::vector const data(size, std::byte{0xFF}); ASSERT_EQ(fletcher_compute(data), reference(data)) << "size " << size; } From 882184322dcd6075adc3a1d0cdac1dfa891ce016 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:14:30 +0200 Subject: [PATCH 48/64] perf(crc): x86 wide fold reduces its last 8 blocks in parallel The VPCLMULQDQ loop folds the 8 blocks left after its 256- and 128-byte steps onto the last one with one constant pair per distance (by_seven to by_two, new in folding_constants), and a 64-byte remainder with one more 256-bit step, instead of three dependent 128-bit folds. The Barrett reduction stays in vector registers, and the wide loop is inlined into the non-inlined long-input callers instead of a second call. --- src/include/checksum/crc.hpp | 19 ++++-- .../checksum_private/x86_64/crc.hpp | 62 ++++++++++++------- tests/unit_tests/ut_crc_engine.cpp | 6 +- 3 files changed, 56 insertions(+), 31 deletions(-) diff --git a/src/include/checksum/crc.hpp b/src/include/checksum/crc.hpp index 67b177d..a5239c0 100644 --- a/src/include/checksum/crc.hpp +++ b/src/include/checksum/crc.hpp @@ -257,11 +257,17 @@ using folding_pair = std::array; // Carry-less multiplication constants of a parameter set (see make_folding_constants()). Aligned so that each pair is one aligned vector // load. struct alignas(16) folding_constants { - folding_pair by_sixteen; // fold over 16 blocks (2048 bits) - folding_pair by_eight; // fold over 8 blocks - folding_pair by_four; // fold over 4 blocks + folding_pair by_sixteen; // fold over 16 blocks (2048 bits) + folding_pair by_eight; // fold over 8 blocks + // Over 7 down to 2 blocks, in descending order: two adjacent pairs fold two adjacent blocks onto the same block. + folding_pair by_seven; + folding_pair by_six; + folding_pair by_five; + folding_pair by_four; + folding_pair by_three; + folding_pair by_two; folding_pair by_one; // fold over 1 block (128 bits) - std::uint64_t quotient; // Barrett constant floor(x^128 / Q) without its x^64 term + std::uint64_t quotient; // Barrett constant floor(x^128 / Q) without its x^64 term; with polynomial, one aligned pair std::uint64_t polynomial; // Q without its x^64 term }; @@ -546,7 +552,12 @@ constexpr folding_constants make_folding_constants(crc_parameters const ¶met }; return {.by_sixteen = fold_pair(16 * block_bits), .by_eight = fold_pair(8 * block_bits), + .by_seven = fold_pair(7 * block_bits), + .by_six = fold_pair(6 * block_bits), + .by_five = fold_pair(5 * block_bits), .by_four = fold_pair(4 * block_bits), + .by_three = fold_pair(3 * block_bits), + .by_two = fold_pair(2 * block_bits), .by_one = fold_pair(block_bits), .quotient = parameters.reflect_input ? reflect(quotient, register_width) : quotient, .polynomial = parameters.reflect_input ? reflect(polynomial, register_width) : polynomial}; diff --git a/src/include_private/checksum_private/x86_64/crc.hpp b/src/include_private/checksum_private/x86_64/crc.hpp index be2d61a..a326540 100644 --- a/src/include_private/checksum_private/x86_64/crc.hpp +++ b/src/include_private/checksum_private/x86_64/crc.hpp @@ -79,8 +79,8 @@ struct pclmul_kernel { template static std::uint64_t reduce(vector accumulator, folding_constants const &constants) noexcept; #if defined(__VPCLMULQDQ__) && defined(__AVX2__) - // Eight 256-bit accumulators (blocks 2j, 2j + 1 in accumulator j) fold 256 bytes per step, then four fold 128; the - // last 64 bytes go to fold_four_with(). + // Eight 256-bit accumulators (blocks 2j, 2j + 1 in accumulator j) fold 256 bytes per step, then four fold 128 and + // 64; their 8 blocks fold onto the last one in parallel, and fold_tail_with() takes the last 0..63 bytes. template static vector fold_wide(folding_constants const &constants, std::uint64_t remainder, std::span data) noexcept; #endif @@ -191,29 +191,32 @@ template [[gnu::always_inline]] inline std::uint64_t pclmul_kernel::l template [[gnu::always_inline]] inline std::uint64_t pclmul_kernel::reduce(vector accumulator, folding_constants const &constants) noexcept { - constexpr unsigned top_bit = 63; - std::uint64_t const low = lane<0>(accumulator); - std::uint64_t const high = lane<1>(accumulator); + // Stays in vector registers: each move between them and general registers costs about 3 cycles of latency. + vector const by_one = pair(constants.by_one); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): aligned load of the quotient and the polynomial. + vector const barrett = _mm_load_si128(reinterpret_cast(&constants.quotient)); if constexpr(Reflected) { - vector const folded = multiply(low, constants.by_one[1]); - std::uint64_t const value_high = lane<0>(folded) ^ high; - std::uint64_t const quotient = value_high ^ (lane<0>(multiply(value_high, constants.quotient)) << 1U); - vector const product = multiply(quotient, constants.polynomial); - return lane<1>(folded) ^ (lane<0>(product) >> top_bit) ^ (lane<1>(product) << 1U); + // Low lane: the high half plus the low half folded over 64 bits; high lane: the rest of the fold. + vector const value = _mm_xor_si128(_mm_clmulepi64_si128(accumulator, by_one, 0x10), _mm_srli_si128(accumulator, 8)); + vector const quotient = _mm_xor_si128(value, _mm_slli_epi64(_mm_clmulepi64_si128(value, barrett, 0x00), 1)); + vector const product = _mm_clmulepi64_si128(quotient, barrett, 0x10); + // High lane of the 128-bit product shifted left by one. + vector const shifted = _mm_xor_si128(_mm_slli_epi64(product, 1), _mm_srli_epi64(_mm_slli_si128(product, 8), 63)); + return lane<1>(_mm_xor_si128(value, shifted)); } else { - vector const folded = multiply(high, constants.by_one[0]); - std::uint64_t const value_high = lane<1>(folded) ^ low; - std::uint64_t const quotient = value_high ^ lane<1>(multiply(value_high, constants.quotient)); - return lane<0>(folded) ^ lane<0>(multiply(quotient, constants.polynomial)); + // High lane: the low half plus the high half folded over 64 bits; low lane: the rest of the fold. + vector const value = _mm_xor_si128(_mm_clmulepi64_si128(accumulator, by_one, 0x01), _mm_slli_si128(accumulator, 8)); + vector const quotient = _mm_xor_si128(value, _mm_clmulepi64_si128(value, barrett, 0x01)); + return lane<0>(_mm_xor_si128(value, _mm_clmulepi64_si128(quotient, barrett, 0x11))); } } #if defined(__VPCLMULQDQ__) && defined(__AVX2__) -// Not inlined: long inputs pay one call, and the eight 256-bit accumulators do not spill onto the stack frame of the -// short-input callers. +// Inlined only into the non-inlined long-input callers (fold_long_message(), fold_long_crc32()): a second call cost +// up to 10 % at 256 bytes. template -[[gnu::noinline]] inline pclmul_kernel::vector pclmul_kernel::fold_wide(folding_constants const &constants, std::uint64_t remainder, - std::span data) noexcept { +[[gnu::always_inline]] inline pclmul_kernel::vector pclmul_kernel::fold_wide(folding_constants const &constants, std::uint64_t remainder, + std::span data) noexcept { constexpr std::size_t half = 32; // bytes per 256-bit accumulator constexpr std::size_t eight = 256; // bytes per iteration of eight accumulators constexpr std::size_t four = 128; // bytes per iteration of four @@ -250,12 +253,23 @@ template for(; data.size() - consumed >= four; consumed += four) { unrolled<4>([&](auto index) { pairs[index] = fold_two(pairs[index], by_eight, load_two(data.subspan(consumed + (index * half)))); }); } - // Blocks 0..3 fold over four blocks onto blocks 4..7. - __m256i const low = fold_two(pairs[0], by_four, pairs[2]); - __m256i const high = fold_two(pairs[1], by_four, pairs[3]); - return fold_four_with( - {_mm256_castsi256_si128(low), _mm256_extracti128_si256(low, 1), _mm256_castsi256_si128(high), _mm256_extracti128_si256(high, 1)}, constants, - data.subspan(consumed), data.last(folding_block_size)); + if(data.size() - consumed >= folding_four_blocks_size) { + // Blocks 0..3 fold over four blocks onto blocks 4..7, followed by blocks 8..11. + pairs = {fold_two(pairs[0], by_four, pairs[2]), fold_two(pairs[1], by_four, pairs[3]), load_two(data.subspan(consumed)), + load_two(data.subspan(consumed + half))}; + consumed += folding_four_blocks_size; + } + // Blocks 0..5 fold onto block 7 with the constants of their own distances, in parallel; block 6 folds over one. + auto const distances = [](folding_pair const &longer) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): unaligned load of two adjacent constant pairs. + return _mm256_loadu_si256(reinterpret_cast<__m256i const *>(longer.data())); + }; + __m256i const block_7 = _mm256_blend_epi32(pairs[3], _mm256_setzero_si256(), 0x0F); + __m256i const folded = fold_two(pairs[0], distances(constants.by_seven), + fold_two(pairs[1], distances(constants.by_five), fold_two(pairs[2], distances(constants.by_three), block_7))); + __m128i const accumulator = fold(_mm256_castsi256_si128(pairs[3]), pair(constants.by_one), + _mm_xor_si128(_mm256_castsi256_si128(folded), _mm256_extracti128_si256(folded, 1))); + return fold_tail_with(accumulator, constants, data.subspan(consumed), data.last(folding_block_size)); } #endif diff --git a/tests/unit_tests/ut_crc_engine.cpp b/tests/unit_tests/ut_crc_engine.cpp index fa0917f..5bba2e7 100644 --- a/tests/unit_tests/ut_crc_engine.cpp +++ b/tests/unit_tests/ut_crc_engine.cpp @@ -63,10 +63,10 @@ static_assert(engine_size_is>(0)); static_assert(engine_size_is>(16 * sizeof(std::uint32_t))); static_assert(engine_size_is>(1024)); static_assert(engine_size_is>(2048)); -// The slicing-by-8 and braided tables also hold 10 x 8 bytes of folding constants. The braided table is the 8 +// The slicing-by-8 and braided tables also hold 20 x 8 bytes of folding constants. The braided table is the 8 // slicing-by-8 slices plus 8 braid slices. -static_assert(engine_size_is>(16384 + 80)); -static_assert(engine_size_is>(32768 + 80)); +static_assert(engine_size_is>(16384 + 160)); +static_assert(engine_size_is>(32768 + 160)); static_assert(!std::is_default_constructible_v>); static_assert(std::is_trivially_copyable_v> && std::is_copy_assignable_v>); From 7d0f50aa2faa38aaa94823133d8f66f92a694c1d Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:11:16 +0200 Subject: [PATCH 49/64] perf(crc): straight-line 256-byte path, CRC-32C ends with crc32 instructions Branches that a 256-byte input does not take are marked unlikely, so that path runs without taken jumps. CRC-32C folds its 8 blocks onto the last two and hands those 32 bytes and the 0..63 remaining ones to the crc32 instruction. CRC-32C at 256 bytes: 0.84 to 0.93 of ISA-L. --- .../checksum_private/x86_64/crc.hpp | 120 +++++++++++++----- 1 file changed, 87 insertions(+), 33 deletions(-) diff --git a/src/include_private/checksum_private/x86_64/crc.hpp b/src/include_private/checksum_private/x86_64/crc.hpp index a326540..65358b5 100644 --- a/src/include_private/checksum_private/x86_64/crc.hpp +++ b/src/include_private/checksum_private/x86_64/crc.hpp @@ -79,8 +79,19 @@ struct pclmul_kernel { template static std::uint64_t reduce(vector accumulator, folding_constants const &constants) noexcept; #if defined(__VPCLMULQDQ__) && defined(__AVX2__) + // Two blocks: byte 0 lowest if reflected, each block byte-reversed otherwise. + template static __m256i load_two(std::span data) noexcept; + + // fold() of two blocks with the constants of each lane. + static __m256i fold_two(__m256i accumulators, __m256i constants, __m256i next) noexcept; + // Eight 256-bit accumulators (blocks 2j, 2j + 1 in accumulator j) fold 256 bytes per step, then four fold 128 and - // 64; their 8 blocks fold onto the last one in parallel, and fold_tail_with() takes the last 0..63 bytes. + // 64. Returns 8 blocks (2 per vector) with fewer than 64 bytes left after them; consumed: the bytes they cover. + template + static std::array<__m256i, 4> fold_wide_blocks(folding_constants const &constants, std::uint64_t remainder, std::span data, + std::size_t &consumed) noexcept; + + // fold_wide_blocks(), its 8 blocks folded onto the last one in parallel, then fold_tail_with() on the last 0..63 bytes. template static vector fold_wide(folding_constants const &constants, std::uint64_t remainder, std::span data) noexcept; #endif @@ -212,53 +223,71 @@ template } #if defined(__VPCLMULQDQ__) && defined(__AVX2__) +template [[gnu::always_inline]] inline __m256i pclmul_kernel::load_two(std::span data) noexcept { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): unaligned vector load, the intrinsic's interface. + __m256i const blocks = _mm256_loadu_si256(reinterpret_cast<__m256i const *>(data.data())); + if constexpr(Reflected) { + return blocks; + } else { + __m128i const reverse = _mm_setr_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + return _mm256_shuffle_epi8(blocks, _mm256_broadcastsi128_si256(reverse)); + } +} + +[[gnu::always_inline]] inline __m256i pclmul_kernel::fold_two(__m256i accumulators, __m256i constants, __m256i next) noexcept { + return _mm256_xor_si256( + _mm256_xor_si256(_mm256_clmulepi64_epi128(accumulators, constants, 0x00), _mm256_clmulepi64_epi128(accumulators, constants, 0x11)), next); +} + // Inlined only into the non-inlined long-input callers (fold_long_message(), fold_long_crc32()): a second call cost // up to 10 % at 256 bytes. template -[[gnu::always_inline]] inline pclmul_kernel::vector pclmul_kernel::fold_wide(folding_constants const &constants, std::uint64_t remainder, - std::span data) noexcept { +[[gnu::always_inline]] inline std::array<__m256i, 4> pclmul_kernel::fold_wide_blocks(folding_constants const &constants, std::uint64_t remainder, + std::span data, + std::size_t &consumed) noexcept { constexpr std::size_t half = 32; // bytes per 256-bit accumulator constexpr std::size_t eight = 256; // bytes per iteration of eight accumulators constexpr std::size_t four = 128; // bytes per iteration of four - auto const load_two = [](std::span bytes) { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): unaligned vector load, the intrinsic's interface. - __m256i const blocks = _mm256_loadu_si256(reinterpret_cast<__m256i const *>(bytes.data())); - if constexpr(Reflected) { - return blocks; - } else { - __m128i const reverse = _mm_setr_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); - return _mm256_shuffle_epi8(blocks, _mm256_broadcastsi128_si256(reverse)); - } - }; - auto const fold_two = [](__m256i accumulator, __m256i distance, __m256i next) { - return _mm256_xor_si256( - _mm256_xor_si256(_mm256_clmulepi64_epi128(accumulator, distance, 0x00), _mm256_clmulepi64_epi128(accumulator, distance, 0x11)), next); - }; __m256i const by_eight = _mm256_broadcastsi128_si256(pair(constants.by_eight)); - __m256i const by_four = _mm256_broadcastsi128_si256(pair(constants.by_four)); - __m256i const first = _mm256_zextsi128_si256(state(remainder)); static_assert(wide_minimum_size == eight, "the eight-accumulator loop runs at least once"); __m256i const by_sixteen = _mm256_broadcastsi128_si256(pair(constants.by_sixteen)); std::array<__m256i, 8> accumulators{}; - unrolled<8>([&](auto index) { accumulators[index] = load_two(data.subspan(index * half)); }); - accumulators[0] = _mm256_xor_si256(accumulators[0], first); - std::size_t consumed = eight; - for(; data.size() - consumed >= eight; consumed += eight) { - unrolled<8>( - [&](auto index) { accumulators[index] = fold_two(accumulators[index], by_sixteen, load_two(data.subspan(consumed + (index * half)))); }); + unrolled<8>([&](auto index) { accumulators[index] = load_two(data.subspan(index * half)); }); + accumulators[0] = _mm256_xor_si256(accumulators[0], _mm256_zextsi128_si256(state(remainder))); + consumed = eight; + // Branches that 256 bytes do not take are marked unlikely: each taken branch on that path cost about 2 %. + if(data.size() - consumed >= eight) [[unlikely]] { + do { + unrolled<8>([&](auto index) { + accumulators[index] = fold_two(accumulators[index], by_sixteen, load_two(data.subspan(consumed + (index * half)))); + }); + consumed += eight; + } while(data.size() - consumed >= eight); } // Blocks 2j, 2j + 1 fold over eight blocks onto blocks 2j + 8, 2j + 9. std::array<__m256i, 4> pairs{}; unrolled<4>([&](auto index) { pairs[index] = fold_two(accumulators[index], by_eight, accumulators[index + 4]); }); - for(; data.size() - consumed >= four; consumed += four) { - unrolled<4>([&](auto index) { pairs[index] = fold_two(pairs[index], by_eight, load_two(data.subspan(consumed + (index * half)))); }); + if(data.size() - consumed >= four) [[unlikely]] { + do { + unrolled<4>([&](auto index) { pairs[index] = fold_two(pairs[index], by_eight, load_two(data.subspan(consumed + (index * half)))); }); + consumed += four; + } while(data.size() - consumed >= four); } - if(data.size() - consumed >= folding_four_blocks_size) { + if(data.size() - consumed >= folding_four_blocks_size) [[unlikely]] { // Blocks 0..3 fold over four blocks onto blocks 4..7, followed by blocks 8..11. - pairs = {fold_two(pairs[0], by_four, pairs[2]), fold_two(pairs[1], by_four, pairs[3]), load_two(data.subspan(consumed)), - load_two(data.subspan(consumed + half))}; + __m256i const by_four = _mm256_broadcastsi128_si256(pair(constants.by_four)); + pairs = {fold_two(pairs[0], by_four, pairs[2]), fold_two(pairs[1], by_four, pairs[3]), load_two(data.subspan(consumed)), + load_two(data.subspan(consumed + half))}; consumed += folding_four_blocks_size; } + return pairs; +} + +template +[[gnu::always_inline]] inline pclmul_kernel::vector pclmul_kernel::fold_wide(folding_constants const &constants, std::uint64_t remainder, + std::span data) noexcept { + std::size_t consumed = 0; + std::array<__m256i, 4> const pairs = fold_wide_blocks(constants, remainder, data, consumed); // Blocks 0..5 fold onto block 7 with the constants of their own distances, in parallel; block 6 folds over one. auto const distances = [](folding_pair const &longer) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): unaligned load of two adjacent constant pairs. @@ -267,9 +296,12 @@ template __m256i const block_7 = _mm256_blend_epi32(pairs[3], _mm256_setzero_si256(), 0x0F); __m256i const folded = fold_two(pairs[0], distances(constants.by_seven), fold_two(pairs[1], distances(constants.by_five), fold_two(pairs[2], distances(constants.by_three), block_7))); - __m128i const accumulator = fold(_mm256_castsi256_si128(pairs[3]), pair(constants.by_one), - _mm_xor_si128(_mm256_castsi256_si128(folded), _mm256_extracti128_si256(folded, 1))); - return fold_tail_with(accumulator, constants, data.subspan(consumed), data.last(folding_block_size)); + vector const accumulator = fold(_mm256_castsi256_si128(pairs[3]), pair(constants.by_one), + _mm_xor_si128(_mm256_castsi256_si128(folded), _mm256_extracti128_si256(folded, 1))); + if(consumed != data.size()) [[unlikely]] { + return fold_tail_with(accumulator, constants, data.subspan(consumed), data.last(folding_block_size)); + } + return accumulator; } #endif @@ -283,6 +315,28 @@ template template <> [[gnu::always_inline]] inline std::uint32_t fold_crc32(folding_constants const &constants, std::uint32_t remainder, std::span data) noexcept { +#if defined(__VPCLMULQDQ__) && defined(__AVX2__) + if(data.size() >= wide_folding_minimum_size) { + // Blocks 0..5 fold onto blocks 6 and 7 in parallel; crc32 instructions take the 32 bytes and the last 0..63 bytes: + // 20 % faster at 256 bytes than folding onto one block. + std::size_t consumed = 0; + std::array<__m256i, 4> const pairs = pclmul_kernel::fold_wide_blocks(constants, remainder, data, consumed); + auto const both = [&](folding_pair const &distance) { return _mm256_broadcastsi128_si256(pclmul_kernel::pair(distance)); }; + __m256i const last_two = pclmul_kernel::fold_two( + pairs[0], both(constants.by_six), + pclmul_kernel::fold_two(pairs[1], both(constants.by_four), pclmul_kernel::fold_two(pairs[2], both(constants.by_two), pairs[3]))); + __m128i const low = _mm256_castsi256_si128(last_two); + __m128i const high = _mm256_extracti128_si256(last_two, 1); + std::uint32_t crc = crc32_word(0, pclmul_kernel::lane<0>(low)); + crc = crc32_word(crc, pclmul_kernel::lane<1>(low)); + crc = crc32_word(crc, pclmul_kernel::lane<0>(high)); + crc = crc32_word(crc, pclmul_kernel::lane<1>(high)); + if(consumed != data.size()) [[unlikely]] { + crc = crc32_instructions(crc, data.subspan(consumed)); + } + return crc; + } +#endif return fold_crc32_with(constants, remainder, data); } #endif From bfee6b75764b42ea9d687e3812636c863ca38aff Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:20:35 +0200 Subject: [PATCH 50/64] docs(crc): x86 256-byte folding, 160 B of constants, ISA-L comparison Re-measured accelerated sliced rows (GCC 16, Core Ultra 7 155H), engine sizes and footprints with the larger folding constants, the decisions behind the single-step fold, and comments that state only measured gains. --- doc/crc.md | 24 ++++++++++--------- doc/design/acceleration.md | 21 +++++++++++++--- .../checksum_private/x86_64/crc.hpp | 8 +++---- 3 files changed, 35 insertions(+), 18 deletions(-) diff --git a/doc/crc.md b/doc/crc.md index 6912643..a93fdb8 100644 --- a/doc/crc.md +++ b/doc/crc.md @@ -168,10 +168,10 @@ results. | `crc_lut_none` (default) | 11 / 16 / 32 / 64 B | Bitwise, no table. Smallest code and data. | | `crc_lut_nibble` | 27 / 48 / 96 / 192 B | 16-entry table, two lookups per byte. | | `crc_lut_byte` | 267 / 528 / 1056 / 2112 B | 256-entry table, one lookup per byte. | -| `crc_lut_sliced` | 2.1 / 4.1 / 8.1 / 16.1 KiB | Slicing-by-8: eight 256-entry tables, one 8-byte word per step. CPU acceleration (section 7). | -| `crc_lut_braided` | 4.1 / 8.1 / 16.1 / 32.1 KiB | Slicing-by-8 plus 8 braid tables: five interleaved streams of 8-byte words from 128 B on. CPU acceleration (section 7). | +| `crc_lut_sliced` | 2.2 / 4.2 / 8.2 / 16.2 KiB | Slicing-by-8: eight 256-entry tables, one 8-byte word per step. CPU acceleration (section 7). | +| `crc_lut_braided` | 4.2 / 8.2 / 16.2 / 32.2 KiB | Slicing-by-8 plus 8 braid tables: five interleaved streams of 8-byte words from 128 B on. CPU acceleration (section 7). | -Sizes are `sizeof(crc_engine)` on a 64-bit host. The sliced and braided engines include 80 B of folding constants +Sizes are `sizeof(crc_engine)` on a 64-bit host. The sliced and braided engines include 160 B of folding constants for the CPU kernels. Large engines belong in static storage (`crc_engine_for`, or a `static`/global object), not on an MCU stack. @@ -243,12 +243,14 @@ GCC 16. Accelerated = `-march=native` (PCLMULQDQ, VPCLMULQDQ, AVX2, SSE4.2). MB/ | CRC | none | nibble | byte | sliced, portable | braided, portable | sliced, accelerated | | --- | --- | --- | --- | --- | --- | --- | -| CRC-8/SMBUS | 180 | 252 | 797 | 3814 / 3540 / 3091 / 3019 | 3705 / 4940 / 5976 / 6045 | 8591 / 39081 / 70047 / 73570 | -| CRC-16/XMODEM | 176 | 245 | 781 | 4099 / 3012 / 2579 / 2589 | 3664 / 4703 / 5884 / 6009 | 8525 / 39037 / 70187 / 73350 | -| CRC-32/ISO-HDLC | 137 | 289 | 673 | 4663 / 3657 / 2923 / 2896 | 4332 / 5345 / 6685 / 6556 | 7906 / 40503 / 71581 / 74656 | -| CRC-64/XZ | 137 | 287 | 661 | 4758 / 2761 / 2501 / 2424 | 4456 / 5192 / 6710 / 6485 | 8395 / 41592 / 71870 / 74835 | +| CRC-8/SMBUS | 180 | 252 | 797 | 3814 / 3540 / 3091 / 3019 | 3705 / 4940 / 5976 / 6045 | 10564 / 49017 / 71769 / 74200 | +| CRC-16/XMODEM | 176 | 245 | 781 | 4099 / 3012 / 2579 / 2589 | 3664 / 4703 / 5884 / 6009 | 10573 / 48774 / 72463 / 71670 | +| CRC-32/ISO-HDLC | 137 | 289 | 673 | 4663 / 3657 / 2923 / 2896 | 4332 / 5345 / 6685 / 6556 | 9754 / 52967 / 74320 / 75889 | +| CRC-64/XZ | 137 | 287 | 661 | 4758 / 2761 / 2501 / 2424 | 4456 / 5192 / 6710 / 6485 | 10291 / 53467 / 73653 / 75693 | The accelerated `crc_lut_braided` is within 6 % of the accelerated `crc_lut_sliced`. Clang gives the same picture. +Against Intel ISA-L (hand-written AVX2 VPCLMULQDQ assembly), the accelerated CRC-32, CRC-32C and CRC-64/XZ run at +0.89-1.45× its speed from 20 B to 1 MiB with GCC 16, and 0.95-1.01× at 256 B. ### 8.2 Cortex-A72 (Raspberry Pi 4, 1.5 GHz) @@ -283,10 +285,10 @@ code added over an empty program / engine in `.rodata`, bytes. | CRC | none | nibble | byte | sliced | braided | | --- | --- | --- | --- | --- | --- | -| CRC-32/ISO-HDLC | 100 / 32 | 104 / 96 | 80 / 1056 | 252 / 8320 | 1116 / 16512 | -| CRC-16/XMODEM | 104 / 16 | 104 / 48 | 76 / 528 | 252 / 4208 | 1212 / 8304 | -| CRC-8/SMBUS | 101 / 11 | 101 / 27 | 97 / 267 | 252 / 2160 | 1068 / 4208 | -| CRC-64/XZ | 116 / 64 | 140 / 192 | 100 / 2112 | 380 / 16528 | 1868 / 32912 | +| CRC-32/ISO-HDLC | 100 / 32 | 104 / 96 | 80 / 1056 | 252 / 8400 | 1116 / 16592 | +| CRC-16/XMODEM | 104 / 16 | 104 / 48 | 76 / 528 | 252 / 4288 | 1212 / 8384 | +| CRC-8/SMBUS | 101 / 11 | 101 / 27 | 97 / 267 | 252 / 2240 | 1068 / 4288 | +| CRC-64/XZ | 116 / 64 | 140 / 192 | 100 / 2112 | 380 / 16608 | 1868 / 32992 | ### 8.4 Cortex-M4 with a CRC peripheral (STM32L4A6, 80 MHz) diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index 6181cda..5117ce8 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -48,10 +48,15 @@ user guides ([CRC](../crc.md#8-performance), [Internet checksum](../internet.md# Kernel>` implements it once over `pclmul_kernel`, `pmull_kernel` and `clmul_kernel`. - **One modulus for every width:** a CRC of width W runs in a 64-bit register modulo Q = x^(64−W) · (x^W + polynomial), so one kernel per bit order covers widths 1..64 and every register type. The - 80 bytes of constants live in the slicing-by-8 and braided tables in every build. + 160 bytes of constants live in the slicing-by-8 and braided tables in every build. +- **Wide x86 loop** (VPCLMULQDQ, from 256 bytes): eight 256-bit accumulators over 256-byte steps, then four over + 128 bytes and one 64-byte step. Like Intel ISA-L, it then folds the 8 remaining blocks onto the last one in a + single step, each block with the constants of its own distance (`by_seven` to `by_one`), instead of a chain of + folds over one block. - **CRC instructions** run for CRC-32 and CRC-32C with reflected input in a 32-bit register, whatever the initial value and final XOR. On x86-64, CRC-32C inputs from 25 bytes fold with PCLMULQDQ and reduce their last 128 bits - with two `crc32` instructions. + with two `crc32` instructions; from 256 bytes the wide loop leaves two blocks, and `crc32` takes those 32 bytes + and the last 0..63 message bytes. - `crc_lut_braided` runs the `crc_lut_sliced` path wherever a kernel applies. Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cortex-A72; MCU: Cortex-M4): @@ -60,7 +65,17 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cor - Kernel inlined into each of the 8 loops (register type × bit order): one shared copy per bit order was up to 31 % (GCC) and 43 % (Clang) slower below 256 B, for 2.7-5.5 KB of code saved. - The wide x86 loop sits behind one non-inlined call: inlined, it gave every caller a stack frame, about 20 % - slower at 16-64 B. + slower at 16-64 B. It is inlined into that callee, one copy per register type and bit order: a second call cost + 8-15 % at 256 B; one shared copy per bit order saved 10 KB but was 9 % slower at 256 B. +- The x86 Barrett reduction stays in vector registers: moving the lanes to general registers and back cost about + 3 cycles per move, and keeping them in vector registers made 16-256 B 10-45 % faster. +- Branches that a 256-byte input does not take are marked unlikely, so that path has no taken jumps: CRC-32C at + 256 B went from 0.84 to 0.93 of ISA-L, measured together with its two-block ending (four `crc32` instructions + instead of a fold over one block and two). CRC-32 and CRC-64/XZ were unchanged. +- Tried at 256 B without gain: starting with four accumulators as ISA-L does (7 % slower), folding all 16 blocks in + one parallel step (5-10 % slower, 128 more bytes of constants), 64-byte alignment of the constants (within 2 %). +- Compared with Intel ISA-L's AVX2 kernels (GCC 16 `-O2 -march=native`): 1.01× (CRC-32), 0.95× (CRC-32C) and + 0.96× (CRC-64/XZ) at 256 B, against 0.71-0.78× before the single-step fold. - Each table source has its own copy of the loops it reuses (internal linkage): equal or up to 20 % faster than calling across sources. - Portable braided loop from 128 bytes, where it overtakes slicing-by-8. diff --git a/src/include_private/checksum_private/x86_64/crc.hpp b/src/include_private/checksum_private/x86_64/crc.hpp index 65358b5..2e8248d 100644 --- a/src/include_private/checksum_private/x86_64/crc.hpp +++ b/src/include_private/checksum_private/x86_64/crc.hpp @@ -240,7 +240,7 @@ template [[gnu::always_inline]] inline __m256i pclmul_kernel::l } // Inlined only into the non-inlined long-input callers (fold_long_message(), fold_long_crc32()): a second call cost -// up to 10 % at 256 bytes. +// 8-15 % at 256 bytes. template [[gnu::always_inline]] inline std::array<__m256i, 4> pclmul_kernel::fold_wide_blocks(folding_constants const &constants, std::uint64_t remainder, std::span data, @@ -255,7 +255,7 @@ template unrolled<8>([&](auto index) { accumulators[index] = load_two(data.subspan(index * half)); }); accumulators[0] = _mm256_xor_si256(accumulators[0], _mm256_zextsi128_si256(state(remainder))); consumed = eight; - // Branches that 256 bytes do not take are marked unlikely: each taken branch on that path cost about 2 %. + // Branches that 256 bytes do not take are marked unlikely, so that path runs without taken jumps. if(data.size() - consumed >= eight) [[unlikely]] { do { unrolled<8>([&](auto index) { @@ -317,8 +317,8 @@ template <> std::span data) noexcept { #if defined(__VPCLMULQDQ__) && defined(__AVX2__) if(data.size() >= wide_folding_minimum_size) { - // Blocks 0..5 fold onto blocks 6 and 7 in parallel; crc32 instructions take the 32 bytes and the last 0..63 bytes: - // 20 % faster at 256 bytes than folding onto one block. + // Blocks 0..5 fold onto blocks 6 and 7 in parallel; crc32 instructions take the 32 bytes and the last 0..63 bytes, + // two carry-less multiplications fewer than folding onto one block. std::size_t consumed = 0; std::array<__m256i, 4> const pairs = pclmul_kernel::fold_wide_blocks(constants, remainder, data, consumed); auto const both = [&](folding_pair const &distance) { return _mm256_broadcastsi128_si256(pclmul_kernel::pair(distance)); }; From 3dfe17dcfc97f3a44b04c934f5282f368b30b1c2 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:22:36 +0200 Subject: [PATCH 51/64] perf(internet): adc chains on x86-64, masked last word, rotate fold The portable loop takes 64-byte blocks in two chains of four words. On x86-64 __builtin_addcll turns each chain into add/adc with the carry added back at once, as Linux csum_partial does. The bytes after the last whole word come from one load of the message's last word with the summed bytes masked off, instead of three branches. fold() adds a value to its rotation by half the width. Short inputs return early and the kernel call is a tail call. --- src/include/checksum/internet.hpp | 13 +-- src/internet/sum_loop.cpp | 136 +++++++++++++++++++++--------- tests/unit_tests/ut_internet.cpp | 7 ++ 3 files changed, 111 insertions(+), 45 deletions(-) diff --git a/src/include/checksum/internet.hpp b/src/include/checksum/internet.hpp index 7417452..714c9c4 100644 --- a/src/include/checksum/internet.hpp +++ b/src/include/checksum/internet.hpp @@ -77,14 +77,15 @@ namespace checksum::internet_detail { template constexpr std::uint16_t fold(Value sum) noexcept { static_assert(std::numeric_limits::digits <= 64); + // The upper half of sum plus sum rotated by half its width is the end-around-carry sum of both halves. + std::uint32_t half = 0; if constexpr(std::numeric_limits::digits > 32) { - sum = (sum & 0xFFFFFFFFU) + (sum >> 32U); // < 2^33 - } - // < 2^17 + 2^16, then <= 0x10001, then <= 0xFFFF - for(int step = 0; step < 3; ++step) { - sum = (sum & 0xFFFFU) + (sum >> 16U); + std::uint64_t const wide = sum; + half = static_cast((wide + std::rotr(wide, 32)) >> 32U); + } else { + half = sum; } - return static_cast(sum); + return static_cast((half + std::rotr(half, 16)) >> 16U); } constexpr std::uint16_t sum_bytes(std::span data) noexcept { diff --git a/src/internet/sum_loop.cpp b/src/internet/sum_loop.cpp index 9e49d8f..c7cf5eb 100644 --- a/src/internet/sum_loop.cpp +++ b/src/internet/sum_loop.cpp @@ -23,25 +23,65 @@ static_assert(std::endian::native == std::endian::little || std::endian::native inline constexpr std::size_t word_size = sizeof(word); +// GCC and Clang turn __builtin_addcll into an adc chain on x86-64; GCC 14 on Arm materializes every carry instead. +#if defined(__x86_64__) && defined(__has_builtin) +#if __has_builtin(__builtin_addcll) +inline constexpr bool carry_flag_chain = true; +#else +inline constexpr bool carry_flag_chain = false; +#endif +#else +inline constexpr bool carry_flag_chain = false; +#endif + template Integer load(std::byte const *data) noexcept { Integer value = 0; std::memcpy(&value, data, sizeof(Integer)); return value; } -// sum + value, counting the carry out. +// sum + value, counting the carry out in carries, or adding it back at once with a carry flag chain. void add_with_carry(word &sum, word &carries, word value) noexcept; +// Adds Count words from data to sum in one carry chain, counting the carries out. +template [[gnu::always_inline]] inline void add_words(word &sum, word &carries, std::byte const *data) noexcept; + // The portable loop over data, plus a sum of native-order words already taken (unfolded); folded, in native byte order. [[gnu::always_inline]] inline std::uint16_t sum_words(std::span data, std::uint64_t blocks) noexcept; -// The CPU kernel, then the portable loop over what it left. Not inlined, so that short inputs run sum_loop() without a -// call: a call in it saved registers on every input and cost 13-23 % below 256 bytes on x86-64. +// The CPU kernel, then the portable loop over what it left; swapped like sum_loop(). Not inlined, so that short inputs +// run sum_loop() without a call: a call in it saved registers on every input and cost 13-23 % below 256 bytes on x86-64. [[gnu::noinline, maybe_unused]] std::uint16_t sum_long(std::span data) noexcept; +// The sum in native byte order to big-endian order. +std::uint16_t to_big_endian(std::uint16_t sum) noexcept; + void add_with_carry(word &sum, word &carries, word value) noexcept { - sum += value; - carries += sum < value ? 1U : 0U; + if constexpr(carry_flag_chain) { + unsigned long long carry = 0; + sum = __builtin_addcll(sum, value, 0, &carry); + sum += carry; + } else { + sum += value; + carries += sum < value ? 1U : 0U; + } +} + +template [[gnu::always_inline]] inline void add_words(word &sum, word &carries, std::byte const *data) noexcept { + if constexpr(carry_flag_chain) { + // The carry is added back at once: a chain that starts without one leaves a sum below 2^64 - 1 if it carries out. + unsigned long long carry = 0; +#pragma GCC unroll 8 + for(std::size_t index = 0; index < Count; ++index) { + sum = __builtin_addcll(sum, load(data + (index * word_size)), carry, &carry); + } + sum += carry; + } else { +#pragma GCC unroll 8 + for(std::size_t index = 0; index < Count; ++index) { + add_with_carry(sum, carries, load(data + (index * word_size))); + } + } } [[gnu::always_inline]] inline std::uint16_t sum_words(std::span data, std::uint64_t blocks) noexcept { @@ -49,47 +89,66 @@ void add_with_carry(word &sum, word &carries, word value) noexcept { std::array sums{}; std::array carries{}; std::byte const *position = data.data(); - std::size_t size = data.size(); - for(; size >= 4 * word_size; size -= 4 * word_size, position += 4 * word_size) { - add_with_carry(sums[0], carries[0], load(position)); - add_with_carry(sums[1], carries[1], load(position + word_size)); - add_with_carry(sums[0], carries[0], load(position + (2 * word_size))); - add_with_carry(sums[1], carries[1], load(position + (3 * word_size))); - } - for(; size >= word_size; size -= word_size, position += word_size) { - add_with_carry(sums[0], carries[0], load(position)); - } - // Fixed-size loads at even offsets: a native 32-bit word is congruent to the sum of its 16-bit halves. - std::uint64_t tail = 0; - if(word_size > 4 && (size & 4U) != 0) { - tail += load(position); - position += 4; - } - if(word_size > 2 && (size & 2U) != 0) { - tail += load(position); - position += 2; - } - if((size & 1U) != 0) { - // The first byte of a native 16-bit word, padded with zero. - tail += std::to_integer(*position) << (std::endian::native == std::endian::little ? 0U : 8U); + std::size_t const size = data.size(); + word tail = 0; + if(size < word_size) { + // Fixed-size loads at even offsets: a native 32-bit word is congruent to the sum of its 16-bit halves. + if(word_size > 4 && (size & 4U) != 0) { + tail += load(position); + position += 4; + } + if(word_size > 2 && (size & 2U) != 0) { + tail += load(position); + position += 2; + } + if((size & 1U) != 0) { + // The first byte of a native 16-bit word, padded with zero. + tail += std::to_integer(*position) << (std::endian::native == std::endian::little ? 0U : 8U); + } + } else { + for(std::byte const *const end = position + (size & ~((8 * word_size) - 1)); position != end; position += 8 * word_size) { + add_words<4>(sums[0], carries[0], position); + add_words<4>(sums[1], carries[1], position + (4 * word_size)); + } + // The rest in fixed steps of 4, 2 and 1 words, then the bytes after the last whole word. + if((size & (4 * word_size)) != 0) { + add_words<4>(sums[0], carries[0], position); + position += 4 * word_size; + } + if((size & (2 * word_size)) != 0) { + add_words<2>(sums[1], carries[1], position); + position += 2 * word_size; + } + if((size & word_size) != 0) { + add_words<1>(sums[0], carries[0], position); + } + if(size % word_size != 0) { + // The message's last word with the bytes already summed masked off; from an odd offset, rotating it by one byte + // multiplies it by 2^8, which moves each byte to the other half of its 16-bit word. + std::size_t const rest_bits = 8 * (size % word_size); + word const keep = std::endian::native == std::endian::little ? ~(~word{0} >> rest_bits) : ~(~word{0} << rest_bits); + tail = std::rotr(load(data.data() + size - word_size) & keep, static_cast(8 * (size % 2))); + } } - // Everything merged into one word, each carry worth 1, then one fold in the word's width. tail fits word: it holds fewer - // bytes than one word. + // Everything merged into one word, each carry worth 1, then one fold in the word's width; the tail goes into the second + // chain first, which is usually the shorter one. + add_with_carry(sums[1], carries[1], tail); + add_with_carry(sums[1], carries[1], fold(blocks)); add_with_carry(sums[0], carries[0], sums[1]); - add_with_carry(sums[0], carries[0], static_cast(tail)); - add_with_carry(sums[0], carries[0], fold(blocks)); word last_carry = 0; add_with_carry(sums[0], last_carry, carries[0] + carries[1]); // After a carry out, sums[0] is below the carries just added, so adding it back cannot overflow. return fold(static_cast(sums[0] + last_carry)); } +std::uint16_t to_big_endian(std::uint16_t sum) noexcept { return std::endian::native == std::endian::little ? std::byteswap(sum) : sum; } + [[gnu::noinline, maybe_unused]] std::uint16_t sum_long(std::span data) noexcept { if constexpr(block_sum_available) { block_total const total = block_sum(data); - return sum_words(data.subspan(total.size), total.sum); + return to_big_endian(sum_words(data.subspan(total.size), total.sum)); } else { - return sum_words(data, 0); + return to_big_endian(sum_words(data, 0)); } } @@ -97,13 +156,12 @@ void add_with_carry(word &sum, word &carries, word value) noexcept { // Words in native byte order: on little-endian targets this sums byte-swapped 16-bit words, and the swap of their sum is the big-endian sum. std::uint16_t sum_loop(std::span data) noexcept { - std::uint16_t sum = 0; if constexpr(block_sum_available) { - sum = data.size() >= block_sum_minimum_size ? sum_long(data) : sum_words(data, 0); - } else { - sum = sum_words(data, 0); + if(data.size() >= block_sum_minimum_size) [[unlikely]] { + return sum_long(data); + } } - return std::endian::native == std::endian::little ? std::byteswap(sum) : sum; + return to_big_endian(sum_words(data, 0)); } } // namespace checksum::internet_detail diff --git a/tests/unit_tests/ut_internet.cpp b/tests/unit_tests/ut_internet.cpp index 000ecd8..36817ba 100644 --- a/tests/unit_tests/ut_internet.cpp +++ b/tests/unit_tests/ut_internet.cpp @@ -116,6 +116,13 @@ TEST(internet, matches_model_with_carries) { EXPECT_EQ(internet_compute(std::span(ones).subspan(offset, (1 << 20) + 1)), 0x00FF) << "offset " << offset; } EXPECT_EQ(internet_compute(std::span(ones).first((5 << 20) + 1)), 0x00FF); + // Every length of the portable loop and its masked tail, where every word carries out. + for(std::size_t offset = 0; offset < 2; ++offset) { + for(std::size_t size = 0; size <= 600; ++size) { + auto const message = std::span(ones).subspan(offset, size); + ASSERT_EQ(internet_compute(message), reference(message)) << "offset " << offset << ", size " << size; + } + } } TEST(internet, split_anywhere) { From 9ff962cb4f01ad1cc8e26222ac49a6659fa391ad Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:10:37 +0200 Subject: [PATCH 52/64] docs(internet): re-measured portable loop, code size, reference comparison --- .cspell.yml | 4 +++ doc/design/acceleration.md | 18 ++++++++--- doc/internet.md | 64 +++++++++++++++++++++++--------------- 3 files changed, 56 insertions(+), 30 deletions(-) diff --git a/.cspell.yml b/.cspell.yml index 10ba650..83614d3 100644 --- a/.cspell.yml +++ b/.cspell.yml @@ -33,6 +33,7 @@ words: - adccp - adcs - addc +- addcll - addtogroup - aixm - alderlake @@ -49,6 +50,7 @@ words: - castsi - ccitt - cdma +- cinc - cksum - clmul - clmulepi @@ -62,6 +64,7 @@ words: - crcs - crosscompiling - cstdint +- csum - ctest - cvref - cvtepu @@ -70,6 +73,7 @@ words: - darc - datagram - dect +- DPDK - dtcm - eabi - endforeach diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index 5117ce8..f5234e7 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -88,7 +88,7 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cor A one's complement sum needs only additions, and the order of the bytes does not matter, so the portable loop is already fast. It adds native `std::size_t` words in two add-with-carry chains and swaps the bytes of the result once: -on x86-64 that is about 8 000 MB/s at 20 B and 49 000 MB/s at 4 KiB, without any instruction-set flags. A kernel has +on x86-64 that is about 7 700 MB/s at 20 B and 50 000 MB/s at 4 KiB, without any instruction-set flags. A kernel has to beat that, not a byte loop. | Target | Verdict | Why | @@ -121,14 +121,22 @@ Cortex-M methods, measured on the nRF52840 and STM32L4A6 (cycles per byte at 4 K | MCU CRC unit | - | It computes CRCs only. | What is left on Cortex-M: inputs below 192 bytes run the portable loop, dominated by the call and the final fold (about -100 cycles for 20 bytes). +125 cycles for 20 bytes). The `ldm` kernel at 192 B (273 cycles) now beats the portable loop at 191 B (345), so its +threshold could move lower. Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Cortex-M4: nRF52840): -- Two carry chains of 64-bit words: 1.3× one chain at 64 B, 2.6× at 4 KiB. A four-chain prototype was up to 1.3× +- Two carry chains of 64-bit words: 1.3× one chain at 64 B, 2.6× at 4 KiB. Each chain takes four words per 64-byte + block; on x86-64 `__builtin_addcll` makes it `add` + 3 `adc` + `adc $0` like Linux `csum_partial`, which took + 256 B from 0.84× to 0.97× of that function. GCC 14 on Arm materializes each carry of the builtin, so Arm and the + other targets keep the carry count (`adds` + `cinc`). Four chains of two words were not faster on x86-64. +- The bytes after the last whole word come from one load of the message's last word with the summed bytes masked off, + rotated by one byte when the length is odd; with the rotating fold this made 20 B 1.7× faster on the A72 (0.62× to 1.10× Linux `do_csum`, + which over-reads instead). Inputs shorter than one word take the 4-, 2- and 1-byte loads before any other branch; + behind the word steps they cost 10-13 % at 7 B. Skipping the masked load for whole-word lengths keeps 64-256 B fast. +- `fold()` adds a value to its rotation by half its width, two steps instead of four. A four-chain prototype was up to 1.3× faster again with Clang but 4× slower with GCC, which kept its array in memory; untried with separate variables. -- The tail is loaded in fixed 4-, 2- and 1-byte steps: a `memcpy` of variable size called the library function and - made a 20-byte input 3.5× slower. +- No `memcpy` of variable size for the tail: it called the library function and made a 20-byte input 3.5× slower. - One final fold after the carry chains are merged: three separate folds cost 8-20 % at 20-64 B. - The AVX2 and NEON kernels work in passes of 2^26 blocks (4 GiB), the vector kernel in passes of 2^18 iterations, so their 64-bit lanes never overflow. diff --git a/doc/internet.md b/doc/internet.md index ebe83de..926b9a9 100644 --- a/doc/internet.md +++ b/doc/internet.md @@ -75,9 +75,12 @@ keep the state instead. `value` must be a `std::uint16_t`: another integer type ## 5. CPU acceleration -The portable loop adds the widest native word (`std::size_t`) with two independent carry chains. It runs at every -optimization level, and its result does not depend on the target's byte order. The order in which bytes are added -does not change a one's complement sum, so the loop adds native-order words and swaps the bytes of the result once. +The portable loop adds the widest native word (`std::size_t`) in 64-byte blocks (32 bytes on 32-bit targets) with two +independent carry chains of four words; on x86-64 each chain is an `add`/`adc` sequence with its carry added back at +once. The bytes after the last whole word come from one load of the message's last word, the bytes already summed +masked off, so no load reaches past the message. It runs at every optimization level, and its result does not depend +on the target's byte order. The order in which bytes are added does not change a one's complement sum, so the loop +adds native-order words and swaps the bytes of the result once. | Target and flags | Kernel | Used from | | --- | --- | --- | @@ -103,15 +106,19 @@ AVX2 is with `-march=native`; portable is with `CHECKSUM_ACCELERATION=OFF` and d | Input | GCC 16 portable | GCC 16 AVX2 | Clang 21 portable | Clang 21 AVX2 | | --- | --- | --- | --- | --- | -| 20 B (IPv4 header) | 8 788 | 8 325 | 7 822 | 7 383 | -| 64 B | 19 619 | 19 412 | 22 743 | 19 761 | -| 256 B | 36 378 | 38 476 | 38 666 | 39 792 | -| 1500 B (Ethernet payload) | 39 273 | 64 339 | 37 892 | 69 386 | -| 4 KiB | 49 066 | 78 821 | 48 414 | 83 060 | -| 1 MiB | 54 418 | 68 182 | 53 725 | 77 821 | +| 20 B (IPv4 header) | 7 709 | 7 699 | 7 094 | 7 103 | +| 64 B | 23 687 | 22 613 | 22 634 | 21 829 | +| 256 B | 43 669 | 43 347 | 42 295 | 42 198 | +| 1500 B (Ethernet payload) | 49 918 | 71 039 | 47 943 | 76 279 | +| 4 KiB | 50 691 | 75 516 | 52 012 | 79 779 | +| 1 MiB | 56 060 | 90 044 | 55 770 | 93 630 | Below 512 bytes both builds run the portable loop; the differences come from `-march=native` and code layout. From -1500 bytes the AVX2 kernel is 1.6-1.8× faster. At 1 MiB the gain is smaller, because the data comes from the L2 cache. +1500 bytes the AVX2 kernel is 1.4-1.7× faster. + +Against Linux v7.3-rc5 `csum_partial` and DPDK `rte_raw_cksum`, built with the same GCC 16 `-O2 -march=native` and +called the same way, this build runs at 0.97× the faster of the two at 256 B, 0.98× at 64 B, 1.14× at 20 B and +1.35-1.76× from 1500 B. ### 6.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz @@ -131,6 +138,10 @@ The 64-bit portable loop is already fast, so the NEON kernel starts at 512 bytes bytes. In 32-bit mode the kernels start at 192 bytes: NEON is 4.1× and `ldm` 2.0× faster at 4 KiB. Below the thresholds every build runs the portable loop, and the differences there come from code layout. +The table predates the current portable loop, which is 1.1-1.45× faster in AArch64 and 1.05-1.4× faster in AArch32 up +to 256 B (comparison harness, same flags): AArch64 now takes 957 MB/s at 20 B, 1.10× Linux v7.3-rc5 `do_csum`, which +reads whole 8-byte words and masks off the bytes past the end. + ### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz GCC 14.3, `-O2`, code in flash and data in RAM; the cycle counter gives the best of 5 calls. Offset is the start @@ -138,18 +149,19 @@ address modulo 4: 2 is typical for an IP header behind a 14-byte Ethernet header | Input | nRF52840 portable | nRF52840 `ldm` | STM32L4A6 portable | STM32L4A6 `ldm` | | --- | --- | --- | --- | --- | -| 20 B | 10.3 | 10.0 | 12.9 | 12.5 | -| 64 B | 24.4 | 23.4 | 30.5 | 29.3 | -| 256 B | 40.2 | 49.5 | 50.2 | 61.9 | -| 1500 B | 48.5 | 80.1 | 60.6 | 100.2 | -| 4 KiB | 50.3 | 91.9 | 62.9 | 114.9 | -| 1500 B, offset 2 | 40.8 | 80.4 | 51.0 | 100.5 | -| 4 KiB, offset 1 | 36.1 | 88.7 | 45.2 | 110.9 | +| 20 B | 10.3 | 10.2 | 12.9 | 12.5 | +| 64 B | 24.4 | 22.4 | 30.5 | 29.3 | +| 256 B | 40.2 | 52.0 | 50.2 | 61.9 | +| 1500 B | 48.5 | 82.6 | 60.6 | 100.2 | +| 4 KiB | 50.3 | 92.5 | 62.9 | 114.9 | +| 1500 B, offset 2 | 40.8 | 81.4 | 51.0 | 100.5 | +| 4 KiB, offset 1 | 36.1 | 90.2 | 45.2 | 110.9 | Per byte at 4 KiB, the kernel takes 0.70 cycles against 1.27 for the portable loop: 1.8× faster, 1.2× at 256 bytes, and up to 2.5× from odd or 2-modulo-4 addresses, where the portable loop's unaligned loads cost more. Both chips run the -same cycles per byte, so the figures scale with the clock. Below 192 bytes the build with the kernel is up to 5 % -slower. +same cycles per byte, so the figures scale with the clock. The nRF52840 `ldm` column is re-measured with the current +portable loop, which is 1.05-1.4× faster than the one in the other columns below 192 bytes (1.2× at 20 B); at 191 +bytes it takes 345 cycles against 273 for the kernel at 192, so the threshold could move lower. ### 6.4 Code size @@ -158,11 +170,13 @@ loop twice: once for short inputs, once after the kernel. | Target | Portable | With kernel | | --- | --- | --- | -| Cortex-M4, `-Os` | 210 B | 778 B | -| Cortex-M4, `-O2` | 248 B | 944 B | -| x86-64, `-O2` (AVX2 with `-mavx2`) | 419 B | 1 229 B | -| AArch64, `-O2` | 364 B | 992 B | -| RISC-V RV64, `-O2` (V with `-march=rv64gcv`) | 848 B | 1 136 B | +| Cortex-M4, `-Os` | 284 B | 920 B | +| Cortex-M4, `-O2` | 356 B | 1 104 B | +| x86-64, `-O2` (AVX2 with `-mavx2`) | 385 B | 985 B | +| AArch64, `-O2` | 484 B | 1 076 B | +| RISC-V RV64, `-O2` (V with `-march=rv64gcv`) | 1 620 B | 1 402 B | + +RV64 without fast unaligned access loads each word byte by byte, which makes its unrolled portable loop large. RISC-V has not been measured on hardware; the vector kernel is tested in QEMU with vector lengths of 128-1024 bits. @@ -173,4 +187,4 @@ RISC-V has not been measured on hardware; the vector kernel is tested in QEMU wi field, as `examples/internet/ttl_decrement.cpp` does. - **UDP zero:** the UDP rule of sending 0xFFFF instead of a computed 0 is protocol logic and stays in the caller. - **No verification helper:** to verify a packet, compute over it, checksum included, and compare the result with 0. -- **Code size:** a build with a kernel adds 290-810 bytes; `CHECKSUM_ACCELERATION=OFF` keeps the portable loop alone. +- **Code size:** a build with a kernel adds 590-750 bytes on Arm and x86-64; `CHECKSUM_ACCELERATION=OFF` keeps the portable loop alone. From fac5f3a14cfa138ed66e6cc9b056a7e02596da27 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:03:17 +0200 Subject: [PATCH 53/64] perf(fletcher4): scalar lane combination, no stack protector check, AVX2 lanes from 128 B GCC vectorized the weight loop of combine() into emulated 64-bit vector multiplies; explicit sums with constant weights become shifts and adds. compute_loop() writes the long result into its own return value, so no local array triggers a stack protector check, and the long path builds its empty state itself. --- src/fletcher4/sum_loop.cpp | 85 +++++++++++-------- .../checksum_private/x86_64/fletcher4.hpp | 2 +- 2 files changed, 51 insertions(+), 36 deletions(-) diff --git a/src/fletcher4/sum_loop.cpp b/src/fletcher4/sum_loop.cpp index 5fac057..401c1c6 100644 --- a/src/fletcher4/sum_loop.cpp +++ b/src/fletcher4/sum_loop.cpp @@ -25,30 +25,30 @@ inline constexpr std::size_t lanes_minimum_size = // The little-endian word at data, from byte loads that compilers merge where unaligned loads are allowed: no memcpy call elsewhere. std::uint64_t load(std::byte const *data) noexcept; -// weights[sum][source][lane]: the weight of the lane's source sum in that sum of the words in message order. Word i of n has the weights 1, -// n-i, C(n-i+1, 2) and C(n-i+2, 3) in sum1 to sum4, which these weights express through the lane sums. -constexpr std::array, 4>, 4> weights{{ - {{{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}}, - {{{0, -1, -2, -3}, {4, 4, 4, 4}, {0, 0, 0, 0}, {0, 0, 0, 0}}}, - {{{0, 0, 1, 3}, {-6, -10, -14, -18}, {16, 16, 16, 16}, {0, 0, 0, 0}}}, - {{{0, 0, 0, -1}, {4, 10, 20, 34}, {-48, -64, -80, -96}, {64, 64, 64, 64}}}, -}}; - // The portable lanes over groups groups of words at data. [[gnu::always_inline, maybe_unused]] inline lane_sums sum_lanes(std::byte const *data, std::size_t groups) noexcept; +// lanes[1] + 2 * lanes[2] + 3 * lanes[3], a weight that grows by one per lane. +[[maybe_unused]] std::uint64_t ramp(std::array const &lanes) noexcept; + // The state after the words that lanes summed, a multiple of lane_count; the earlier sums add to the later ones once per word. -[[maybe_unused]] fletcher4_state combine(fletcher4_state state, lane_sums const &lanes, std::uint64_t words) noexcept; +[[gnu::always_inline, maybe_unused]] inline fletcher4_state combine(fletcher4_state state, lane_sums const &lanes, std::uint64_t words) noexcept; // One word at a time, then the bytes of an unfinished word. [[gnu::always_inline]] inline fletcher4_state sum_words(fletcher4_state state, std::span data) noexcept; -// The lanes of the CPU kernel, else the portable ones, then sum_words() over what they left. Not inlined, so that short inputs -// run sum_loop() without a call. +// The lanes of the CPU kernel, else the portable ones, then sum_words() over what they left. +[[gnu::always_inline, maybe_unused]] inline fletcher4_state sum_lanes_then_words(fletcher4_state state, std::span data) noexcept; + +// sum_lanes_then_words(). Not inlined, so that short inputs run sum_loop() without a call. [[gnu::noinline, maybe_unused]] fletcher4_state sum_long(fletcher4_state state, std::span data) noexcept; -// sum_long() from lanes_minimum_size bytes, else sum_words(). -[[gnu::always_inline]] inline fletcher4_state sum_any(fletcher4_state state, std::span data) noexcept; +// compute_loop() from lanes_minimum_size bytes, into value. The empty state is built here, so the short path of compute_loop() stores +// none; and value is the caller's return value, where a returned array would be a local copy behind a stack protector check. +[[gnu::noinline, maybe_unused]] void compute_long(std::span data, fletcher4_value &value) noexcept; + +// Whether data is long enough for the lanes. +[[gnu::always_inline]] inline bool use_lanes(std::span data) noexcept; std::uint64_t load(std::byte const *data) noexcept { return std::to_integer(data[0]) | (std::to_integer(data[1]) << 8) | (std::to_integer(data[2]) << 16) | @@ -68,20 +68,21 @@ std::uint64_t load(std::byte const *data) noexcept { return lanes; } -fletcher4_state combine(fletcher4_state state, lane_sums const &lanes, std::uint64_t words) noexcept { +std::uint64_t ramp(std::array const &lanes) noexcept { return lanes[1] + (2 * lanes[2]) + (3 * lanes[3]); } + +[[gnu::always_inline]] inline fletcher4_state combine(fletcher4_state state, lane_sums const &lanes, std::uint64_t words) noexcept { // C(n+1, 2) and C(n+2, 3) modulo 2^64 for an even n; the second divides exactly by 3, a product with its inverse modulo 2^64. std::uint64_t const triangular = (words / 2) * (words + 1); std::uint64_t const tetrahedral = triangular * (words + 2) * 0xAAAA'AAAA'AAAA'AAABU; - std::array sums{state.sum1, state.sum2 + (words * state.sum1), state.sum3 + (words * state.sum2) + (triangular * state.sum1), - state.sum4 + (words * state.sum3) + (triangular * state.sum2) + (tetrahedral * state.sum1)}; - for(std::size_t sum = 0; sum < sums.size(); ++sum) { - for(std::size_t source = 0; source <= sum; ++source) { - for(std::size_t lane = 0; lane < lane_count; ++lane) { - sums[sum] += static_cast(weights[sum][source][lane]) * lanes[source][lane]; - } - } - } - return {.sum1 = sums[0], .sum2 = sums[1], .sum3 = sums[2], .sum4 = sums[3]}; + auto const total = [&](std::size_t source) { return lanes[source][0] + lanes[source][1] + lanes[source][2] + lanes[source][3]; }; + // Word i of n weighs 1, n-i, C(n-i+1, 2) and C(n-i+2, 3) in sum1 to sum4; these are those weights in terms of the lane sums. + std::uint64_t const tail1 = lanes[0][2] + (3 * lanes[0][3]); + std::uint64_t const tail2 = lanes[1][2] + (3 * lanes[1][3]); + return {.sum1 = state.sum1 + total(0), + .sum2 = state.sum2 + (words * state.sum1) + (4 * total(1)) - ramp(lanes[0]), + .sum3 = state.sum3 + (words * state.sum2) + (triangular * state.sum1) + (16 * total(2)) - (6 * total(1)) - (4 * ramp(lanes[1])) + tail1, + .sum4 = state.sum4 + (words * state.sum3) + (triangular * state.sum2) + (tetrahedral * state.sum1) + (64 * total(3)) - (48 * total(2)) - + (16 * ramp(lanes[2])) + (4 * total(1)) + (6 * ramp(lanes[1])) + (4 * tail2) - lanes[0][3]}; } [[gnu::always_inline]] inline fletcher4_state sum_words(fletcher4_state state, std::span data) noexcept { @@ -99,7 +100,7 @@ fletcher4_state combine(fletcher4_state state, lane_sums const &lanes, std::uint return state; } -[[gnu::noinline]] fletcher4_state sum_long(fletcher4_state state, std::span data) noexcept { +[[gnu::always_inline]] inline fletcher4_state sum_lanes_then_words(fletcher4_state state, std::span data) noexcept { std::size_t const groups = data.size() / group_size; if constexpr(lane_kernel_available) { state = combine(state, lane_kernel(data.data(), groups), groups * lane_count); @@ -109,19 +110,33 @@ fletcher4_state combine(fletcher4_state state, lane_sums const &lanes, std::uint return sum_words(state, data.subspan(groups * group_size)); } -[[gnu::always_inline]] inline fletcher4_state sum_any(fletcher4_state state, std::span data) noexcept { - // Without lanes, sum_long() is not even linked. - if constexpr(lanes_minimum_size == std::numeric_limits::max()) { - return sum_words(state, data); - } else { - return data.size() >= lanes_minimum_size ? sum_long(state, data) : sum_words(state, data); - } +[[gnu::noinline]] fletcher4_state sum_long(fletcher4_state state, std::span data) noexcept { + return sum_lanes_then_words(state, data); +} + +[[gnu::noinline]] void compute_long(std::span data, fletcher4_value &value) noexcept { + value = fletcher4_finalize(sum_lanes_then_words(fletcher4_state{}, data)); +} + +[[gnu::always_inline]] inline bool use_lanes(std::span data) noexcept { + // Without lanes, the long functions are not even linked. + return lanes_minimum_size != std::numeric_limits::max() && data.size() >= lanes_minimum_size; } } // namespace -fletcher4_state sum_loop(fletcher4_state state, std::span data) noexcept { return sum_any(state, data); } +fletcher4_state sum_loop(fletcher4_state state, std::span data) noexcept { + return use_lanes(data) ? sum_long(state, data) : sum_words(state, data); +} -fletcher4_value compute_loop(std::span data) noexcept { return fletcher4_finalize(sum_any(fletcher4_state{}, data)); } +fletcher4_value compute_loop(std::span data) noexcept { + fletcher4_value value{}; + if(use_lanes(data)) { + compute_long(data, value); + } else { + value = fletcher4_finalize(sum_words(fletcher4_state{}, data)); + } + return value; +} } // namespace checksum::fletcher4_detail diff --git a/src/include_private/checksum_private/x86_64/fletcher4.hpp b/src/include_private/checksum_private/x86_64/fletcher4.hpp index ad1c54b..52865b5 100644 --- a/src/include_private/checksum_private/x86_64/fletcher4.hpp +++ b/src/include_private/checksum_private/x86_64/fletcher4.hpp @@ -20,7 +20,7 @@ inline constexpr bool lane_kernel_available = true; #if defined(__AVX2__) // Where the kernel overtakes the word loop on a Core Ultra 7 155H, with GCC and Clang. -inline constexpr std::size_t lane_kernel_minimum_size = 192; +inline constexpr std::size_t lane_kernel_minimum_size = 128; inline lane_sums lane_kernel(std::byte const *data, std::size_t groups) noexcept { __m256i sum1 = _mm256_setzero_si256(); From eeda7a2396644b9f0315ae8221089e7e2392b694 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:25:15 +0200 Subject: [PATCH 54/64] perf(fletcher4): zero the long result only on the long path, SSE2 lanes from 192 B WIP: docs, cross-check tables and the nRF52840 run still to do. --- src/fletcher4/sum_loop.cpp | 7 +++---- src/include_private/checksum_private/x86_64/fletcher4.hpp | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/fletcher4/sum_loop.cpp b/src/fletcher4/sum_loop.cpp index 401c1c6..778348d 100644 --- a/src/fletcher4/sum_loop.cpp +++ b/src/fletcher4/sum_loop.cpp @@ -130,13 +130,12 @@ fletcher4_state sum_loop(fletcher4_state state, std::span data) } fletcher4_value compute_loop(std::span data) noexcept { - fletcher4_value value{}; if(use_lanes(data)) { + fletcher4_value value{}; compute_long(data, value); - } else { - value = fletcher4_finalize(sum_words(fletcher4_state{}, data)); + return value; } - return value; + return fletcher4_finalize(sum_words(fletcher4_state{}, data)); } } // namespace checksum::fletcher4_detail diff --git a/src/include_private/checksum_private/x86_64/fletcher4.hpp b/src/include_private/checksum_private/x86_64/fletcher4.hpp index 52865b5..17e01d6 100644 --- a/src/include_private/checksum_private/x86_64/fletcher4.hpp +++ b/src/include_private/checksum_private/x86_64/fletcher4.hpp @@ -47,7 +47,7 @@ inline lane_sums lane_kernel(std::byte const *data, std::size_t groups) noexcept #else // The kernel overtakes the word loop on a Core Ultra 7 155H at 192 bytes with GCC and at 384 with Clang, which is 10 % slower at 256. -inline constexpr std::size_t lane_kernel_minimum_size = 256; +inline constexpr std::size_t lane_kernel_minimum_size = 192; // Lanes 0 and 1 in the low vectors, 2 and 3 in the high ones. inline lane_sums lane_kernel(std::byte const *data, std::size_t groups) noexcept { From 69897fc3c5fcdbbd1b983908e806a2ed6be0bbeb Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:23:05 +0200 Subject: [PATCH 55/64] perf(fletcher4): NEON lanes from 192 B on AArch32 too With the cheaper lane combination they overtake the word loop at 192 B on a Cortex-A72 in AArch32 with GCC and Clang, as on AArch64. --- src/include_private/checksum_private/arm/fletcher4.hpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/include_private/checksum_private/arm/fletcher4.hpp b/src/include_private/checksum_private/arm/fletcher4.hpp index 3a91a0a..0b19faf 100644 --- a/src/include_private/checksum_private/arm/fletcher4.hpp +++ b/src/include_private/checksum_private/arm/fletcher4.hpp @@ -12,14 +12,13 @@ #include #include -#include namespace checksum::fletcher4_detail { inline constexpr bool lane_kernel_available = true; -// Where the kernel overtakes the word loop on a Cortex-A72 with GCC and Clang. On AArch32 it pays a slower combination of the lanes. -inline constexpr std::size_t lane_kernel_minimum_size = std::numeric_limits::digits == 64 ? 192 : 384; +// Where the kernel overtakes the word loop on a Cortex-A72 with Clang, on AArch64 and AArch32; with GCC it wins from 80 bytes on AArch64. +inline constexpr std::size_t lane_kernel_minimum_size = 192; // Lanes 0 and 1 in the low vectors, 2 and 3 in the high ones. inline lane_sums lane_kernel(std::byte const *data, std::size_t groups) noexcept { From 5e2b35fff154ca7fa3876a74012a2fba8f0b26b4 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:31:15 +0200 Subject: [PATCH 56/64] refactor(fletcher4): lane weights as powers of the lane count Same code; the constants of combine() get names. --- src/fletcher4/sum_loop.cpp | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/fletcher4/sum_loop.cpp b/src/fletcher4/sum_loop.cpp index 778348d..fdd4169 100644 --- a/src/fletcher4/sum_loop.cpp +++ b/src/fletcher4/sum_loop.cpp @@ -16,7 +16,7 @@ namespace { // Bytes of one word per lane. inline constexpr std::size_t group_size = lane_count * word_size; -// Shortest input for the lanes. The portable ones overtake the word loop on a Cortex-A72 at 256 bytes with GCC, 384 with Clang; on 32-bit targets +// Shortest input for the lanes. The portable ones overtake the word loop on a Cortex-A72 at 128 bytes with GCC, 256 with Clang; on 32-bit targets // their 64-bit sums run out of registers, 3 times slower there. inline constexpr std::size_t lanes_minimum_size = lane_kernel_available ? lane_kernel_minimum_size @@ -75,14 +75,21 @@ std::uint64_t ramp(std::array const &lanes) noexcept std::uint64_t const triangular = (words / 2) * (words + 1); std::uint64_t const tetrahedral = triangular * (words + 2) * 0xAAAA'AAAA'AAAA'AAABU; auto const total = [&](std::size_t source) { return lanes[source][0] + lanes[source][1] + lanes[source][2] + lanes[source][3]; }; - // Word i of n weighs 1, n-i, C(n-i+1, 2) and C(n-i+2, 3) in sum1 to sum4; these are those weights in terms of the lane sums. + // Word i of n weighs 1, n-i, C(n-i+1, 2) and C(n-i+2, 3) in sum1 to sum4; these are those weights in terms of the lane sums, where + // a lane word stands for lane_count message words. + constexpr std::uint64_t width = lane_count; + constexpr std::uint64_t squared = width * width; + constexpr std::uint64_t cubed = squared * width; + constexpr std::uint64_t pairs = (squared - width) / 2; std::uint64_t const tail1 = lanes[0][2] + (3 * lanes[0][3]); std::uint64_t const tail2 = lanes[1][2] + (3 * lanes[1][3]); return {.sum1 = state.sum1 + total(0), - .sum2 = state.sum2 + (words * state.sum1) + (4 * total(1)) - ramp(lanes[0]), - .sum3 = state.sum3 + (words * state.sum2) + (triangular * state.sum1) + (16 * total(2)) - (6 * total(1)) - (4 * ramp(lanes[1])) + tail1, - .sum4 = state.sum4 + (words * state.sum3) + (triangular * state.sum2) + (tetrahedral * state.sum1) + (64 * total(3)) - (48 * total(2)) - - (16 * ramp(lanes[2])) + (4 * total(1)) + (6 * ramp(lanes[1])) + (4 * tail2) - lanes[0][3]}; + .sum2 = state.sum2 + (words * state.sum1) + (width * total(1)) - ramp(lanes[0]), + .sum3 = state.sum3 + (words * state.sum2) + (triangular * state.sum1) + (squared * total(2)) - (pairs * total(1)) - + (width * ramp(lanes[1])) + tail1, + .sum4 = state.sum4 + (words * state.sum3) + (triangular * state.sum2) + (tetrahedral * state.sum1) + (cubed * total(3)) - + ((cubed - squared) * total(2)) - (squared * ramp(lanes[2])) + (width * total(1)) + (pairs * ramp(lanes[1])) + (width * tail2) - + lanes[0][3]}; } [[gnu::always_inline]] inline fletcher4_state sum_words(fletcher4_state state, std::span data) noexcept { From fb7ab8867828119fb41b9a2eee25cf072103722a Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:31:15 +0200 Subject: [PATCH 57/64] docs(fletcher4): new thresholds, re-measured x86 and A72 tables, OpenZFS comparison --- doc/design/acceleration.md | 25 ++++++++++++------ doc/fletcher4.md | 54 +++++++++++++++++++++----------------- 2 files changed, 47 insertions(+), 32 deletions(-) diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index f5234e7..45e2c97 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -276,11 +276,11 @@ long input pays a fixed cost of a few multiplications. All sums wrap modulo 2^64 | Target | Verdict | Why | | --- | --- | --- | -| x86-64 AVX2 | Yes, from 192 B | One 256-bit vector per sum. 29 164 MB/s at 4 KiB with GCC against 19 781 for the SSE2 kernel (1.5×); 30 027 with Clang. | -| x86-64 SSE2 (baseline) | Yes, from 256 B | Two 128-bit vectors per sum. With GCC as fast as the portable lanes from 512 B; with Clang 19 755 MB/s at 4 KiB against 7 156 for the portable lanes. | -| AArch64 NEON, little-endian | Yes, from 192 B | A72 at 256 B: 1 747 against 1 539 MB/s with GCC, 1 842 against 1 547 with Clang; at 4 KiB 2 % (GCC) and 21 % (Clang) faster. | -| 32-bit Arm NEON, little-endian | Yes, from 384 B | A72 in AArch32 at 4 KiB: 2 179 MB/s with GCC against 1 059 for the word loop (2.1×), 2 809 with Clang. The combination of the lanes costs more than on AArch64. | -| Portable lanes, 64-bit targets | Yes, from 256 B | They overtake the word loop on the A72 at 256 B with GCC and 384 with Clang. | +| x86-64 AVX2 | Yes, from 128 B | One 256-bit vector per sum. 29 258 MB/s at 4 KiB with GCC against 19 318 for the SSE2 kernel (1.5×); 28 620 with Clang. | +| x86-64 SSE2 (baseline) | Yes, from 192 B | Two 128-bit vectors per sum. With GCC the portable lanes are within 15 % of it from 1500 B; with Clang 19 246 MB/s at 4 KiB against 8 424 for the portable lanes. | +| AArch64 NEON, little-endian | Yes, from 192 B | A72 at 256 B: 2 209 MB/s with GCC, as fast as its portable lanes; 2 101 with Clang against 1 500 for its portable lanes. | +| 32-bit Arm NEON, little-endian | Yes, from 192 B | A72 in AArch32 at 4 KiB: 2 384 MB/s with GCC against 1 069 for the word loop (2.2×), 2 862 with Clang. | +| Portable lanes, 64-bit targets | Yes, from 256 B | On the A72 they overtake the word loop at 128 B with GCC but only at 256 B with Clang, whose word loop is unrolled. | | Portable lanes, 32-bit targets | No | The 64-bit sums of four lanes do not fit the registers: 3× slower than the word loop. Without a kernel the lane code is not even linked. | | Big-endian NEON | No | The kernel reads vector lanes as little-endian words; big-endian AArch64 runs the portable lanes. | | RISC-V V extension | Not done | No hardware to measure; RV64 runs the portable lanes. | @@ -288,9 +288,18 @@ long input pays a fixed cost of a few multiplications. All sums wrap modulo 2^64 Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cortex-A72): -- Thresholds are where the lanes overtake the word loop of the same build: AVX2 at 192 B with GCC and Clang; SSE2 at - 192 B with GCC and 384 with Clang, which is 10 % slower at 256, so 256; NEON at 192 B on AArch64 and 384 on AArch32. +- Thresholds are where the lanes overtake the word loop of the same build, with GCC and Clang: AVX2 at 128 B; SSE2 at + 192 B (GCC's SSE2 lanes are slower at 128 and 160); NEON at 192 B on AArch64 and AArch32, where Clang's unrolled word + loop wins below (GCC's NEON lanes win from 80 B). +- `combine()` is written out with constant weights, which become shifts and additions. As a loop over a weight table + GCC vectorized it into emulated 64-bit vector multiplications, which cost more than the lanes saved up to 512 B. +- `compute_loop()` passes its own return value to the long path by reference. A `fletcher4_value` returned by a call is + an array local, which `-fstack-protector-strong` (on by default in some distributions) guards with a canary check on + every call, short ones included. - Words are assembled from four byte loads, which compilers merge into one load where unaligned loads are allowed; elsewhere this avoids a call to `memcpy`. - The lane loop and the word loop after it sit in a separate non-inlined function, as for the Internet checksum, so - inputs below the threshold run without a call. + inputs below the threshold run without a call; `fletcher4_compute` has its own copy that starts from the empty state. +- Against OpenZFS f79c81d (`fletcher_4_native` with its superscalar4, sse2, ssse3, avx2 and aarch64_neon kernels, GCC + `-O2`), the library runs at 0.93× the fastest at 20 B and 1.09× at 256 B on x86-64, 0.92× and 1.18× on the A72, and + 1.0× from 4 KiB on both. diff --git a/doc/fletcher4.md b/doc/fletcher4.md index 9b1c41e..ef1abfc 100644 --- a/doc/fletcher4.md +++ b/doc/fletcher4.md @@ -79,10 +79,10 @@ run in vector registers where a kernel exists, else in portable code: | Target and flags | Lanes | | --- | --- | -| x86-64 with AVX2 (`-mavx2`, or a `-march` that includes it) | One 256-bit vector per sum, from 192 B | -| x86-64 without AVX2 (SSE2 is always there) | Two 128-bit vectors per sum, from 256 B | +| x86-64 with AVX2 (`-mavx2`, or a `-march` that includes it) | One 256-bit vector per sum, from 128 B | +| x86-64 without AVX2 (SSE2 is always there) | Two 128-bit vectors per sum, from 192 B | | AArch64, little-endian | NEON, two 128-bit vectors per sum, from 192 B | -| 32-bit Arm with NEON, little-endian | NEON, from 384 B | +| 32-bit Arm with NEON, little-endian | NEON, from 192 B | | other 64-bit targets (RISC-V, big-endian AArch64), or `CHECKSUM_ACCELERATION=OFF` on a 64-bit target | Portable lanes, from 256 B | | other 32-bit targets (Cortex-M, 32-bit Arm without NEON, big-endian), or `CHECKSUM_ACCELERATION=OFF` on a 32-bit target | Word loop only | @@ -95,37 +95,43 @@ behind each choice are in [design/acceleration.md](design/acceleration.md#fletch ### 6.1 x86-64: Core Ultra 7 155H -MB/s (10⁶ bytes per second). Portable is the library with `CHECKSUM_ACCELERATION=OFF` (portable lanes from 256 B), -SSE2 the default x86-64 flags, AVX2 a build with AVX2 enabled. +MB/s (10⁶ bytes per second), `-O2`, one core, each call timed in a loop over the same buffer. Portable is the library with +`CHECKSUM_ACCELERATION=OFF` (portable lanes from 256 B), SSE2 the default x86-64 flags, AVX2 `-march=native`. | Build | 20 B | 64 B | 128 B | 256 B | 512 B | 1500 B | 4 KiB | 1 MiB | | --- | --- | --- | --- | --- | --- | --- | --- | --- | -| GCC portable | 4 724 | 8 081 | 10 258 | 12 082 | 16 265 | 18 201 | 19 804 | 20 712 | -| GCC SSE2 | 4 206 | 7 556 | 10 179 | 13 079 | 15 665 | 17 593 | 19 781 | 20 518 | -| GCC AVX2 | 4 195 | 8 127 | 9 840 | 15 354 | 20 756 | 26 230 | 29 164 | 30 678 | -| Clang portable | 3 995 | 8 342 | 10 879 | 5 052 | 6 137 | 6 916 | 7 156 | 7 233 | -| Clang SSE2 | 3 975 | 8 323 | 10 972 | 12 732 | 15 618 | 18 341 | 19 755 | 20 600 | -| Clang AVX2 | 3 996 | 8 993 | 11 004 | 16 393 | 21 805 | 26 679 | 30 027 | 31 376 | +| GCC portable | 4 269 | 8 114 | 9 378 | 9 725 | 13 357 | 15 640 | 16 917 | 17 497 | +| GCC SSE2 | 4 402 | 8 233 | 9 756 | 13 545 | 16 092 | 17 811 | 19 318 | 19 703 | +| GCC AVX2 | 4 715 | 9 440 | 12 863 | 18 875 | 21 258 | 26 384 | 29 258 | 30 817 | +| Clang portable | 3 665 | 8 977 | 10 443 | 5 591 | 6 096 | 7 818 | 8 424 | 8 757 | +| Clang SSE2 | 4 293 | 8 886 | 10 437 | 13 512 | 16 259 | 17 679 | 19 246 | 19 416 | +| Clang AVX2 | 3 716 | 9 120 | 11 612 | 16 941 | 22 186 | 26 171 | 28 620 | 29 653 | -Below the thresholds every build runs the word loop; the differences there come from code layout. AVX2 is 1.5× the -SSE2 kernel at 4 KiB. With GCC the portable lanes are as fast as the SSE2 kernel from 512 bytes; with Clang they reach -about a third of its speed, which matters only for a build with `CHECKSUM_ACCELERATION=OFF`. +Below the thresholds every build runs the word loop; differences of up to 10 % there come from code placement, which +moves with the link order. AVX2 is 1.5× the SSE2 kernel at 4 KiB. With GCC the portable lanes are within 15 % of the +SSE2 kernel from 1500 bytes; with Clang they reach about 45 % of it, which matters only for a build with `CHECKSUM_ACCELERATION=OFF`. + +Against the OpenZFS kernels (`fletcher_4_native` of OpenZFS f79c81d with its superscalar4, sse2, ssse3 and avx2 kernels, +all built with GCC `-O2 -march=native`), the AVX2 build runs at 0.93× the fastest at 20 bytes, 1.09× at 256 bytes and +1.0× from 1500 bytes. ### 6.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz -GCC 14.3 and Clang, `-O2`, one core. MB/s: +GCC 14.3 and Clang 21, `-O2 -mcpu=cortex-a72`, one core. MB/s: | Build | 20 B | 64 B | 128 B | 256 B | 512 B | 1500 B | 4 KiB | 1 MiB | | --- | --- | --- | --- | --- | --- | --- | --- | --- | -| AArch64 GCC portable | 571 | 1 114 | 1 255 | 1 539 | 1 947 | 2 580 | 2 889 | 2 774 | -| AArch64 GCC NEON | 570 | 1 116 | 1 252 | 1 747 | 2 135 | 2 678 | 2 933 | 2 768 | -| AArch64 Clang portable | 825 | 1 363 | 1 613 | 1 547 | 1 912 | 2 232 | 2 398 | 2 264 | -| AArch64 Clang NEON | 822 | 1 373 | 1 529 | 1 842 | 2 292 | 2 675 | 2 900 | 2 703 | -| AArch32 GCC word loop | 229 | 504 | 688 | 811 | 927 | 1 021 | 1 059 | 1 041 | -| AArch32 GCC NEON | 309 | 603 | 775 | 860 | 1 041 | 1 663 | 2 179 | 2 334 | -| AArch32 Clang NEON | 389 | 689 | 826 | 976 | 1 719 | 2 367 | 2 809 | 2 773 | - -On AArch64 NEON gains 14 % (GCC) and 19 % (Clang) at 256 bytes, and 2 % (GCC) and 21 % (Clang) at 4 KiB. On AArch32 NEON is 2.1× the word loop at 4 KiB with GCC. +| AArch64 GCC portable | 803 | 1 343 | 1 526 | 2 228 | 2 432 | 2 797 | 3 026 | 2 766 | +| AArch64 GCC NEON | 803 | 1 337 | 1 531 | 2 209 | 2 450 | 2 827 | 3 024 | 2 757 | +| AArch64 Clang portable | 756 | 1 462 | 1 813 | 1 500 | 1 494 | 1 619 | 1 672 | 1 617 | +| AArch64 Clang NEON | 761 | 1 465 | 1 809 | 2 101 | 2 443 | 2 740 | 2 889 | 2 638 | +| AArch32 GCC word loop | 484 | 778 | 839 | 931 | 1 001 | 1 053 | 1 069 | 1 027 | +| AArch32 GCC NEON | 375 | 678 | 769 | 1 126 | 1 504 | 2 046 | 2 384 | 2 408 | +| AArch32 Clang NEON | 325 | 622 | 785 | 1 354 | 1 788 | 2 460 | 2 862 | 2 815 | + +On AArch64 with GCC the portable lanes are as fast as NEON; with Clang NEON is 1.4× them at 256 bytes and 1.7× at +4 KiB. On AArch32 NEON is 2.2× the word loop at 4 KiB with GCC. Against OpenZFS (GCC, its superscalar4 and aarch64_neon +kernels) the AArch64 GCC build runs at 0.92× at 20 bytes, 1.18× at 256 bytes and 1.0× from 4 KiB. ### 6.3 Cortex-M4 From c1dfc6efe6f14177cae9f191d6ebdc19565c60de Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:10:25 +0200 Subject: [PATCH 58/64] perf(adler32, fletcher): AVX-VNNI byte kernel, four blocks per iteration vpdpbusd weights four 32-byte blocks by 127..0 in one instruction each, so the previous sums are added once per 128 bytes; the lane totals reduce together. --- .../checksum_private/x86_64/fletcher.hpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/include_private/checksum_private/x86_64/fletcher.hpp b/src/include_private/checksum_private/x86_64/fletcher.hpp index 06c0204..b0d7594 100644 --- a/src/include_private/checksum_private/x86_64/fletcher.hpp +++ b/src/include_private/checksum_private/x86_64/fletcher.hpp @@ -159,6 +159,57 @@ template std::uint64_t column_total(simd_vector low, simd_vector hi return total; } +#if defined(__AVXVNNI__) +// vpdpbusd weights four blocks by 127, 126, ..., 0 with one instruction per block, and adding the byte sums once at the end +// makes the weights 128 .. 1; so previous gains the sums only every four blocks. Four accumulators hide the latency of +// vpdpbusd. The last blocks weigh 31 .. 0 and count their previous per block. +inline chunk_sums kernel<8>::sum(std::byte const *data, std::size_t blocks) noexcept { + simd_vector const zero = _mm256_setzero_si256(); + simd_vector const first_weights = _mm256_setr_epi8(127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, + 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96); + simd_vector const second_weights = _mm256_setr_epi8(95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, + 71, 70, 69, 68, 67, 66, 65, 64); + simd_vector const third_weights = _mm256_setr_epi8(63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, + 39, 38, 37, 36, 35, 34, 33, 32); + simd_vector const fourth_weights = + _mm256_setr_epi8(31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + // The byte sums of psadbw are 64-bit lanes. + simd_vector sum = zero; + simd_vector group_previous = zero; + simd_vector weighted = zero; + simd_vector second_weighted = zero; + simd_vector third_weighted = zero; + simd_vector fourth_weighted = zero; + for(; blocks >= 4; blocks -= 4, data += 4 * block_size) { + simd_vector const first = load_vector(data); + simd_vector const second = load_vector(data + block_size); + simd_vector const third = load_vector(data + (2 * block_size)); + simd_vector const fourth = load_vector(data + (3 * block_size)); + group_previous = _mm256_add_epi64(group_previous, sum); + sum = _mm256_add_epi64( + sum, _mm256_add_epi64(_mm256_add_epi64(byte_sums(first), byte_sums(second)), _mm256_add_epi64(byte_sums(third), byte_sums(fourth)))); + weighted = _mm256_dpbusd_avx_epi32(weighted, first, first_weights); + second_weighted = _mm256_dpbusd_avx_epi32(second_weighted, second, second_weights); + third_weighted = _mm256_dpbusd_avx_epi32(third_weighted, third, third_weights); + fourth_weighted = _mm256_dpbusd_avx_epi32(fourth_weighted, fourth, fourth_weights); + } + weighted = add_lanes32(add_lanes32(weighted, second_weighted), add_lanes32(third_weighted, fourth_weighted)); + simd_vector previous = zero; + for(; blocks != 0; --blocks, data += block_size) { + simd_vector const value = load_vector(data); + previous = _mm256_add_epi64(previous, sum); + sum = _mm256_add_epi64(sum, byte_sums(value)); + weighted = _mm256_dpbusd_avx_epi32(weighted, value, fourth_weights); + } + // In 64-bit lanes: 128 * group_previous + 32 * previous + both halves of weighted + sum, then both totals at once. + simd_vector const total = + _mm256_add_epi64(_mm256_add_epi64(_mm256_slli_epi64(group_previous, 7), _mm256_slli_epi64(previous, 5)), + _mm256_add_epi64(_mm256_add_epi64(_mm256_srli_epi64(weighted, 32), _mm256_blend_epi32(weighted, zero, 0xAA)), sum)); + simd_vector const pairs = _mm256_add_epi64(_mm256_unpacklo_epi64(sum, total), _mm256_unpackhi_epi64(sum, total)); + __m128i const totals = _mm_add_epi64(_mm256_castsi256_si128(pairs), _mm256_extracti128_si256(pairs, 1)); + return {.sum = static_cast(_mm_cvtsi128_si64(totals)), .weighted = static_cast(_mm_extract_epi64(totals, 1))}; +} +#else // Per block: previous += sum, so that previous ends as the sum over blocks of the byte sums before each block. The byte sums // stay below 2^32, so their 64-bit lanes of psadbw add as 32-bit lanes. inline chunk_sums kernel<8>::sum(std::byte const *data, std::size_t blocks) noexcept { @@ -174,6 +225,7 @@ inline chunk_sums kernel<8>::sum(std::byte const *data, std::size_t blocks) noex return {.sum = lane_total(sum), .weighted = (block_size * lane_total(previous)) + lane_total(weighted)}; } +#endif // Column sums of the values, weighted at the end of the chunk; previous as for bytes. inline chunk_sums kernel<16>::sum(std::byte const *data, std::size_t blocks) noexcept { From a893f54841e25cbcaf9a0823a367022d2e92af30 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:10:51 +0200 Subject: [PATCH 59/64] perf(adler32, fletcher): AArch64 NEON byte kernel over 64-byte groups From 320 bytes, group_kernel sums four 16-byte blocks per iteration with pairwise additions and 64 column sums weighted 64..1, as zlib-ng does; sum_long() reaches it through a tail call so its registers do not slow the 16-byte kernel. Adler-32 on the Cortex-A72 at 4 KiB: 4 746 -> 6 270 MB/s. AArch32 keeps the 16-byte kernel: with half the registers it spilled. --- .../checksum_private/arm/fletcher.hpp | 78 +++++++++++++++++++ .../checksum_private/fletcher_loops.hpp | 27 +++++-- .../checksum_private/generic/fletcher.hpp | 8 +- tests/unit_tests/ut_adler32.cpp | 4 +- tests/unit_tests/ut_fletcher.cpp | 4 +- 5 files changed, 111 insertions(+), 10 deletions(-) diff --git a/src/include_private/checksum_private/arm/fletcher.hpp b/src/include_private/checksum_private/arm/fletcher.hpp index 0c26c9b..0e34c71 100644 --- a/src/include_private/checksum_private/arm/fletcher.hpp +++ b/src/include_private/checksum_private/arm/fletcher.hpp @@ -34,6 +34,23 @@ template <> struct kernel<8> { static chunk_sums sum(std::byte const *data, std::size_t blocks) noexcept; }; +#if defined(__aarch64__) +// AArch32 has half the NEON registers: there the group loop spilled and ran 10-27 % slower than kernel<8>. +template <> struct group_kernel<8> { + static constexpr bool available = true; + static constexpr std::size_t block_size = 16; + // The weighted sum of a chunk, at most 255 * n(n + 1) / 2 for n bytes, stays within 32 bits, so the chunk loop reduces in + // 32-bit arithmetic. A 16-bit lane of the column sums gains at most 255 per 4 blocks, and 255 per block in the last 3. + static constexpr std::size_t max_blocks = 360; + static_assert(std::uint64_t{255} * (block_size * max_blocks) * ((block_size * max_blocks) + 1) / 2 <= std::numeric_limits::max()); + static_assert(255 * ((max_blocks / 4) + 3) <= std::numeric_limits::max()); + // Where it overtakes kernel<8> on a Cortex-A72 (Raspberry Pi 4); below, its 64 column weights cost more than they save. + static constexpr std::size_t minimum_size = 320; + static constexpr std::size_t alignment = 1; + static chunk_sums sum(std::byte const *start, std::size_t blocks) noexcept; +}; +#endif + template <> struct kernel<16> { static constexpr bool available = true; static constexpr std::size_t block_size = 16; @@ -88,6 +105,67 @@ inline chunk_sums kernel<8>::sum(std::byte const *data, std::size_t blocks) noex return {.sum = lane_total(sum), .weighted = (block_size * lane_total(previous)) + lane_total(weighted)}; } +#if defined(__aarch64__) +// As kernel<8> per 64 bytes, with pairwise additions of the 4 blocks into sum and 64 columns weighted 64 .. 1. The last +// blocks that fill no group add to the columns of the last 16 bytes, weights 16 .. 1, and count their previous per block. +inline chunk_sums group_kernel<8>::sum(std::byte const *start, std::size_t blocks) noexcept { + auto const *data = reinterpret_cast(start); + static constexpr std::array weights{64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, + 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, + 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; + uint32x4_t sum = vdupq_n_u32(0); + uint32x4_t previous = sum; + uint16x8_t columns0 = vdupq_n_u16(0); + uint16x8_t columns1 = columns0; + uint16x8_t columns2 = columns0; + uint16x8_t columns3 = columns0; + uint16x8_t columns4 = columns0; + uint16x8_t columns5 = columns0; + uint16x8_t columns6 = columns0; + uint16x8_t columns7 = columns0; + for(; blocks >= 4; blocks -= 4, data += 4 * block_size) { + uint8x16_t const first = vld1q_u8(data); + uint8x16_t const second = vld1q_u8(data + block_size); + uint8x16_t const third = vld1q_u8(data + (2 * block_size)); + uint8x16_t const fourth = vld1q_u8(data + (3 * block_size)); + previous = vaddq_u32(previous, sum); + sum = vpadalq_u16(sum, vpadalq_u8(vpadalq_u8(vpadalq_u8(vpaddlq_u8(first), second), third), fourth)); + columns0 = vaddw_u8(columns0, vget_low_u8(first)); + columns1 = vaddw_u8(columns1, vget_high_u8(first)); + columns2 = vaddw_u8(columns2, vget_low_u8(second)); + columns3 = vaddw_u8(columns3, vget_high_u8(second)); + columns4 = vaddw_u8(columns4, vget_low_u8(third)); + columns5 = vaddw_u8(columns5, vget_high_u8(third)); + columns6 = vaddw_u8(columns6, vget_low_u8(fourth)); + columns7 = vaddw_u8(columns7, vget_high_u8(fourth)); + } + // Counted in blocks: 4 per group. + previous = vshlq_n_u32(previous, 2); + for(; blocks != 0; --blocks, data += block_size) { + uint8x16_t const value = vld1q_u8(data); + previous = vaddq_u32(previous, sum); + sum = vpadalq_u16(sum, vpaddlq_u8(value)); + columns6 = vaddw_u8(columns6, vget_low_u8(value)); + columns7 = vaddw_u8(columns7, vget_high_u8(value)); + } + auto const add_weighted = [](uint32x4_t total, uint16x8_t columns, std::uint16_t const *column_weights) { + uint16x8_t const weight = vld1q_u16(column_weights); + total = vmlal_u16(total, vget_low_u16(columns), vget_low_u16(weight)); + return vmlal_u16(total, vget_high_u16(columns), vget_high_u16(weight)); + }; + uint32x4_t weighted = vmull_u16(vget_low_u16(columns0), vget_low_u16(vld1q_u16(weights.data()))); + weighted = vmlal_u16(weighted, vget_high_u16(columns0), vget_high_u16(vld1q_u16(weights.data()))); + weighted = add_weighted(weighted, columns1, weights.data() + 8); + weighted = add_weighted(weighted, columns2, weights.data() + 16); + weighted = add_weighted(weighted, columns3, weights.data() + 24); + weighted = add_weighted(weighted, columns4, weights.data() + 32); + weighted = add_weighted(weighted, columns5, weights.data() + 40); + weighted = add_weighted(weighted, columns6, weights.data() + 48); + weighted = add_weighted(weighted, columns7, weights.data() + 56); + return {.sum = lane_total(sum), .weighted = (block_size * lane_total(previous)) + lane_total(weighted)}; +} +#endif + // As for bytes, with 8 values per block and 32-bit column sums. inline chunk_sums kernel<16>::sum(std::byte const *data, std::size_t blocks) noexcept { static constexpr std::array weights{8, 7, 6, 5, 4, 3, 2, 1}; diff --git a/src/include_private/checksum_private/fletcher_loops.hpp b/src/include_private/checksum_private/fletcher_loops.hpp index 19c3078..99ce73c 100644 --- a/src/include_private/checksum_private/fletcher_loops.hpp +++ b/src/include_private/checksum_private/fletcher_loops.hpp @@ -49,7 +49,7 @@ template Value load(std::byte const *data) noexcept; // Adds the whole kernel blocks at the start of data to the sums of state, a chunk of at most max_blocks blocks per kernel call, each sum // reduced after every chunk. Returns the number of bytes taken; inlined into its one caller. -template +template [[gnu::always_inline]] inline std::size_t sum_chunks(State &state, std::span data) noexcept; // The portable loop over the whole Values of data. @@ -57,9 +57,14 @@ template [[gnu::always_inline]] inline State sum_portable(State state, std::span data) noexcept; // The CPU kernel, then the portable loop over what it left. Not inlined, so that short inputs run sum_portable() without a call. +// From the minimum size of group_kernel, a tail call to sum_groups() instead. template [[gnu::noinline, maybe_unused]] State sum_long(State state, std::span data) noexcept; +// group_kernel, then the portable loop. A separate function, so that its registers cost sum_long() nothing. +template +[[gnu::noinline, maybe_unused]] State sum_groups(State state, std::span data) noexcept; + // Whether size bytes go to sum_long(): from the minimum size of the kernel, if there is one. Callers branch on it themselves, // so that the call of sum_long() stays a tail call. template constexpr bool runs_kernel(std::size_t size) noexcept; @@ -122,10 +127,10 @@ template Value load(std::byte const *data) noexcept { } } -template +template [[gnu::always_inline]] inline std::size_t sum_chunks(State &state, std::span data) noexcept { constexpr unsigned bits = std::numeric_limits::digits; - using chunk_kernel = kernel; + using chunk_kernel = Kernel; constexpr std::uint64_t values_per_block = chunk_kernel::block_size / sizeof(Value); constexpr std::uint64_t max_values = chunk_kernel::max_blocks * values_per_block; constexpr std::uint64_t largest_value = std::numeric_limits::max(); @@ -259,13 +264,25 @@ template template [[gnu::noinline, maybe_unused]] State sum_long(State state, std::span data) noexcept { + constexpr unsigned bits = std::numeric_limits::digits; + if constexpr(group_kernel::available) { + if(data.size() >= group_kernel::minimum_size) { + return sum_groups(state, data); + } + } std::size_t size = 0; - if constexpr(kernel::digits>::available) { - size = sum_chunks(state, data); + if constexpr(kernel::available) { + size = sum_chunks, Value, Modulus>(state, data); } return sum_portable(state, data.subspan(size)); } +template +[[gnu::noinline, maybe_unused]] State sum_groups(State state, std::span data) noexcept { + std::size_t const size = sum_chunks::digits>, Value, Modulus>(state, data); + return sum_portable(state, data.subspan(size)); +} + template constexpr bool runs_kernel(std::size_t size) noexcept { using value_kernel = kernel::digits>; return value_kernel::available && size >= value_kernel::minimum_size; diff --git a/src/include_private/checksum_private/generic/fletcher.hpp b/src/include_private/checksum_private/generic/fletcher.hpp index 05ed353..312f1d0 100644 --- a/src/include_private/checksum_private/generic/fletcher.hpp +++ b/src/include_private/checksum_private/generic/fletcher.hpp @@ -2,7 +2,7 @@ #define CHECKSUM_PRIVATE_GENERIC_FLETCHER_HPP // No kernel for values of Bits bits: the portable loop sums everything. Every architecture header includes it and -// specializes kernel for the value sizes it accelerates. +// specializes kernel, and group_kernel where it has one, for the value sizes it accelerates. #include #include @@ -14,6 +14,12 @@ template struct kernel { static constexpr std::size_t minimum_size = std::numeric_limits::max(); }; +// A second kernel with the interface of kernel, for long inputs only: from its minimum_size it runs instead of kernel. +template struct group_kernel { + static constexpr bool available = false; + static constexpr std::size_t minimum_size = std::numeric_limits::max(); +}; + } // namespace checksum::fletcher_detail #endif // CHECKSUM_PRIVATE_GENERIC_FLETCHER_HPP diff --git a/tests/unit_tests/ut_adler32.cpp b/tests/unit_tests/ut_adler32.cpp index 72eca40..7526efe 100644 --- a/tests/unit_tests/ut_adler32.cpp +++ b/tests/unit_tests/ut_adler32.cpp @@ -78,8 +78,8 @@ TEST(adler32, chunk_boundaries) { std::vector const ones((2 * largest_chunk) + 64, std::byte{0xFF}); auto const random = random_bytes(ones.size(), 7); for(auto const &data : {ones, random}) { - for(std::size_t const chunk : - {std::size_t{1024}, std::size_t{2048}, std::size_t{4096}, std::size_t{5600}, std::size_t{16} << 10U, std::size_t{32} << 10U, largest_chunk}) { + for(std::size_t const chunk : {std::size_t{1024}, std::size_t{2048}, std::size_t{4096}, std::size_t{5600}, std::size_t{5760}, + std::size_t{16} << 10U, std::size_t{32} << 10U, largest_chunk}) { for(std::size_t const size : {chunk - 1, chunk, chunk + 1, chunk + 35, (2 * chunk) + 35}) { for(std::size_t offset = 0; offset < 4; ++offset) { auto const message = std::span(data).subspan(offset, size); diff --git a/tests/unit_tests/ut_fletcher.cpp b/tests/unit_tests/ut_fletcher.cpp index 1b39900..e3ca2e4 100644 --- a/tests/unit_tests/ut_fletcher.cpp +++ b/tests/unit_tests/ut_fletcher.cpp @@ -120,8 +120,8 @@ TYPED_TEST(fletcher, chunk_boundaries) { std::vector const ones((2 * largest_chunk) + 64, std::byte{0xFF}); auto const random = random_bytes(ones.size(), 7); for(auto const &data : {ones, random}) { - for(std::size_t const chunk : - {std::size_t{1024}, std::size_t{2048}, std::size_t{4096}, std::size_t{5600}, std::size_t{16} << 10U, std::size_t{32} << 10U, largest_chunk}) { + for(std::size_t const chunk : {std::size_t{1024}, std::size_t{2048}, std::size_t{4096}, std::size_t{5600}, std::size_t{5760}, + std::size_t{16} << 10U, std::size_t{32} << 10U, largest_chunk}) { for(std::size_t const size : {chunk - 1, chunk, chunk + 1, chunk + 35, (2 * chunk) + 35}) { for(std::size_t offset = 0; offset < 4; ++offset) { auto const message = std::span(data).subspan(offset, size); From 5e301563ab06ef1cdbbd0d1ec3117780f6807500 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:10:51 +0200 Subject: [PATCH 60/64] perf(fletcher, adler32): short inputs without store-forwarding stalls GCC returned small states by storing their members one by one and loading them as one word. The sums are now built in one integer, Fletcher-16/-32 pass their state to sum_loop() as one integer, unfinished blocks go to a separate function, 64-bit Fletcher sums reduce with a constant %, and AArch64 sums 16-bit values in 32 bits. Against a plain deferred-modulo loop at 20 bytes: Fletcher-16 0.68 -> 0.94x and Fletcher-32 0.51 -> 0.86x on x86-64, Fletcher-32 0.52 -> 0.88x on the Cortex-A72. --- src/fletcher/sum_loop.cpp | 72 ++++++++++++++++--- src/include/checksum/fletcher.hpp | 38 ++++++++-- .../checksum_private/fletcher_loops.hpp | 70 ++++++++++++++++-- 3 files changed, 162 insertions(+), 18 deletions(-) diff --git a/src/fletcher/sum_loop.cpp b/src/fletcher/sum_loop.cpp index 0322388..ae8c1bc 100644 --- a/src/fletcher/sum_loop.cpp +++ b/src/fletcher/sum_loop.cpp @@ -5,20 +5,60 @@ #include #include +#include #include namespace checksum::fletcher_detail { namespace { +// The whole blocks of data with the shared loops, from the start of a block. +template +[[gnu::always_inline]] inline fletcher_state sum_blocks(fletcher_state state, std::span data) noexcept; + // update_bytes() out of line, so that the byte loop takes no registers from the block loops. -template [[gnu::noinline]] fletcher_state add_bytes(fletcher_state state, std::span data) noexcept { +template [[gnu::noinline]] fletcher_state add_bytes(fletcher_state state, std::span data) noexcept; + +// Finishes an unfinished block byte by byte, sums the whole blocks, and adds the bytes of a last unfinished block to sum1, +// with the byte loops out of line: for Fletcher-64 and on 32-bit targets, inside sum_any(). +template +[[gnu::always_inline]] inline fletcher_state sum_mixed(fletcher_state state, std::span data) noexcept; + +// The same out of line, with the byte loops inline: Fletcher-16 and -32 on 64-bit targets. +template [[gnu::noinline]] state_word sum_unfinished(state_word word, std::span data) noexcept; + +// Whole blocks from the start of a block go to sum_blocks() here, everything else to sum_unfinished(), so that this path +// makes no call that needs a frame. +template state_word sum_any(state_word word, std::span data) noexcept; + +template fletcher_state sum_blocks(fletcher_state state, std::span data) noexcept { + using sum_type = fletcher_state::sum_type; + sum_pair const sums{.sum1 = state.sum1, .sum2 = state.sum2}; + sum_pair const result = + runs_kernel(data.size()) ? sum_long>(sums, data) : sum_portable>(sums, data); + return make_state>(result.sum1, result.sum2); +} + +template fletcher_state add_bytes(fletcher_state state, std::span data) noexcept { return update_bytes(state, data); } -// Finishes an unfinished block byte by byte, sums the whole blocks with the shared loops, and adds the bytes of a last -// unfinished block to sum1. The byte loop runs only where there are such bytes. -template fletcher_state sum_any(fletcher_state state, std::span data) noexcept { +template state_word sum_unfinished(state_word word, std::span data) noexcept { + constexpr unsigned size = block_size; + fletcher_state state = from_word(word); + if(state.block_offset % size != 0) { + std::size_t const head = std::min(data.size(), size - (state.block_offset % size)); + state = update_bytes(state, data.first(head)); + if(state.block_offset != 0) { + return to_word(state); + } + data = data.subspan(head); + } + std::size_t const whole = data.size() - (data.size() % size); + return to_word(update_bytes(sum_blocks(state, data.first(whole)), data.subspan(whole))); +} + +template fletcher_state sum_mixed(fletcher_state state, std::span data) noexcept { using sum_type = fletcher_state::sum_type; constexpr unsigned size = block_size; sum_pair sums{.sum1 = state.sum1, .sum2 = state.sum2}; @@ -35,17 +75,33 @@ template fletcher_state sum_any(fletcher_state st runs_kernel(data.size()) ? sum_long>(sums, data) : sum_portable>(sums, data); std::size_t const tail = data.size() % size; if(tail == 0) { - return {.sum1 = result.sum1, .sum2 = result.sum2, .block_offset = 0}; + return make_state>(result.sum1, result.sum2); } return add_bytes({.sum1 = result.sum1, .sum2 = result.sum2, .block_offset = 0}, data.last(tail)); } +template state_word sum_any(state_word word, std::span data) noexcept { + constexpr unsigned size = block_size; + if constexpr(Width == 64) { + // Its state passes as it is; out of line, unfinished blocks cost Fletcher-64 3-8 % on the Cortex-A72. + return sum_mixed(word, data); + } else if constexpr(sizeof(std::size_t) < sizeof(std::uint64_t)) { + // 32-bit targets lost 4-10 % with unfinished blocks out of line. + return to_word(sum_mixed(from_word(word), data)); + } + fletcher_state const state = from_word(word); + if(state.block_offset % size != 0 || data.size() % size != 0) { + return sum_unfinished(word, data); + } + return to_word(sum_blocks(state, data)); +} + } // namespace -fletcher_state<16> sum_loop(fletcher_state<16> state, std::span data) noexcept { return sum_any(state, data); } +state_word<16> sum_loop(state_word<16> state, std::span data) noexcept { return sum_any<16>(state, data); } -fletcher_state<32> sum_loop(fletcher_state<32> state, std::span data) noexcept { return sum_any(state, data); } +state_word<32> sum_loop(state_word<32> state, std::span data) noexcept { return sum_any<32>(state, data); } -fletcher_state<64> sum_loop(fletcher_state<64> state, std::span data) noexcept { return sum_any(state, data); } +state_word<64> sum_loop(state_word<64> state, std::span data) noexcept { return sum_any<64>(state, data); } } // namespace checksum::fletcher_detail diff --git a/src/include/checksum/fletcher.hpp b/src/include/checksum/fletcher.hpp index 1fc1646..4e30812 100644 --- a/src/include/checksum/fletcher.hpp +++ b/src/include/checksum/fletcher.hpp @@ -107,10 +107,18 @@ template constexpr integer reduce_once(integer va // Folds data byte by byte; the constant-evaluation loop, also used at run time for the bytes of an unfinished block. template constexpr fletcher_state update_bytes(fletcher_state state, std::span data) noexcept; +// The state of Fletcher-16 and Fletcher-32 as one integer, sum1, sum2 and block_offset from the low bits in Width/2 bits each, +// so that compilers pass it in a register; Fletcher-64 passes the state itself. +template +using state_word = std::conditional_t>>; + +template constexpr state_word to_word(fletcher_state state) noexcept; +template constexpr fletcher_state from_word(state_word word) noexcept; + // The same fold at run time, defined in src/fletcher/sum_loop.cpp. -fletcher_state<16> sum_loop(fletcher_state<16> state, std::span data) noexcept; -fletcher_state<32> sum_loop(fletcher_state<32> state, std::span data) noexcept; -fletcher_state<64> sum_loop(fletcher_state<64> state, std::span data) noexcept; +state_word<16> sum_loop(state_word<16> state, std::span data) noexcept; +state_word<32> sum_loop(state_word<32> state, std::span data) noexcept; +state_word<64> sum_loop(state_word<64> state, std::span data) noexcept; } // namespace checksum::fletcher_detail @@ -123,6 +131,28 @@ template constexpr integer reduce_once(integer va return value >= modulus ? static_cast>(value - modulus) : value; } +template constexpr state_word to_word(fletcher_state state) noexcept { + if constexpr(Width == 64) { + return state; + } else { + constexpr unsigned bits = Width / 2; + return static_cast>(state.sum1 | (state_word{state.sum2} << bits) | + (state_word{state.block_offset} << (2 * bits))); + } +} + +template constexpr fletcher_state from_word(state_word word) noexcept { + if constexpr(Width == 64) { + return word; + } else { + using sum_type = fletcher_state::sum_type; + constexpr unsigned bits = Width / 2; + return {.sum1 = static_cast(word), + .sum2 = static_cast(word >> bits), + .block_offset = static_cast(word >> (2 * bits))}; + } +} + template constexpr fletcher_state update_bytes(fletcher_state state, std::span data) noexcept { using sum_type = fletcher_state::sum_type; integer sum1 = reduce_once(state.sum1); @@ -146,7 +176,7 @@ template constexpr fletcher_state fletcher_update(fletch if consteval { return fletcher_detail::update_bytes(state, data); } else { - return fletcher_detail::sum_loop(state, data); + return fletcher_detail::from_word(fletcher_detail::sum_loop(fletcher_detail::to_word(state), data)); } } diff --git a/src/include_private/checksum_private/fletcher_loops.hpp b/src/include_private/checksum_private/fletcher_loops.hpp index 99ce73c..404a9c6 100644 --- a/src/include_private/checksum_private/fletcher_loops.hpp +++ b/src/include_private/checksum_private/fletcher_loops.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +29,12 @@ template struct sum_pair { // NOLINTNEXTLINE(misc-anonymous-namespace-in-header): a private header, included only by src/fletcher and src/adler32. namespace { +#if defined(__aarch64__) +inline constexpr bool narrow_value_sums = true; +#else +inline constexpr bool narrow_value_sums = false; +#endif + // Largest n with (n + 1)(Modulus - 1) + largest_value * n(n + 1) / 2 <= the maximum of Integer: sums below Modulus stay within // Integer while they add n values of at most largest_value, sum2 after each. template constexpr std::size_t values_per_reduction(std::uint64_t largest_value) noexcept; @@ -44,6 +51,10 @@ template Word reduce_chunk(Word value) noexc // and elsewhere load single bytes instead of calling memcpy. template Value load(std::byte const *data) noexcept; +// A sum_pair, adler32_state or fletcher_state with these sums and any other member 0. GCC returns a small aggregate by storing +// its members one by one and reloading them as one word, which stalls store forwarding; a copy of one integer does not. +template State make_state(std::uint64_t sum1, std::uint64_t sum2) noexcept; + // The loops take and return a sum_pair or an adler32_state, which has the same members: sums below 2 * Modulus in, below // Modulus out. @@ -127,6 +138,24 @@ template Value load(std::byte const *data) noexcept { } } +template State make_state(std::uint64_t sum1, std::uint64_t sum2) noexcept { + using sum_type = decltype(State::sum1); + constexpr unsigned bits = std::numeric_limits::digits; + if constexpr(sizeof(State) <= sizeof(std::size_t) && (std::endian::native == std::endian::little || std::endian::native == std::endian::big)) { + // The bytes of State from one integer: sum1 at the lowest address, then sum2, the rest 0. + static_assert(offsetof(State, sum1) == 0 && offsetof(State, sum2) == sizeof(sum_type)); + constexpr std::uint64_t mask = (std::uint64_t{1} << bits) - 1; + std::uint64_t const low_first = (sum1 & mask) | ((sum2 & mask) << bits); + std::uint64_t const high_first = ((sum1 & mask) << (64 - bits)) | ((sum2 & mask) << (64 - (2 * bits))); + std::uint64_t const word = std::endian::native == std::endian::little ? low_first : high_first; + State state; + std::memcpy(static_cast(&state), &word, sizeof(State)); + return state; + } else { + return {.sum1 = static_cast(sum1), .sum2 = static_cast(sum2)}; + } +} + template [[gnu::always_inline]] inline std::size_t sum_chunks(State &state, std::span data) noexcept { constexpr unsigned bits = std::numeric_limits::digits; @@ -179,8 +208,10 @@ template template [[gnu::always_inline]] inline State sum_portable(State state, std::span data) noexcept { - // The widest integer the target adds natively, or 64 bits for 32-bit values. - using accumulator = std::conditional_t; + // The widest integer the target adds natively, or 64 bits for 32-bit values. AArch64 sums 16-bit values in 32 bits: + // Fletcher-32 at 20 bytes ran 6 % faster on a Cortex-A72 (a reduction every 360 values costs little), but 9 % slower on x86-64. + using accumulator = + std::conditional_t>; // 32-bit targets sum 16-bit values as 32-bit words, two values each; 64-bit targets keep the 4-value formula on native words. constexpr bool sums_words = sizeof(Value) == 2 && std::numeric_limits::digits == 32; constexpr std::size_t size = sizeof(Value); @@ -232,7 +263,11 @@ template } else { // Four values at a time: sum1 has one addition per group in its dependency chain instead of four. With 64-bit sums on a // 32-bit target the multiplications cost more than the chain, so the values are added one by one. - for(; count >= 4; count -= 4, position += 4 * size) { + // 64-bit targets bound the loop by its end, which made Fletcher-32 at 20 bytes faster on x86-64; on a Cortex-M4 that cost + // Fletcher-64 3 % at 4 KiB, so 32-bit targets count the values. + constexpr bool bounded_by_end = std::numeric_limits::digits == 64; + std::byte const *const end = position + ((count / 4) * 4 * size); + for(; bounded_by_end ? position != end : count >= 4; position += 4 * size, count -= bounded_by_end ? 0 : 4) { accumulator const first = load(position); accumulator const second = load(position + size); accumulator const third = load(position + (2 * size)); @@ -251,15 +286,38 @@ template sum1 += first + second + third + fourth; } } + count %= 4; + if constexpr(std::numeric_limits::digits == 64) { + if((count & 2U) != 0) { + accumulator const first = load(position); + accumulator const second = load(position + size); + sum2 += (2 * sum1) + (2 * first) + second; + sum1 += first + second; + position += 2 * size; + } + if((count & 1U) != 0) { + sum1 += load(position); + sum2 += sum1; + position += size; + } + count = 0; + } } for(; count != 0; --count, position += size) { sum1 += load(position); sum2 += sum1; } - sum1 = reduce(sum1); - sum2 = reduce(sum2); + if constexpr(sizeof(accumulator) == sizeof(std::uint64_t) && sizeof(std::size_t) == sizeof(std::uint64_t) && std::has_single_bit(Modulus + 1)) { + // A constant % of a 64-bit sum is a multiplication on 64-bit targets: no branches, which the fold loop mispredicted on + // the A72 when the number of folds changed with the input size. 32-bit targets would call a division function. + sum1 %= Modulus; + sum2 %= Modulus; + } else { + sum1 = reduce(sum1); + sum2 = reduce(sum2); + } } - return {.sum1 = static_cast(sum1), .sum2 = static_cast(sum2)}; + return make_state(sum1, sum2); } template From 40042d6b520e5686d23180adcee50f21024a751e Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:10:51 +0200 Subject: [PATCH 61/64] docs(adler32, fletcher): AVX-VNNI and 64-byte NEON kernels, short-input decisions, reference comparison --- .cspell.yml | 4 ++++ doc/adler32.md | 19 +++++++++++++++---- doc/design/acceleration.md | 23 +++++++++++++++++++++-- doc/fletcher.md | 28 +++++++++++++++++++++------- 4 files changed, 61 insertions(+), 13 deletions(-) diff --git a/.cspell.yml b/.cspell.yml index 83614d3..00dc156 100644 --- a/.cspell.yml +++ b/.cspell.yml @@ -241,3 +241,7 @@ words: - zextsi - zmodem - znver +- avxvnni +- dpbusd +- vpdpbusd +- VNNI diff --git a/doc/adler32.md b/doc/adler32.md index e134c18..8d41a54 100644 --- a/doc/adler32.md +++ b/doc/adler32.md @@ -77,9 +77,11 @@ From 64 bytes, Adler-32 runs the byte kernel of Fletcher-16 with modulus 65521: | Target and flags | Kernel | | --- | --- | +| x86-64 with AVX-VNNI (`-mavxvnni`, or a `-march` that includes it, e.g. Alder Lake, Meteor Lake) | `vpdpbusd`, 128 bytes per iteration | | x86-64 with AVX2 (`-mavx2`, or a `-march` that includes it) | 32-byte vectors | | x86-64 without AVX2 (SSE2 is always there; SSSE3 used if enabled) | 16-byte vectors | -| AArch64 and 32-bit Arm with NEON, little-endian | NEON, 16-byte vectors | +| AArch64 with NEON, little-endian | NEON, 16-byte vectors; from 320 bytes 64 bytes per iteration | +| 32-bit Arm with NEON, little-endian | NEON, 16-byte vectors | | Little-endian M-profile Arm with the DSP extension (Cortex-M4/M7/M33) | `usada8` + `smlad`, 8 bytes per iteration | | everything else, or `CHECKSUM_ACCELERATION=OFF` | portable loop | @@ -92,7 +94,15 @@ evaluation always runs a byte-by-byte loop with the same result. The measurement ### 6.1 x86-64: Core Ultra 7 155H GCC 16, 4 KiB, measured on a loaded host: 7 365 MB/s (10⁶ bytes per second) for the portable loop, 54 211 MB/s with -the AVX2 kernel, 7.4× faster. +the AVX2 kernel, 7.4× faster. With `-march=native` the AVX-VNNI kernel runs (MB/s, GCC 16 and Clang 21): + +| Input | 20 B | 64 B | 256 B | 1500 B | 4 KiB | 1 MiB | +| --- | --- | --- | --- | --- | --- | --- | +| GCC | 3 441 | 10 846 | 33 317 | 55 254 | 85 045 | 89 051 | +| Clang | 3 420 | 10 542 | 34 390 | 54 459 | 83 602 | 90 845 | + +Against zlib-ng (develop, its AVX-VNNI kernel, same flags) that is 0.98× at 20 B, 0.78× at 64 B, 0.91× at 256 B and +1.13-1.17× from 4 KiB; the AVX2 kernel reached 0.71-0.83× there. ### 6.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz @@ -101,11 +111,12 @@ GCC 14.3, `-O2`, one core, start address aligned. GiB/s: | Build | 64 B | 256 B | 1500 B | 4 KiB | | --- | --- | --- | --- | --- | | AArch64 portable | 0.68 | 0.77 | 0.83 | 0.84 | -| AArch64 NEON | 1.15 | 2.59 | 3.79 | 4.39 | +| AArch64 NEON | 1.13 | 2.62 | 4.79 | 5.84 | | AArch32 portable | 0.52 | 0.71 | 0.85 | 0.86 | | AArch32 NEON | 0.98 | 2.44 | 3.75 | 4.32 | -NEON is about 5× faster at 4 KiB and 1.7-1.9× at 64 bytes. +NEON is 5-7× faster at 4 KiB and 1.7-1.9× at 64 bytes. On AArch64, from 320 bytes the kernel sums 64 bytes per +iteration: 0.96-0.99× zlib-ng and ISA-L from 1500 B, where 16 bytes per iteration reached 0.72-0.79×. ### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index 45e2c97..c8a9b18 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -164,11 +164,13 @@ x86-64 at 4 KiB with GCC, but only 0.84 GiB/s on a Cortex-A72 and 5.3 cycles per | Target | Verdict | Why | | --- | --- | --- | +| x86-64 AVX-VNNI | Yes, bytes from 64 B | `vpdpbusd` weights 32 bytes in one instruction instead of `pmaddubsw` + `pmaddwd` + add; four blocks per iteration weigh 127 .. 0 against one `previous` addition. Adler-32 at 4 KiB: 85 045 MB/s against 56 382 for the AVX2 kernel (1.5×), 1.13× zlib-ng's AVX-VNNI kernel. Not in a test preset: QEMU has no AVX-VNNI and GitHub runners may lack it, so it is tested locally with `-march=native`. | | x86-64 AVX2 | Yes: bytes from 64 B, 16-bit values from 128 B, 32-bit values from 384 B | At 4 KiB with GCC, 7.4× the portable loop for Fletcher-16 and Adler-32, 3.3× for Fletcher-32, 2.0× for Fletcher-64. | | x86-64 SSE2 (baseline), SSSE3 | Yes, bytes and 16-bit values | Fletcher-16 3.1× and Fletcher-32 1.5× the portable loop at 4 KiB with GCC. SSSE3 `pmaddubsw` weights 16 bytes in two instructions; plain SSE2 widens the bytes first. | | x86-64 SSE2, 32-bit values | Not done | The 64-bit portable loop of Fletcher-64 already runs 26 900 MB/s at 4 KiB. | | x86-64 AVX-512 | Not measured | No AVX-512 hardware available. | -| AArch64 NEON | Yes: bytes from 64 B, 16-bit from 128 B, 32-bit from 256 B | Cortex-A72 at 4 KiB: about 5× for Fletcher-16 and Adler-32, 2.8× for Fletcher-32, 1.45× for Fletcher-64, whose 64-bit portable loop is already fast. | +| AArch64 NEON | Yes: bytes from 64 B, 16-bit from 128 B, 32-bit from 256 B | Cortex-A72 at 4 KiB: about 7× for Fletcher-16 and Adler-32, 2.8× for Fletcher-32, 1.45× for Fletcher-64, whose 64-bit portable loop is already fast. | +| AArch64 NEON, 64 bytes per iteration (`group_kernel`) | Yes, bytes from 320 B | Pairwise additions of four blocks into `sum`, 64 column sums weighted 64 .. 1, one `previous` addition per 64 bytes, as zlib-ng: Adler-32 at 4 KiB 6 270 against 4 746 MB/s (1.32×), 0.96× zlib-ng and ISA-L. Below 320 B weighting 64 columns costs more than it saves. In AArch32 (16 NEON registers) it spilled and lost 10-27 %. | | 32-bit Arm NEON, little-endian | Yes, the same kernels and thresholds | A72 in AArch32 at 4 KiB: 5.0× for Fletcher-16 and Adler-32, 2.9× for Fletcher-32, 3.0× for Fletcher-64. | | M-profile Arm DSP (Cortex-M4/M7/M33), bytes | Yes, from 64 B | `usada8` sums 4 bytes, `uxtb16` + `smlad` weight them: 2.69 cycles per byte against 5.30 on a Cortex-M4 (nRF52840 and STM32L4A6), 2.0× at 4 KiB, 1.6× at 256 B. | | M-profile Arm DSP, 16-bit and 32-bit values | No | The portable loop sums 32-bit words on 32-bit targets: 2.11 cycles per byte for Fletcher-32 and 1.80 for Fletcher-64, within 2 % of a DSP kernel of the same scheme. | @@ -188,7 +190,24 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cor - The chunk sums are reduced in 32-bit arithmetic wherever every intermediate result fits, with the high half of a 64-bit value folded with the weight 2^32 modulo M, so the modulo is a 32-bit operation on every target. - The kernel and the portable loop after it sit in a separate non-inlined function, as for the Internet checksum, so - inputs below the threshold run without a call. + inputs below the threshold run without a call. `group_kernel` has its own such function, reached by a tail call: + inside the same function its registers slowed the 16-byte kernel by 10-15 % at 64-256 B. +- The 64-byte NEON kernel takes chunks of 360 blocks, so the weighted sum of a chunk fits 32 bits and the chunk loop + stays in 32-bit arithmetic; with 1016 blocks it went to 64 bits and cost 15 % at 64 B. +- Short inputs, against a plain deferred-modulo loop (the Wikipedia one), at 20 bytes with GCC on x86-64: + - GCC returned a small aggregate by storing its members one by one and loading them as one word, which stalls store + forwarding. The sums are built in one integer and copied (`make_state()`), and Fletcher-16 and -32 pass their + state to `sum_loop()` as one integer (`state_word`): Fletcher-16 0.68 to 0.94×, Fletcher-32 0.51 to 0.86×. + - Unfinished blocks go to a separate non-inlined function, so the whole-block path needs no frame; there the byte + loops are inline. Fletcher-64, whose state passes in two registers, and 32-bit targets lost 3-10 % that way and + keep them in `sum_any()`, with out-of-line byte loops. + - The portable loop ends with straight-line steps of 2 and 1 values on 64-bit targets, and bounds its 4-value loop by + a pointer; on the Cortex-M4 the pointer cost Fletcher-64 3 % at 4 KiB, so 32-bit targets count. + - On 64-bit targets the Fletcher moduli reduce 64-bit sums with a constant `%`, a multiplication: the fold loop's + branches made Fletcher-32 on the A72 swing between 0.55 and 0.85× of the reference with the input size. Adler-32 + keeps the fold, which was 5-10 % faster for 65521, and 32-bit targets would call a division function. + - AArch64 sums 16-bit values in 32-bit sums: Fletcher-32 at 20 B 0.80 to 0.86× on the A72; on x86-64 it was 9 % + slower, so x86-64 keeps 64-bit sums. - The DSP kernel sums single bytes up to a 4-byte aligned address first: word loads from other addresses made the Cortex-M4 loop 15-25 % slower. From an odd address it takes 2.71 cycles per byte against 2.69. - The DSP kernel is not inlined into the chunk loop: there GCC reloaded two weights in every iteration. diff --git a/doc/fletcher.md b/doc/fletcher.md index 51fcc83..02e0691 100644 --- a/doc/fletcher.md +++ b/doc/fletcher.md @@ -91,16 +91,18 @@ a length keep the state instead. Fletcher-16 continues after any length. The portable loop adds blocks into the widest native integer and reduces modulo M only when an overflow could otherwise happen: on 64-bit targets after 380 million bytes for Fletcher-16, on 32-bit targets after 5 802 bytes. It adds four blocks per step, so `sum1` has one addition per four blocks in its dependency chain. On 32-bit targets -Fletcher-32 sums 32-bit words, two blocks at a time. +Fletcher-32 sums 32-bit words, two blocks at a time; on AArch64 it sums its 16-bit blocks in 32-bit sums, reduced every +360 blocks. From a minimum size, a kernel sums whole vectors of blocks. It returns the sum of the blocks and their weighted sum, and `sum2` gains both at the end of each chunk, 2 KiB to 256 KiB depending on the kernel. | Target and flags | Fletcher-16 | Fletcher-32 | Fletcher-64 | | --- | --- | --- | --- | +| x86-64 with AVX-VNNI (`-mavxvnni`, or a `-march` that includes it) | `vpdpbusd`, 128 bytes per iteration, from 64 B | as AVX2 | as AVX2 | | x86-64 with AVX2 (`-mavx2`, or a `-march` that includes it) | 32-byte vectors, from 64 B | from 128 B | from 384 B | | x86-64 without AVX2 (SSE2 is always there; SSSE3 used if enabled) | 16-byte vectors, from 64 B | from 128 B | portable loop | -| AArch64, little-endian | NEON, from 64 B | from 128 B | from 256 B | +| AArch64, little-endian | NEON, from 64 B; 64 bytes per iteration from 320 B | from 128 B | from 256 B | | 32-bit Arm with NEON, little-endian | NEON, from 64 B | from 128 B | from 256 B | | Little-endian M-profile Arm with the DSP extension (Cortex-M4/M7/M33) | `usada8` + `smlad`, from 64 B | portable loop | portable loop | | everything else (Cortex-M0/M3, A-profile 32-bit Arm without NEON, big-endian, RISC-V), or `CHECKSUM_ACCELERATION=OFF` | portable loop | portable loop | portable loop | @@ -124,6 +126,17 @@ Portable is the library without kernels, SSE2 the default x86-64 flags, AVX2 a b | Fletcher-64 | 26 853 | | 52 801 | 13 065 | 54 881 | The AVX2 kernels are 7.4× (Fletcher-16), 3.3× (Fletcher-32) and 2.0× (Fletcher-64) faster than the GCC portable loop. +With `-march=native` (AVX-VNNI), GCC 16, MB/s: + +| Checksum | 20 B | 64 B | 256 B | 1500 B | 4 KiB | 1 MiB | +| --- | --- | --- | --- | --- | --- | --- | +| Fletcher-16 | 3 094 | 9 959 | 31 780 | 54 938 | 81 283 | 90 798 | +| Fletcher-32 | 3 972 | 7 739 | 21 029 | 37 057 | 49 934 | 51 822 | +| Fletcher-64 | 3 920 | 9 423 | 18 352 | 37 030 | 49 787 | 59 639 | + +At 20 bytes the plain deferred-modulo loop of the Wikipedia article (`-O2 -march=native`) runs 3 300 MB/s for +Fletcher-16 and 4 600 for Fletcher-32: 0.94× and 0.86× for the library, which needs the state and its unfinished +block on top. ### 6.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz @@ -131,13 +144,14 @@ GCC 14.3, `-O2`, one core. GiB/s at 64 B / 256 B / 1500 B / 4 KiB, start address | Checksum | AArch64 portable | AArch64 NEON | AArch32 portable | AArch32 NEON | | --- | --- | --- | --- | --- | -| Fletcher-16 | 0.62 / 0.74 / 0.83 / 0.84 | 0.84 / 2.19 / 3.60 / 4.24 | 0.57 / 0.73 / 0.82 / 0.84 | 0.82 / 2.13 / 3.58 / 4.23 | -| Fletcher-32 | 0.98 / 1.42 / 1.61 / 1.67 | 0.98 / 2.32 / 4.16 / 4.75 | 0.78 / 1.37 / 1.56 / 1.65 | 0.80 / 2.37 / 4.09 / 4.74 | -| Fletcher-64 | 1.46 / 2.71 / 3.36 / 3.56 | 1.40 / 2.68 / 4.40 / 5.17 | 0.91 / 1.40 / 1.61 / 1.67 | 0.90 / 2.30 / 4.10 / 5.06 | +| Fletcher-16 | 0.62 / 0.74 / 0.83 / 0.84 | 0.96 / 2.38 / 4.67 / 5.75 | 0.57 / 0.73 / 0.82 / 0.84 | 0.82 / 2.13 / 3.58 / 4.23 | +| Fletcher-32 | 0.98 / 1.42 / 1.61 / 1.67 | 1.09 / 2.57 / 4.27 / 4.78 | 0.78 / 1.37 / 1.56 / 1.65 | 0.80 / 2.37 / 4.09 / 4.74 | +| Fletcher-64 | 1.46 / 2.71 / 3.36 / 3.56 | 1.41 / 2.85 / 4.41 / 5.16 | 0.91 / 1.40 / 1.61 / 1.67 | 0.90 / 2.30 / 4.10 / 5.06 | -At 4 KiB NEON is 5.0× faster for Fletcher-16, 2.8-2.9× for Fletcher-32, and 1.45× (AArch64) or 3.0× (AArch32) for +At 4 KiB NEON is 5.0× (AArch32) to 6.8× (AArch64, 64 bytes per iteration) faster for Fletcher-16, 2.8-2.9× for Fletcher-32, and 1.45× (AArch64) or 3.0× (AArch32) for Fletcher-64, whose 64-bit portable loop is already fast on AArch64. Below the thresholds both builds run the portable -loop; the differences there come from code layout. +loop; the differences there come from code layout. At 20 bytes AArch64 Fletcher-32 runs 592 MB/s, 0.88× the Wikipedia +loop (675). ### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz From e7bc4801244bf0742aa08eb74c15c5890f7e44d4 Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 23:45:10 +0200 Subject: [PATCH 62/64] docs: bring the guides in line with the gap fixes --- doc/adler32.md | 7 ++- doc/design/acceleration.md | 43 +++++++++++-------- doc/design/testing.md | 5 ++- doc/fletcher.md | 5 ++- doc/internet.md | 30 ++++++------- src/fletcher4/sum_loop.cpp | 4 +- .../checksum_private/crc_arch.hpp | 3 +- .../checksum_private/fletcher_arch.hpp | 2 + .../checksum_private/fletcher_loops.hpp | 2 +- .../checksum_private/x86_64/fletcher.hpp | 4 +- .../checksum_private/x86_64/fletcher4.hpp | 2 +- 11 files changed, 60 insertions(+), 47 deletions(-) diff --git a/doc/adler32.md b/doc/adler32.md index 8d41a54..d74d5d4 100644 --- a/doc/adler32.md +++ b/doc/adler32.md @@ -94,7 +94,8 @@ evaluation always runs a byte-by-byte loop with the same result. The measurement ### 6.1 x86-64: Core Ultra 7 155H GCC 16, 4 KiB, measured on a loaded host: 7 365 MB/s (10⁶ bytes per second) for the portable loop, 54 211 MB/s with -the AVX2 kernel, 7.4× faster. With `-march=native` the AVX-VNNI kernel runs (MB/s, GCC 16 and Clang 21): +the AVX2 kernel, 7.4× faster (56 382 MB/s in the later run of the table below). The portable figure predates the +current portable loop. With `-march=native` the AVX-VNNI kernel runs (MB/s, GCC 16 and Clang 21): | Input | 20 B | 64 B | 256 B | 1500 B | 4 KiB | 1 MiB | | --- | --- | --- | --- | --- | --- | --- | @@ -116,7 +117,9 @@ GCC 14.3, `-O2`, one core, start address aligned. GiB/s: | AArch32 NEON | 0.98 | 2.44 | 3.75 | 4.32 | NEON is 5-7× faster at 4 KiB and 1.7-1.9× at 64 bytes. On AArch64, from 320 bytes the kernel sums 64 bytes per -iteration: 0.96-0.99× zlib-ng and ISA-L from 1500 B, where 16 bytes per iteration reached 0.72-0.79×. +iteration: 0.96-0.99× zlib-ng and ISA-L from 1500 B, where 16 bytes per iteration reached 0.72-0.79×. The AArch64 +portable row was measured before the current portable loop, which bounds its loop by a pointer; re-measure before +relying on it. ### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index c8a9b18..7bf1e08 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -21,7 +21,8 @@ user guides ([CRC](../crc.md#8-performance), [Internet checksum](../internet.md# - **Constants computed by `constexpr` code** and stored with the tables, so the data layout is the same in every build and named engines stay in read-only data. - **Bit-identical results.** Every accelerated path is tested against the portable one, including in QEMU for each - architecture. Constant evaluation always runs the portable code. + architecture; the x86-64 AVX-VNNI kernel, which QEMU cannot run, is tested locally with `-march=native` on a CPU + that has it. Constant evaluation always runs the portable code. - **Measure before adding.** A kernel stays only if it beats the portable loops on real hardware at the sizes where it runs; thresholds come from measurements. @@ -93,19 +94,22 @@ to beat that, not a byte loop. | Target | Verdict | Why | | --- | --- | --- | -| x86-64 AVX2 | Yes, from 512 B | 64-byte blocks, 32-bit halves summed into 64-bit lanes: 1.6-1.8× the portable loop at 1500 B-4 KiB. The call and the reduction make it slower below about 450 B. | +| x86-64 AVX2 | Yes, from 512 B | 64-byte blocks, 32-bit halves summed into 64-bit lanes: 1.4-1.7× the portable loop from 1500 B. The call and the reduction make it slower below about 450 B. | | x86-64 SSE2 (baseline) | No | The same scheme with 16-byte vectors matched the scalar carry loop and was never faster. | | x86-64 AVX-512 | Not measured | No AVX-512 hardware available; the AVX2 kernel is near the L1 bandwidth, so the gain is likely small. | | Compiler auto-vectorization | No | GCC `-O3 -march=native` vectorizes a 32-bit-word loop to about 47 000 MB/s, below the scalar carry loop; Clang does not vectorize it. | | AArch64 NEON (`uadalp`) | Yes, from 512 B | Cortex-A72: 1.5× at 1500 B, 1.8× at 4 KiB. The 64-bit portable loop is fast (5 400 MB/s at 256 B), so the kernel loses below about 450 B. Eight accumulators (128 B per iteration) were slower than four. | | AArch64 `ldp` + `adcs` assembly | No, for now | 1.3-1.5× the portable loop at 256 B-4 KiB on the A72, better than NEON at 256 B but worse from 1500 B. A second kernel for 256-511 B is not worth the assembly. | | 32-bit Arm NEON | Yes, from 192 B | A72 in AArch32: 4.1× at 4 KiB, where the portable loop runs 32-bit words. | -| 32-bit Arm without NEON (Cortex-M) | Yes, from 192 B, inline assembly | `ldm` + `adcs` chain: 0.70 cycles per byte against 1.27 on a Cortex-M4 (nRF52840 and STM32L4A6): 1.8× at 4 KiB, 1.2× at 256 B, up to 2.5× from an odd address. | +| 32-bit Arm without NEON (Cortex-M) | Yes, from 192 B, inline assembly | `ldm` + `adcs` chain: 0.70 cycles per byte against 1.27 for the earlier portable loop on a Cortex-M4 (nRF52840 and STM32L4A6): 1.8× at 4 KiB, 1.2× at 256 B, up to 2.5× from an odd address. | | Cortex-M0/M0+/M23 (Thumb-1) | Not done | `adcs` and `ldm` exist for low registers, but there is no `teq`: the loop test must not clobber the carry. No hardware to measure. | | Big-endian NEON | No | `vreinterpret` lane order differs between GCC and Clang, as for PMULL; big-endian AArch64 runs the portable loop. | | RISC-V V extension | Implemented, unproven | Widening add `vwaddu.wv` into 64-bit lanes, vector-length agnostic; tested in QEMU with VLEN 128-1024. No hardware measured, so the 64 B threshold is a guess. | | RISC-V scalar (Zba, Zbb) | No | No carry flag: a 64-bit word costs a load and three instructions with or without `add.uw`, the same as the portable loop. | +The Cortex-A72 figures and thresholds above predate the current portable loop, which is 1.1-1.45× faster in AArch64 +and 1.05-1.4× faster in AArch32 up to 256 B; the NEON thresholds have not been re-measured against it. + Cortex-M methods, measured on the nRF52840 and STM32L4A6 (cycles per byte at 4 KiB): | Method | Cycles per byte | Notes | @@ -120,33 +124,34 @@ Cortex-M methods, measured on the nRF52840 and STM32L4A6 (cycles per byte at 4 K | DSP (`uxtah`, `uadd16`, `usada8`) | - | At least two instructions per word, against one `adcs`. | | MCU CRC unit | - | It computes CRCs only. | -What is left on Cortex-M: inputs below 192 bytes run the portable loop, dominated by the call and the final fold (about -125 cycles for 20 bytes). The `ldm` kernel at 192 B (273 cycles) now beats the portable loop at 191 B (345), so its -threshold could move lower. +What is left on Cortex-M: inputs below 192 bytes run the portable loop, dominated by the call and the final fold. In +one harness the current loop takes 125 cycles for 20 bytes against 152 before; at 191 B it takes 345 cycles against +273 for the `ldm` kernel at 192 B, so the threshold could move lower. Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Cortex-M4: nRF52840): -- Two carry chains of 64-bit words: 1.3× one chain at 64 B, 2.6× at 4 KiB. Each chain takes four words per 64-byte - block; on x86-64 `__builtin_addcll` makes it `add` + 3 `adc` + `adc $0` like Linux `csum_partial`, which took - 256 B from 0.84× to 0.97× of that function. GCC 14 on Arm materializes each carry of the builtin, so Arm and the +- Two carry chains of 64-bit words: 1.3× one chain at 64 B, 2.6× at 4 KiB. A four-chain prototype was up to 1.3× + faster again with Clang but 4× slower with GCC, which kept its array in memory; untried with separate variables. + Each chain takes four words per 64-byte block; on x86-64 `__builtin_addcll` makes it `add` + 3 `adc` + `adc $0` + like Linux `csum_partial`, which took 256 B from 0.84× to 0.97× of that function. GCC 14 on Arm materializes each carry of the builtin, so Arm and the other targets keep the carry count (`adds` + `cinc`). Four chains of two words were not faster on x86-64. - The bytes after the last whole word come from one load of the message's last word with the summed bytes masked off, rotated by one byte when the length is odd; with the rotating fold this made 20 B 1.7× faster on the A72 (0.62× to 1.10× Linux `do_csum`, which over-reads instead). Inputs shorter than one word take the 4-, 2- and 1-byte loads before any other branch; behind the word steps they cost 10-13 % at 7 B. Skipping the masked load for whole-word lengths keeps 64-256 B fast. -- `fold()` adds a value to its rotation by half its width, two steps instead of four. A four-chain prototype was up to 1.3× - faster again with Clang but 4× slower with GCC, which kept its array in memory; untried with separate variables. +- `fold()` adds a value to its rotation by half its width, two steps instead of four. - No `memcpy` of variable size for the tail: it called the library function and made a 20-byte input 3.5× slower. - One final fold after the carry chains are merged: three separate folds cost 8-20 % at 20-64 B. - The AVX2 and NEON kernels work in passes of 2^26 blocks (4 GiB), the vector kernel in passes of 2^18 iterations, so their 64-bit lanes never overflow. - The final fold works in the width of the native word: on a Cortex-M4 a 64-bit fold cost 30 cycles of the 150 that - a 20-byte input took. + a 20-byte input took with the earlier portable loop. - `sum_loop()` holds no call for short inputs: the kernel and the loop after it sit in a separate non-inlined function. A call inside `sum_loop()` saved registers on every input and cost 13-23 % below 256 bytes on x86-64; one shared, non-inlined copy of the portable loop saved 100 bytes on a Cortex-M4 but cost 25 % at 20 bytes on x86-64. -- Thresholds are where the kernel overtakes the portable loop of the same build: x86-64 at about 450 bytes, AArch64 at - 450, AArch32 NEON at 150-190, the Cortex-M4 `ldm` kernel at 130-190 depending on the start address. +- Thresholds are where the kernel overtakes the portable loop of the same build, measured against the earlier + portable loop: x86-64 at about 450 bytes, AArch64 at 450, AArch32 NEON at 150-190, the Cortex-M4 `ldm` kernel at + 130-190 depending on the start address. - The `ldm` kernel returns its last carry separately: added back into the 32-bit sum, it would be lost when the sum is 0xFFFFFFFF. @@ -171,7 +176,7 @@ x86-64 at 4 KiB with GCC, but only 0.84 GiB/s on a Cortex-A72 and 5.3 cycles per | x86-64 AVX-512 | Not measured | No AVX-512 hardware available. | | AArch64 NEON | Yes: bytes from 64 B, 16-bit from 128 B, 32-bit from 256 B | Cortex-A72 at 4 KiB: about 7× for Fletcher-16 and Adler-32, 2.8× for Fletcher-32, 1.45× for Fletcher-64, whose 64-bit portable loop is already fast. | | AArch64 NEON, 64 bytes per iteration (`group_kernel`) | Yes, bytes from 320 B | Pairwise additions of four blocks into `sum`, 64 column sums weighted 64 .. 1, one `previous` addition per 64 bytes, as zlib-ng: Adler-32 at 4 KiB 6 270 against 4 746 MB/s (1.32×), 0.96× zlib-ng and ISA-L. Below 320 B weighting 64 columns costs more than it saves. In AArch32 (16 NEON registers) it spilled and lost 10-27 %. | -| 32-bit Arm NEON, little-endian | Yes, the same kernels and thresholds | A72 in AArch32 at 4 KiB: 5.0× for Fletcher-16 and Adler-32, 2.9× for Fletcher-32, 3.0× for Fletcher-64. | +| 32-bit Arm NEON, little-endian | Yes, the same kernels and thresholds except `group_kernel` | A72 in AArch32 at 4 KiB: 5.0× for Fletcher-16 and Adler-32, 2.9× for Fletcher-32, 3.0× for Fletcher-64. | | M-profile Arm DSP (Cortex-M4/M7/M33), bytes | Yes, from 64 B | `usada8` sums 4 bytes, `uxtb16` + `smlad` weight them: 2.69 cycles per byte against 5.30 on a Cortex-M4 (nRF52840 and STM32L4A6), 2.0× at 4 KiB, 1.6× at 256 B. | | M-profile Arm DSP, 16-bit and 32-bit values | No | The portable loop sums 32-bit words on 32-bit targets: 2.11 cycles per byte for Fletcher-32 and 1.80 for Fletcher-64, within 2 % of a DSP kernel of the same scheme. | | A-profile 32-bit Arm without NEON | No | The DSP kernel is slower than the portable loop on the Cortex-A72 in AArch32; only M-profile cores use it. | @@ -193,7 +198,7 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cor inputs below the threshold run without a call. `group_kernel` has its own such function, reached by a tail call: inside the same function its registers slowed the 16-byte kernel by 10-15 % at 64-256 B. - The 64-byte NEON kernel takes chunks of 360 blocks, so the weighted sum of a chunk fits 32 bits and the chunk loop - stays in 32-bit arithmetic; with 1016 blocks it went to 64 bits and cost 15 % at 64 B. + stays in 32-bit arithmetic; with 1016 blocks it went to 64 bits and was 15 % slower. - Short inputs, against a plain deferred-modulo loop (the Wikipedia one), at 20 bytes with GCC on x86-64: - GCC returned a small aggregate by storing its members one by one and loading them as one word, which stalls store forwarding. The sums are built in one integer and copied (`make_state()`), and Fletcher-16 and -32 pass their @@ -299,7 +304,7 @@ long input pays a fixed cost of a few multiplications. All sums wrap modulo 2^64 | x86-64 SSE2 (baseline) | Yes, from 192 B | Two 128-bit vectors per sum. With GCC the portable lanes are within 15 % of it from 1500 B; with Clang 19 246 MB/s at 4 KiB against 8 424 for the portable lanes. | | AArch64 NEON, little-endian | Yes, from 192 B | A72 at 256 B: 2 209 MB/s with GCC, as fast as its portable lanes; 2 101 with Clang against 1 500 for its portable lanes. | | 32-bit Arm NEON, little-endian | Yes, from 192 B | A72 in AArch32 at 4 KiB: 2 384 MB/s with GCC against 1 069 for the word loop (2.2×), 2 862 with Clang. | -| Portable lanes, 64-bit targets | Yes, from 256 B | On the A72 they overtake the word loop at 128 B with GCC but only at 256 B with Clang, whose word loop is unrolled. | +| Portable lanes, 64-bit targets | Yes, from 256 B | On the A72 they overtake the word loop at 128 B with GCC; with Clang, whose word loop is unrolled, they stay below it (1 500 MB/s at 256 B against 1 813 for the word loop at 128 B). | | Portable lanes, 32-bit targets | No | The 64-bit sums of four lanes do not fit the registers: 3× slower than the word loop. Without a kernel the lane code is not even linked. | | Big-endian NEON | No | The kernel reads vector lanes as little-endian words; big-endian AArch64 runs the portable lanes. | | RISC-V V extension | Not done | No hardware to measure; RV64 runs the portable lanes. | @@ -309,7 +314,7 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cor - Thresholds are where the lanes overtake the word loop of the same build, with GCC and Clang: AVX2 at 128 B; SSE2 at 192 B (GCC's SSE2 lanes are slower at 128 and 160); NEON at 192 B on AArch64 and AArch32, where Clang's unrolled word - loop wins below (GCC's NEON lanes win from 80 B). + loop wins below (GCC's NEON lanes win from 80 B on AArch64). - `combine()` is written out with constant weights, which become shifts and additions. As a loop over a weight table GCC vectorized it into emulated 64-bit vector multiplications, which cost more than the lanes saved up to 512 B. - `compute_loop()` passes its own return value to the long path by reference. A `fletcher4_value` returned by a call is @@ -321,4 +326,4 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cor inputs below the threshold run without a call; `fletcher4_compute` has its own copy that starts from the empty state. - Against OpenZFS f79c81d (`fletcher_4_native` with its superscalar4, sse2, ssse3, avx2 and aarch64_neon kernels, GCC `-O2`), the library runs at 0.93× the fastest at 20 B and 1.09× at 256 B on x86-64, 0.92× and 1.18× on the A72, and - 1.0× from 4 KiB on both. + 1.0× from 1500 B on x86-64 and from 4 KiB on the A72. diff --git a/doc/design/testing.md b/doc/design/testing.md index 6060b0a..2aef82a 100644 --- a/doc/design/testing.md +++ b/doc/design/testing.md @@ -2,8 +2,8 @@ ## Layout -- Unit tests: Google Test, `tests/unit_tests/ut__.cpp`. Shared test data and helpers are headers in - `tests/unit_tests/include/`, maintained by hand. +- Unit tests: Google Test, `tests/unit_tests/ut_.cpp`, or `ut__.cpp` when an algorithm has + several. Shared test data and helpers are headers in `tests/unit_tests/include/`, maintained by hand. - Negative compile tests: `tests/compile_fail`. Each is a CTest test that builds an `EXCLUDE_FROM_ALL` target and passes only if the build output matches the expected diagnostic; each source also builds as a control target without the error. @@ -20,6 +20,7 @@ | Bit or byte manipulation (tables, slicing, loads) | also `native-asan` (AddressSanitizer + UBSan) | | Preconditions, exceptions, RTTI | also `native-gcc-no-exceptions`; the unit tests include one executable built with `NDEBUG` | | Architecture headers or the table loops | also `x86_64-gcc-pclmul`, `native-gcc-portable` and the cross presets of `cmake/emulator_presets.json` (QEMU user mode) | +| The x86-64 AVX-VNNI Fletcher/Adler-32 kernel | also a local build with `-march=native` on a CPU with AVX-VNNI (no preset or CI job covers it) | Run benchmarks and the full cross matrix only when the change needs them, filtered to what changed; they are slow. diff --git a/doc/fletcher.md b/doc/fletcher.md index 02e0691..7a01618 100644 --- a/doc/fletcher.md +++ b/doc/fletcher.md @@ -126,7 +126,7 @@ Portable is the library without kernels, SSE2 the default x86-64 flags, AVX2 a b | Fletcher-64 | 26 853 | | 52 801 | 13 065 | 54 881 | The AVX2 kernels are 7.4× (Fletcher-16), 3.3× (Fletcher-32) and 2.0× (Fletcher-64) faster than the GCC portable loop. -With `-march=native` (AVX-VNNI), GCC 16, MB/s: +The portable columns predate the current portable loop. With `-march=native` (AVX-VNNI), GCC 16, MB/s: | Checksum | 20 B | 64 B | 256 B | 1500 B | 4 KiB | 1 MiB | | --- | --- | --- | --- | --- | --- | --- | @@ -151,7 +151,8 @@ GCC 14.3, `-O2`, one core. GiB/s at 64 B / 256 B / 1500 B / 4 KiB, start address At 4 KiB NEON is 5.0× (AArch32) to 6.8× (AArch64, 64 bytes per iteration) faster for Fletcher-16, 2.8-2.9× for Fletcher-32, and 1.45× (AArch64) or 3.0× (AArch32) for Fletcher-64, whose 64-bit portable loop is already fast on AArch64. Below the thresholds both builds run the portable loop; the differences there come from code layout. At 20 bytes AArch64 Fletcher-32 runs 592 MB/s, 0.88× the Wikipedia -loop (675). +loop (675). The AArch64 portable column was measured before the current portable loop (32-bit sums for Fletcher-32, a +constant `%` for the Fletcher moduli, pointer-bounded loop); re-measure before relying on it. ### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz diff --git a/doc/internet.md b/doc/internet.md index 926b9a9..1889447 100644 --- a/doc/internet.md +++ b/doc/internet.md @@ -134,13 +134,13 @@ GCC 14.3, `-O2`, static binaries on one core. Portable is with `CHECKSUM_ACCELER | 4 KiB | 7 214 | 13 182 | 2 737 | 11 149 | 5 359 | | 1 MiB | 5 386 | 6 679 | 2 580 | 6 253 | 4 561 | -The 64-bit portable loop is already fast, so the NEON kernel starts at 512 bytes and is 1.5-1.8× faster from 1500 -bytes. In 32-bit mode the kernels start at 192 bytes: NEON is 4.1× and `ldm` 2.0× faster at 4 KiB. Below the -thresholds every build runs the portable loop, and the differences there come from code layout. +The 64-bit portable loop is already fast, so the NEON kernel starts at 512 bytes and is 1.5-1.8× faster at +1500 B-4 KiB (1.24× at 1 MiB). In 32-bit mode the kernels start at 192 bytes: NEON is 4.1× and `ldm` 2.0× faster at +4 KiB. Below the thresholds every build runs the portable loop, and the differences there come from code layout. The table predates the current portable loop, which is 1.1-1.45× faster in AArch64 and 1.05-1.4× faster in AArch32 up -to 256 B (comparison harness, same flags): AArch64 now takes 957 MB/s at 20 B, 1.10× Linux v7.3-rc5 `do_csum`, which -reads whole 8-byte words and masks off the bytes past the end. +to 256 B. In the comparison harness, whose figures are lower than this table's, AArch64 takes 957 MB/s at 20 B, 1.10× +Linux v7.3-rc5 `do_csum`, which reads whole 8-byte words and masks off the bytes past the end. ### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz @@ -149,19 +149,19 @@ address modulo 4: 2 is typical for an IP header behind a 14-byte Ethernet header | Input | nRF52840 portable | nRF52840 `ldm` | STM32L4A6 portable | STM32L4A6 `ldm` | | --- | --- | --- | --- | --- | -| 20 B | 10.3 | 10.2 | 12.9 | 12.5 | -| 64 B | 24.4 | 22.4 | 30.5 | 29.3 | -| 256 B | 40.2 | 52.0 | 50.2 | 61.9 | -| 1500 B | 48.5 | 82.6 | 60.6 | 100.2 | -| 4 KiB | 50.3 | 92.5 | 62.9 | 114.9 | -| 1500 B, offset 2 | 40.8 | 81.4 | 51.0 | 100.5 | -| 4 KiB, offset 1 | 36.1 | 90.2 | 45.2 | 110.9 | +| 20 B | 10.3 | 10.0 | 12.9 | 12.5 | +| 64 B | 24.4 | 23.4 | 30.5 | 29.3 | +| 256 B | 40.2 | 49.5 | 50.2 | 61.9 | +| 1500 B | 48.5 | 80.1 | 60.6 | 100.2 | +| 4 KiB | 50.3 | 91.9 | 62.9 | 114.9 | +| 1500 B, offset 2 | 40.8 | 80.4 | 51.0 | 100.5 | +| 4 KiB, offset 1 | 36.1 | 88.7 | 45.2 | 110.9 | Per byte at 4 KiB, the kernel takes 0.70 cycles against 1.27 for the portable loop: 1.8× faster, 1.2× at 256 bytes, and up to 2.5× from odd or 2-modulo-4 addresses, where the portable loop's unaligned loads cost more. Both chips run the -same cycles per byte, so the figures scale with the clock. The nRF52840 `ldm` column is re-measured with the current -portable loop, which is 1.05-1.4× faster than the one in the other columns below 192 bytes (1.2× at 20 B); at 191 -bytes it takes 345 cycles against 273 for the kernel at 192, so the threshold could move lower. +same cycles per byte, so the figures scale with the clock. The table predates the current portable loop: in a separate +harness on the nRF52840, the `ldm` build of the current code is 1.22× faster than before at 20 B, 1.08× at 64 B and +1.15× at 256 B. At 191 bytes it takes 345 cycles against 273 for the kernel at 192, so the threshold could move lower. ### 6.4 Code size diff --git a/src/fletcher4/sum_loop.cpp b/src/fletcher4/sum_loop.cpp index fdd4169..a8cbda5 100644 --- a/src/fletcher4/sum_loop.cpp +++ b/src/fletcher4/sum_loop.cpp @@ -16,8 +16,8 @@ namespace { // Bytes of one word per lane. inline constexpr std::size_t group_size = lane_count * word_size; -// Shortest input for the lanes. The portable ones overtake the word loop on a Cortex-A72 at 128 bytes with GCC, 256 with Clang; on 32-bit targets -// their 64-bit sums run out of registers, 3 times slower there. +// Shortest input for the lanes. The portable ones overtake the word loop on a Cortex-A72 at 128 bytes with GCC but stay below +// Clang's unrolled word loop; on 32-bit targets their 64-bit sums run out of registers, 3 times slower there. inline constexpr std::size_t lanes_minimum_size = lane_kernel_available ? lane_kernel_minimum_size : (std::numeric_limits::digits == 64 ? 256 : std::numeric_limits::max()); diff --git a/src/include_private/checksum_private/crc_arch.hpp b/src/include_private/checksum_private/crc_arch.hpp index 78744cf..ceeb367 100644 --- a/src/include_private/checksum_private/crc_arch.hpp +++ b/src/include_private/checksum_private/crc_arch.hpp @@ -80,7 +80,8 @@ std::uint32_t fold_crc32(folding_constants const &constants, std::uint32_t remai // - partial(accumulator, by_one, last, size): accumulator plus the last size (1..15) bytes; last = final 16 bytes // - reduce(accumulator, constants): the 64-bit register // - lane(accumulator): low (0) or high (1) 64 bits; fold_crc32_with() only -// - wide; if true, wide_minimum_size and fold_wide(), a wider loop that finishes with fold_four_with() +// - wide; if true, wide_minimum_size and fold_wide(), a wider loop that folds its 8 last blocks in parallel and ends +// with fold_tail_with() template typename Kernel::vector fold_blocks_with(folding_constants const &constants, std::uint64_t remainder, std::span data) noexcept; diff --git a/src/include_private/checksum_private/fletcher_arch.hpp b/src/include_private/checksum_private/fletcher_arch.hpp index e203ec1..57d9597 100644 --- a/src/include_private/checksum_private/fletcher_arch.hpp +++ b/src/include_private/checksum_private/fletcher_arch.hpp @@ -10,6 +10,8 @@ // - minimum_size: shortest input for the kernel (max: never) // - for kernel<8> also alignment: sum_chunks() of fletcher_loops.hpp adds single bytes up to an address of that alignment // before the kernel +// An optional group_kernel with the same interface runs instead of kernel from its own minimum_size (sum_long() of +// fletcher_loops.hpp). #include diff --git a/src/include_private/checksum_private/fletcher_loops.hpp b/src/include_private/checksum_private/fletcher_loops.hpp index 404a9c6..40e30c0 100644 --- a/src/include_private/checksum_private/fletcher_loops.hpp +++ b/src/include_private/checksum_private/fletcher_loops.hpp @@ -209,7 +209,7 @@ template template [[gnu::always_inline]] inline State sum_portable(State state, std::span data) noexcept { // The widest integer the target adds natively, or 64 bits for 32-bit values. AArch64 sums 16-bit values in 32 bits: - // Fletcher-32 at 20 bytes ran 6 % faster on a Cortex-A72 (a reduction every 360 values costs little), but 9 % slower on x86-64. + // Fletcher-32 at 20 bytes ran 7 % faster on a Cortex-A72 (a reduction every 360 values costs little), but 9 % slower on x86-64. using accumulator = std::conditional_t>; // 32-bit targets sum 16-bit values as 32-bit words, two values each; 64-bit targets keep the 4-value formula on native words. diff --git a/src/include_private/checksum_private/x86_64/fletcher.hpp b/src/include_private/checksum_private/x86_64/fletcher.hpp index b0d7594..79fdf04 100644 --- a/src/include_private/checksum_private/x86_64/fletcher.hpp +++ b/src/include_private/checksum_private/x86_64/fletcher.hpp @@ -1,8 +1,8 @@ #ifndef CHECKSUM_PRIVATE_X86_64_FLETCHER_HPP #define CHECKSUM_PRIVATE_X86_64_FLETCHER_HPP -// x86-64 kernels of the Fletcher checksums and Adler-32 on 256-bit AVX2 vectors, else on 128-bit SSE2 vectors (the x86-64 -// baseline) for bytes and 16-bit values. Included only by fletcher_arch.hpp. +// x86-64 kernels of the Fletcher checksums and Adler-32 on 256-bit AVX2 vectors (bytes with vpdpbusd under AVX-VNNI), else +// on 128-bit SSE2 vectors (the x86-64 baseline) for bytes and 16-bit values. Included only by fletcher_arch.hpp. #include diff --git a/src/include_private/checksum_private/x86_64/fletcher4.hpp b/src/include_private/checksum_private/x86_64/fletcher4.hpp index 17e01d6..17671b9 100644 --- a/src/include_private/checksum_private/x86_64/fletcher4.hpp +++ b/src/include_private/checksum_private/x86_64/fletcher4.hpp @@ -46,7 +46,7 @@ inline lane_sums lane_kernel(std::byte const *data, std::size_t groups) noexcept #else -// The kernel overtakes the word loop on a Core Ultra 7 155H at 192 bytes with GCC and at 384 with Clang, which is 10 % slower at 256. +// Where the kernel overtakes the word loop on a Core Ultra 7 155H, with GCC and Clang; GCC's lanes are slower at 128 and 160 bytes. inline constexpr std::size_t lane_kernel_minimum_size = 192; // Lanes 0 and 1 in the low vectors, 2 and 3 in the high ones. From b61579250794d87d2a8041b0b65d456bad2f69ce Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Sun, 4 Oct 2026 23:45:40 +0200 Subject: [PATCH 63/64] chore: spelling words for the gap-fix docs --- .cspell.yml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/.cspell.yml b/.cspell.yml index 00dc156..07f1349 100644 --- a/.cspell.yml +++ b/.cspell.yml @@ -41,6 +41,7 @@ words: - armv - asan - autosar +- avxvnni - broadcastsi - bugprone - buypass @@ -73,6 +74,7 @@ words: - darc - datagram - dect +- dpbusd - DPDK - dtcm - eabi @@ -118,6 +120,7 @@ words: - maddubs - madler - mavx +- mavxvnni - mcpu - mcrf - memcpy @@ -148,6 +151,7 @@ words: - pclmul - pclmulqdq - pmaddubsw +- pmaddwd - pmull - polys - predefines @@ -179,6 +183,7 @@ words: - stdint - storeu - strequal +- superscalar - taskset - teledisk - templatize @@ -212,9 +217,11 @@ words: - vmul - vmull - vmulq +- VNNI - vpadalq -- VPCLMULQDQ - vpaddlq +- VPCLMULQDQ +- vpdpbusd - vqtbl - vreinterpret - vreinterpretq @@ -241,7 +248,3 @@ words: - zextsi - zmodem - znver -- avxvnni -- dpbusd -- vpdpbusd -- VNNI From 9565d12974095ceb700e9481de1e58c212983fbf Mon Sep 17 00:00:00 2001 From: Jan Macheta <2372096+jmacheta@users.noreply.github.com> Date: Mon, 5 Oct 2026 00:48:57 +0200 Subject: [PATCH 64/64] docs: re-measure the Fletcher, Adler-32 and Internet tables x86-64 (Core Ultra 7 155H), Cortex-A72 and Cortex-M4 (nRF52840, STM32L4A6) figures come from one run of the current code; the notes on figures that predated the portable loop changes are gone. Break-even points of the Internet kernels are re-measured, and the Wikipedia-loop comparison at 20 bytes runs in the same harness. --- doc/adler32.md | 33 +++++----- doc/design/acceleration.md | 39 ++++++------ doc/fletcher.md | 42 ++++++------- doc/internet.md | 62 +++++++++---------- .../checksum_private/arm/internet.hpp | 3 +- .../checksum_private/x86_64/internet.hpp | 2 +- 6 files changed, 89 insertions(+), 92 deletions(-) diff --git a/doc/adler32.md b/doc/adler32.md index d74d5d4..5ced703 100644 --- a/doc/adler32.md +++ b/doc/adler32.md @@ -93,33 +93,32 @@ evaluation always runs a byte-by-byte loop with the same result. The measurement ### 6.1 x86-64: Core Ultra 7 155H -GCC 16, 4 KiB, measured on a loaded host: 7 365 MB/s (10⁶ bytes per second) for the portable loop, 54 211 MB/s with -the AVX2 kernel, 7.4× faster (56 382 MB/s in the later run of the table below). The portable figure predates the -current portable loop. With `-march=native` the AVX-VNNI kernel runs (MB/s, GCC 16 and Clang 21): +GCC 16, 4 KiB, one pinned core, the better median of two runs: 7 309 MB/s (10⁶ bytes per second) for the portable +loop, 22 964 MB/s with SSE2 and 58 088 MB/s with the AVX2 kernel, 7.9× faster. With `-march=native` the AVX-VNNI +kernel runs (MB/s, GCC 16 and Clang 21): | Input | 20 B | 64 B | 256 B | 1500 B | 4 KiB | 1 MiB | | --- | --- | --- | --- | --- | --- | --- | -| GCC | 3 441 | 10 846 | 33 317 | 55 254 | 85 045 | 89 051 | -| Clang | 3 420 | 10 542 | 34 390 | 54 459 | 83 602 | 90 845 | +| GCC | 3 781 | 11 570 | 35 225 | 56 789 | 84 504 | 88 630 | +| Clang | 3 746 | 11 655 | 36 649 | 57 952 | 85 027 | 89 914 | -Against zlib-ng (develop, its AVX-VNNI kernel, same flags) that is 0.98× at 20 B, 0.78× at 64 B, 0.91× at 256 B and -1.13-1.17× from 4 KiB; the AVX2 kernel reached 0.71-0.83× there. +In a separate comparison harness, against zlib-ng (develop, its AVX-VNNI kernel, same flags) the library runs 0.98× +at 20 B, 0.78× at 64 B, 0.91× at 256 B and 1.13-1.17× from 4 KiB; the AVX2 kernel reached 0.71-0.83× there. ### 6.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz -GCC 14.3, `-O2`, one core, start address aligned. GiB/s: +GCC 14.3, `-O2`, AArch64 `-march=armv8-a`, one core, start address aligned. GiB/s: | Build | 64 B | 256 B | 1500 B | 4 KiB | | --- | --- | --- | --- | --- | -| AArch64 portable | 0.68 | 0.77 | 0.83 | 0.84 | -| AArch64 NEON | 1.13 | 2.62 | 4.79 | 5.84 | -| AArch32 portable | 0.52 | 0.71 | 0.85 | 0.86 | -| AArch32 NEON | 0.98 | 2.44 | 3.75 | 4.32 | - -NEON is 5-7× faster at 4 KiB and 1.7-1.9× at 64 bytes. On AArch64, from 320 bytes the kernel sums 64 bytes per -iteration: 0.96-0.99× zlib-ng and ISA-L from 1500 B, where 16 bytes per iteration reached 0.72-0.79×. The AArch64 -portable row was measured before the current portable loop, which bounds its loop by a pointer; re-measure before -relying on it. +| AArch64 portable | 0.69 | 0.77 | 0.83 | 0.84 | +| AArch64 NEON | 1.15 | 2.60 | 5.01 | 6.16 | +| AArch32 portable | 0.66 | 0.77 | 0.85 | 0.87 | +| AArch32 NEON | 0.95 | 2.42 | 3.75 | 4.30 | + +NEON is 5.0-7.3× faster at 4 KiB and 1.4-1.7× at 64 bytes. On AArch64, from 320 bytes the kernel sums 64 bytes per +iteration: 0.96-0.99× zlib-ng and ISA-L from 1500 B in the comparison harness, where 16 bytes per iteration reached +0.72-0.79×. ### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz diff --git a/doc/design/acceleration.md b/doc/design/acceleration.md index 7bf1e08..cb5be62 100644 --- a/doc/design/acceleration.md +++ b/doc/design/acceleration.md @@ -89,27 +89,24 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cor A one's complement sum needs only additions, and the order of the bytes does not matter, so the portable loop is already fast. It adds native `std::size_t` words in two add-with-carry chains and swaps the bytes of the result once: -on x86-64 that is about 7 700 MB/s at 20 B and 50 000 MB/s at 4 KiB, without any instruction-set flags. A kernel has +on x86-64 that is about 8 200 MB/s at 20 B and 55 500 MB/s at 4 KiB, without any instruction-set flags. A kernel has to beat that, not a byte loop. | Target | Verdict | Why | | --- | --- | --- | -| x86-64 AVX2 | Yes, from 512 B | 64-byte blocks, 32-bit halves summed into 64-bit lanes: 1.4-1.7× the portable loop from 1500 B. The call and the reduction make it slower below about 450 B. | +| x86-64 AVX2 | Yes, from 512 B | 64-byte blocks, 32-bit halves summed into 64-bit lanes: 1.4-1.7× the portable loop at 1500 B-4 KiB, 1.2-1.5× at 1 MiB. The call and the reduction make it slower below about 350 B. | | x86-64 SSE2 (baseline) | No | The same scheme with 16-byte vectors matched the scalar carry loop and was never faster. | | x86-64 AVX-512 | Not measured | No AVX-512 hardware available; the AVX2 kernel is near the L1 bandwidth, so the gain is likely small. | | Compiler auto-vectorization | No | GCC `-O3 -march=native` vectorizes a 32-bit-word loop to about 47 000 MB/s, below the scalar carry loop; Clang does not vectorize it. | -| AArch64 NEON (`uadalp`) | Yes, from 512 B | Cortex-A72: 1.5× at 1500 B, 1.8× at 4 KiB. The 64-bit portable loop is fast (5 400 MB/s at 256 B), so the kernel loses below about 450 B. Eight accumulators (128 B per iteration) were slower than four. | +| AArch64 NEON (`uadalp`) | Yes, from 512 B | Cortex-A72: 1.5× at 1500 B, 1.8× at 4 KiB. The 64-bit portable loop is fast (5 700 MB/s at 256 B), so the kernel loses below about 370 B. Eight accumulators (128 B per iteration) were slower than four. | | AArch64 `ldp` + `adcs` assembly | No, for now | 1.3-1.5× the portable loop at 256 B-4 KiB on the A72, better than NEON at 256 B but worse from 1500 B. A second kernel for 256-511 B is not worth the assembly. | -| 32-bit Arm NEON | Yes, from 192 B | A72 in AArch32: 4.1× at 4 KiB, where the portable loop runs 32-bit words. | -| 32-bit Arm without NEON (Cortex-M) | Yes, from 192 B, inline assembly | `ldm` + `adcs` chain: 0.70 cycles per byte against 1.27 for the earlier portable loop on a Cortex-M4 (nRF52840 and STM32L4A6): 1.8× at 4 KiB, 1.2× at 256 B, up to 2.5× from an odd address. | +| 32-bit Arm NEON | Yes, from 192 B | A72 in AArch32: 3.6× at 4 KiB, where the portable loop runs 32-bit words. | +| 32-bit Arm without NEON (Cortex-M) | Yes, from 192 B, inline assembly | `ldm` + `adcs` chain: 0.69 cycles per byte against 1.27 for the portable loop on a Cortex-M4 (nRF52840 and STM32L4A6): 1.8× at 4 KiB, 1.3× at 256 B, up to 2.5× from an odd address. | | Cortex-M0/M0+/M23 (Thumb-1) | Not done | `adcs` and `ldm` exist for low registers, but there is no `teq`: the loop test must not clobber the carry. No hardware to measure. | | Big-endian NEON | No | `vreinterpret` lane order differs between GCC and Clang, as for PMULL; big-endian AArch64 runs the portable loop. | | RISC-V V extension | Implemented, unproven | Widening add `vwaddu.wv` into 64-bit lanes, vector-length agnostic; tested in QEMU with VLEN 128-1024. No hardware measured, so the 64 B threshold is a guess. | | RISC-V scalar (Zba, Zbb) | No | No carry flag: a 64-bit word costs a load and three instructions with or without `add.uw`, the same as the portable loop. | -The Cortex-A72 figures and thresholds above predate the current portable loop, which is 1.1-1.45× faster in AArch64 -and 1.05-1.4× faster in AArch32 up to 256 B; the NEON thresholds have not been re-measured against it. - Cortex-M methods, measured on the nRF52840 and STM32L4A6 (cycles per byte at 4 KiB): | Method | Cycles per byte | Notes | @@ -124,9 +121,9 @@ Cortex-M methods, measured on the nRF52840 and STM32L4A6 (cycles per byte at 4 K | DSP (`uxtah`, `uadd16`, `usada8`) | - | At least two instructions per word, against one `adcs`. | | MCU CRC unit | - | It computes CRCs only. | -What is left on Cortex-M: inputs below 192 bytes run the portable loop, dominated by the call and the final fold. In -one harness the current loop takes 125 cycles for 20 bytes against 152 before; at 191 B it takes 345 cycles against -273 for the `ldm` kernel at 192 B, so the threshold could move lower. +What is left on Cortex-M: inputs below 192 bytes run the portable loop, dominated by the call and the final fold: 122 +cycles for 20 bytes, and 346 cycles at 191 B against 273 for the `ldm` kernel at 192 B, so the threshold could move +lower. Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Cortex-M4: nRF52840): @@ -144,14 +141,13 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Cortex-M - One final fold after the carry chains are merged: three separate folds cost 8-20 % at 20-64 B. - The AVX2 and NEON kernels work in passes of 2^26 blocks (4 GiB), the vector kernel in passes of 2^18 iterations, so their 64-bit lanes never overflow. -- The final fold works in the width of the native word: on a Cortex-M4 a 64-bit fold cost 30 cycles of the 150 that - a 20-byte input took with the earlier portable loop. +- The final fold works in the width of the native word: on a Cortex-M4 a 64-bit fold cost 30 cycles per call. - `sum_loop()` holds no call for short inputs: the kernel and the loop after it sit in a separate non-inlined function. A call inside `sum_loop()` saved registers on every input and cost 13-23 % below 256 bytes on x86-64; one shared, non-inlined copy of the portable loop saved 100 bytes on a Cortex-M4 but cost 25 % at 20 bytes on x86-64. -- Thresholds are where the kernel overtakes the portable loop of the same build, measured against the earlier - portable loop: x86-64 at about 450 bytes, AArch64 at 450, AArch32 NEON at 150-190, the Cortex-M4 `ldm` kernel at - 130-190 depending on the start address. +- Thresholds sit above the point where the kernel overtakes the portable loop of the same build: x86-64 at about 350 + bytes, AArch64 at 370, AArch32 NEON and `ldm` on the A72 at 100-130, the Cortex-M4 `ldm` kernel at 120-160 depending + on the start address. - The `ldm` kernel returns its last carry separately: added back into the 32-bit sum, it would be lost when the sum is 0xFFFFFFFF. @@ -169,14 +165,14 @@ x86-64 at 4 KiB with GCC, but only 0.84 GiB/s on a Cortex-A72 and 5.3 cycles per | Target | Verdict | Why | | --- | --- | --- | -| x86-64 AVX-VNNI | Yes, bytes from 64 B | `vpdpbusd` weights 32 bytes in one instruction instead of `pmaddubsw` + `pmaddwd` + add; four blocks per iteration weigh 127 .. 0 against one `previous` addition. Adler-32 at 4 KiB: 85 045 MB/s against 56 382 for the AVX2 kernel (1.5×), 1.13× zlib-ng's AVX-VNNI kernel. Not in a test preset: QEMU has no AVX-VNNI and GitHub runners may lack it, so it is tested locally with `-march=native`. | -| x86-64 AVX2 | Yes: bytes from 64 B, 16-bit values from 128 B, 32-bit values from 384 B | At 4 KiB with GCC, 7.4× the portable loop for Fletcher-16 and Adler-32, 3.3× for Fletcher-32, 2.0× for Fletcher-64. | +| x86-64 AVX-VNNI | Yes, bytes from 64 B | `vpdpbusd` weights 32 bytes in one instruction instead of `pmaddubsw` + `pmaddwd` + add; four blocks per iteration weigh 127 .. 0 against one `previous` addition. Adler-32 at 4 KiB: 84 504 MB/s against 58 088 for the AVX2 kernel (1.45×), 1.13× zlib-ng's AVX-VNNI kernel. Not in a test preset: QEMU has no AVX-VNNI and GitHub runners may lack it, so it is tested locally with `-march=native`. | +| x86-64 AVX2 | Yes: bytes from 64 B, 16-bit values from 128 B, 32-bit values from 384 B | At 4 KiB with GCC, 7.4× the portable loop for Fletcher-16, 7.9× for Adler-32, 3.7× for Fletcher-32, 1.9× for Fletcher-64. | | x86-64 SSE2 (baseline), SSSE3 | Yes, bytes and 16-bit values | Fletcher-16 3.1× and Fletcher-32 1.5× the portable loop at 4 KiB with GCC. SSSE3 `pmaddubsw` weights 16 bytes in two instructions; plain SSE2 widens the bytes first. | -| x86-64 SSE2, 32-bit values | Not done | The 64-bit portable loop of Fletcher-64 already runs 26 900 MB/s at 4 KiB. | +| x86-64 SSE2, 32-bit values | Not done | The 64-bit portable loop of Fletcher-64 already runs 27 500 MB/s at 4 KiB. | | x86-64 AVX-512 | Not measured | No AVX-512 hardware available. | | AArch64 NEON | Yes: bytes from 64 B, 16-bit from 128 B, 32-bit from 256 B | Cortex-A72 at 4 KiB: about 7× for Fletcher-16 and Adler-32, 2.8× for Fletcher-32, 1.45× for Fletcher-64, whose 64-bit portable loop is already fast. | | AArch64 NEON, 64 bytes per iteration (`group_kernel`) | Yes, bytes from 320 B | Pairwise additions of four blocks into `sum`, 64 column sums weighted 64 .. 1, one `previous` addition per 64 bytes, as zlib-ng: Adler-32 at 4 KiB 6 270 against 4 746 MB/s (1.32×), 0.96× zlib-ng and ISA-L. Below 320 B weighting 64 columns costs more than it saves. In AArch32 (16 NEON registers) it spilled and lost 10-27 %. | -| 32-bit Arm NEON, little-endian | Yes, the same kernels and thresholds except `group_kernel` | A72 in AArch32 at 4 KiB: 5.0× for Fletcher-16 and Adler-32, 2.9× for Fletcher-32, 3.0× for Fletcher-64. | +| 32-bit Arm NEON, little-endian | Yes, the same kernels and thresholds except `group_kernel` | A72 in AArch32 at 4 KiB: 4.7× for Fletcher-16, 5.0× for Adler-32, 2.9× for Fletcher-32, 3.1× for Fletcher-64. | | M-profile Arm DSP (Cortex-M4/M7/M33), bytes | Yes, from 64 B | `usada8` sums 4 bytes, `uxtb16` + `smlad` weight them: 2.69 cycles per byte against 5.30 on a Cortex-M4 (nRF52840 and STM32L4A6), 2.0× at 4 KiB, 1.6× at 256 B. | | M-profile Arm DSP, 16-bit and 32-bit values | No | The portable loop sums 32-bit words on 32-bit targets: 2.11 cycles per byte for Fletcher-32 and 1.80 for Fletcher-64, within 2 % of a DSP kernel of the same scheme. | | A-profile 32-bit Arm without NEON | No | The DSP kernel is slower than the portable loop on the Cortex-A72 in AArch32; only M-profile cores use it. | @@ -202,7 +198,8 @@ Decisions, with the measurement behind each (x86-64: Core Ultra 7 155H; Arm: Cor - Short inputs, against a plain deferred-modulo loop (the Wikipedia one), at 20 bytes with GCC on x86-64: - GCC returned a small aggregate by storing its members one by one and loading them as one word, which stalls store forwarding. The sums are built in one integer and copied (`make_state()`), and Fletcher-16 and -32 pass their - state to `sum_loop()` as one integer (`state_word`): Fletcher-16 0.68 to 0.94×, Fletcher-32 0.51 to 0.86×. + state to `sum_loop()` as one integer (`state_word`): Fletcher-16 from 0.68× to 1.0×, Fletcher-32 from 0.51× to + 0.74×. - Unfinished blocks go to a separate non-inlined function, so the whole-block path needs no frame; there the byte loops are inline. Fletcher-64, whose state passes in two registers, and 32-bit targets lost 3-10 % that way and keep them in `sum_any()`, with out-of-line byte loops. diff --git a/doc/fletcher.md b/doc/fletcher.md index 7a01618..c79aea4 100644 --- a/doc/fletcher.md +++ b/doc/fletcher.md @@ -116,43 +116,43 @@ each choice are in [design/acceleration.md](design/acceleration.md#fletcher-and- ### 6.1 x86-64: Core Ultra 7 155H -MB/s (10⁶ bytes per second) at 4 KiB, GCC 16 and Clang 21, measured on a loaded host, so the figures are approximate. +MB/s (10⁶ bytes per second) at 4 KiB, GCC 16 and Clang 21, one pinned core, the better median of two runs. Portable is the library without kernels, SSE2 the default x86-64 flags, AVX2 a build with AVX2 enabled. | Checksum | GCC portable | GCC SSE2 | GCC AVX2 | Clang portable | Clang AVX2 | | --- | --- | --- | --- | --- | --- | -| Fletcher-16 | 7 314 | 22 778 | 54 107 | 3 205 | 58 109 | -| Fletcher-32 | 14 167 | 21 916 | 47 221 | 6 447 | 54 311 | -| Fletcher-64 | 26 853 | | 52 801 | 13 065 | 54 881 | +| Fletcher-16 | 7 373 | 22 955 | 54 620 | 3 183 | 56 748 | +| Fletcher-32 | 14 419 | 21 918 | 53 037 | 6 436 | 52 933 | +| Fletcher-64 | 27 485 | | 51 094 | 12 977 | 53 681 | -The AVX2 kernels are 7.4× (Fletcher-16), 3.3× (Fletcher-32) and 2.0× (Fletcher-64) faster than the GCC portable loop. -The portable columns predate the current portable loop. With `-march=native` (AVX-VNNI), GCC 16, MB/s: +The AVX2 kernels are 7.4× (Fletcher-16), 3.7× (Fletcher-32) and 1.9× (Fletcher-64) faster than the GCC portable loop. +Clang's portable loop is 2.1-2.3× slower than GCC's. With `-march=native` (AVX-VNNI), GCC 16, MB/s: | Checksum | 20 B | 64 B | 256 B | 1500 B | 4 KiB | 1 MiB | | --- | --- | --- | --- | --- | --- | --- | -| Fletcher-16 | 3 094 | 9 959 | 31 780 | 54 938 | 81 283 | 90 798 | -| Fletcher-32 | 3 972 | 7 739 | 21 029 | 37 057 | 49 934 | 51 822 | -| Fletcher-64 | 3 920 | 9 423 | 18 352 | 37 030 | 49 787 | 59 639 | +| Fletcher-16 | 3 402 | 10 461 | 32 186 | 55 934 | 78 507 | 76 821 | +| Fletcher-32 | 4 234 | 8 187 | 20 612 | 40 062 | 50 327 | 51 876 | +| Fletcher-64 | 4 358 | 10 300 | 19 442 | 37 377 | 49 912 | 56 686 | -At 20 bytes the plain deferred-modulo loop of the Wikipedia article (`-O2 -march=native`) runs 3 300 MB/s for -Fletcher-16 and 4 600 for Fletcher-32: 0.94× and 0.86× for the library, which needs the state and its unfinished +At 20 bytes the plain deferred-modulo loop of the Wikipedia article (`-O2 -march=native`, same harness) runs 3 360 MB/s +for Fletcher-16 and 5 700 for Fletcher-32: 1.0× and 0.74× for the library, which needs the state and its unfinished block on top. ### 6.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz -GCC 14.3, `-O2`, one core. GiB/s at 64 B / 256 B / 1500 B / 4 KiB, start address aligned. +GCC 14.3, `-O2`, AArch64 `-march=armv8-a`, one core. GiB/s at 64 B / 256 B / 1500 B / 4 KiB, start address aligned. | Checksum | AArch64 portable | AArch64 NEON | AArch32 portable | AArch32 NEON | | --- | --- | --- | --- | --- | -| Fletcher-16 | 0.62 / 0.74 / 0.83 / 0.84 | 0.96 / 2.38 / 4.67 / 5.75 | 0.57 / 0.73 / 0.82 / 0.84 | 0.82 / 2.13 / 3.58 / 4.23 | -| Fletcher-32 | 0.98 / 1.42 / 1.61 / 1.67 | 1.09 / 2.57 / 4.27 / 4.78 | 0.78 / 1.37 / 1.56 / 1.65 | 0.80 / 2.37 / 4.09 / 4.74 | -| Fletcher-64 | 1.46 / 2.71 / 3.36 / 3.56 | 1.41 / 2.85 / 4.41 / 5.16 | 0.91 / 1.40 / 1.61 / 1.67 | 0.90 / 2.30 / 4.10 / 5.06 | - -At 4 KiB NEON is 5.0× (AArch32) to 6.8× (AArch64, 64 bytes per iteration) faster for Fletcher-16, 2.8-2.9× for Fletcher-32, and 1.45× (AArch64) or 3.0× (AArch32) for -Fletcher-64, whose 64-bit portable loop is already fast on AArch64. Below the thresholds both builds run the portable -loop; the differences there come from code layout. At 20 bytes AArch64 Fletcher-32 runs 592 MB/s, 0.88× the Wikipedia -loop (675). The AArch64 portable column was measured before the current portable loop (32-bit sums for Fletcher-32, a -constant `%` for the Fletcher moduli, pointer-bounded loop); re-measure before relying on it. +| Fletcher-16 | 0.66 / 0.77 / 0.84 / 0.85 | 1.02 / 2.42 / 4.92 / 6.11 | 0.57 / 0.78 / 0.90 / 0.91 | 0.98 / 2.40 / 3.71 / 4.31 | +| Fletcher-32 | 1.20 / 1.63 / 1.67 / 1.72 | 1.10 / 2.66 / 4.41 / 4.90 | 0.86 / 1.44 / 1.60 / 1.65 | 0.85 / 2.45 / 4.18 / 4.76 | +| Fletcher-64 | 1.50 / 2.70 / 3.37 / 3.57 | 1.55 / 2.91 / 4.46 / 5.22 | 0.92 / 1.39 / 1.57 / 1.67 | 0.88 / 2.33 / 4.27 / 5.12 | + +At 4 KiB NEON is 4.7× (AArch32) to 7.2× (AArch64, 64 bytes per iteration) faster for Fletcher-16, 2.8-2.9× for +Fletcher-32, and 1.47× (AArch64) or 3.1× (AArch32) for Fletcher-64, whose 64-bit portable loop is already fast on +AArch64. Below the thresholds both builds run the portable loop; the differences there come from code layout. At 20 +bytes AArch64 Fletcher-32 runs 690 MB/s with `-mcpu=cortex-a72`, 0.85× the Wikipedia loop (813), and 654 MB/s with +`-march=armv8-a`, 0.79× (823). ### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz diff --git a/doc/internet.md b/doc/internet.md index 1889447..f29387f 100644 --- a/doc/internet.md +++ b/doc/internet.md @@ -106,15 +106,15 @@ AVX2 is with `-march=native`; portable is with `CHECKSUM_ACCELERATION=OFF` and d | Input | GCC 16 portable | GCC 16 AVX2 | Clang 21 portable | Clang 21 AVX2 | | --- | --- | --- | --- | --- | -| 20 B (IPv4 header) | 7 709 | 7 699 | 7 094 | 7 103 | -| 64 B | 23 687 | 22 613 | 22 634 | 21 829 | -| 256 B | 43 669 | 43 347 | 42 295 | 42 198 | -| 1500 B (Ethernet payload) | 49 918 | 71 039 | 47 943 | 76 279 | -| 4 KiB | 50 691 | 75 516 | 52 012 | 79 779 | -| 1 MiB | 56 060 | 90 044 | 55 770 | 93 630 | +| 20 B (IPv4 header) | 8 198 | 8 193 | 7 564 | 7 573 | +| 64 B | 25 213 | 24 161 | 24 291 | 23 353 | +| 256 B | 46 748 | 46 352 | 45 065 | 45 027 | +| 1500 B (Ethernet payload) | 53 538 | 74 313 | 52 868 | 81 358 | +| 4 KiB | 55 492 | 82 858 | 56 057 | 95 187 | +| 1 MiB | 59 974 | 71 025 | 60 008 | 88 316 | Below 512 bytes both builds run the portable loop; the differences come from `-march=native` and code layout. From -1500 bytes the AVX2 kernel is 1.4-1.7× faster. +1500 bytes the AVX2 kernel is 1.4-1.7× faster up to 4 KiB, and 1.2× (GCC) or 1.5× (Clang) at 1 MiB. Against Linux v7.3-rc5 `csum_partial` and DPDK `rte_raw_cksum`, built with the same GCC 16 `-O2 -march=native` and called the same way, this build runs at 0.97× the faster of the two at 256 B, 0.98× at 64 B, 1.14× at 20 B and @@ -122,25 +122,25 @@ called the same way, this build runs at 0.97× the faster of the two at 256 B, 0 ### 6.2 Cortex-A72: Raspberry Pi 4, 1.5 GHz -GCC 14.3, `-O2`, static binaries on one core. Portable is with `CHECKSUM_ACCELERATION=OFF`. In 32-bit mode, NEON is -`-march=armv8-a+crc -mfpu=neon-fp-armv8`, and `ldm` is `-mfpu=vfpv3-d16` (no NEON). +GCC 14.3, `-O2`, static binaries on one core. Portable is with `CHECKSUM_ACCELERATION=OFF`. AArch64 is +`-march=armv8-a`; in 32-bit mode, NEON is `-march=armv8-a+crc -mfpu=neon-fp-armv8`, and `ldm` is `-mfpu=vfpv3-d16` +(no NEON). | Input | AArch64 portable | AArch64 NEON | AArch32 portable | AArch32 NEON | AArch32 `ldm` | | --- | --- | --- | --- | --- | --- | -| 20 B | 1 314 | 1 075 | 665 | 842 | 782 | -| 64 B | 2 719 | 3 339 | 1 475 | 2 058 | 1 941 | -| 256 B | 5 360 | 6 042 | 2 293 | 3 339 | 3 049 | -| 1500 B | 6 636 | 10 312 | 2 630 | 8 289 | 4 561 | -| 4 KiB | 7 214 | 13 182 | 2 737 | 11 149 | 5 359 | -| 1 MiB | 5 386 | 6 679 | 2 580 | 6 253 | 4 561 | +| 20 B | 1 190 | 1 144 | 899 | 842 | 837 | +| 64 B | 2 974 | 2 758 | 1 779 | 1 730 | 1 730 | +| 256 B | 5 682 | 5 437 | 2 819 | 4 426 | 3 536 | +| 1500 B | 7 288 | 11 204 | 3 186 | 9 409 | 4 838 | +| 4 KiB | 7 527 | 13 620 | 3 309 | 11 777 | 5 413 | +| 1 MiB | 5 454 | 6 975 | 3 032 | 6 777 | 4 679 | The 64-bit portable loop is already fast, so the NEON kernel starts at 512 bytes and is 1.5-1.8× faster at -1500 B-4 KiB (1.24× at 1 MiB). In 32-bit mode the kernels start at 192 bytes: NEON is 4.1× and `ldm` 2.0× faster at +1500 B-4 KiB (1.28× at 1 MiB). In 32-bit mode the kernels start at 192 bytes: NEON is 3.6× and `ldm` 1.6× faster at 4 KiB. Below the thresholds every build runs the portable loop, and the differences there come from code layout. -The table predates the current portable loop, which is 1.1-1.45× faster in AArch64 and 1.05-1.4× faster in AArch32 up -to 256 B. In the comparison harness, whose figures are lower than this table's, AArch64 takes 957 MB/s at 20 B, 1.10× -Linux v7.3-rc5 `do_csum`, which reads whole 8-byte words and masks off the bytes past the end. +In the comparison harness, whose figures are lower than this table's, AArch64 takes 957 MB/s at 20 B, 1.10× Linux +v7.3-rc5 `do_csum`, which reads whole 8-byte words and masks off the bytes past the end. ### 6.3 Cortex-M4: nRF52840 at 64 MHz, STM32L4A6 at 80 MHz @@ -149,19 +149,19 @@ address modulo 4: 2 is typical for an IP header behind a 14-byte Ethernet header | Input | nRF52840 portable | nRF52840 `ldm` | STM32L4A6 portable | STM32L4A6 `ldm` | | --- | --- | --- | --- | --- | -| 20 B | 10.3 | 10.0 | 12.9 | 12.5 | -| 64 B | 24.4 | 23.4 | 30.5 | 29.3 | -| 256 B | 40.2 | 49.5 | 50.2 | 61.9 | -| 1500 B | 48.5 | 80.1 | 60.6 | 100.2 | -| 4 KiB | 50.3 | 91.9 | 62.9 | 114.9 | -| 1500 B, offset 2 | 40.8 | 80.4 | 51.0 | 100.5 | -| 4 KiB, offset 1 | 36.1 | 88.7 | 45.2 | 110.9 | - -Per byte at 4 KiB, the kernel takes 0.70 cycles against 1.27 for the portable loop: 1.8× faster, 1.2× at 256 bytes, +| 20 B | 10.8 | 10.5 | 13.4 | 13.1 | +| 64 B | 23.3 | 22.6 | 29.1 | 28.3 | +| 256 B | 39.4 | 52.0 | 49.2 | 65.0 | +| 1500 B | 48.9 | 82.6 | 61.1 | 103.4 | +| 4 KiB | 50.3 | 92.6 | 62.8 | 115.7 | +| 1500 B, offset 2 | 41.0 | 81.1 | 51.3 | 101.9 | +| 4 KiB, offset 1 | 36.1 | 90.2 | 45.1 | 112.8 | + +Per byte at 4 KiB, the kernel takes 0.69 cycles against 1.27 for the portable loop: 1.8× faster, 1.3× at 256 bytes, and up to 2.5× from odd or 2-modulo-4 addresses, where the portable loop's unaligned loads cost more. Both chips run the -same cycles per byte, so the figures scale with the clock. The table predates the current portable loop: in a separate -harness on the nRF52840, the `ldm` build of the current code is 1.22× faster than before at 20 B, 1.08× at 64 B and -1.15× at 256 B. At 191 bytes it takes 345 cycles against 273 for the kernel at 192, so the threshold could move lower. +same cycles per byte, so the figures scale with the clock. Below 192 bytes both builds run the portable loop: 191 bytes +take 346 cycles against 273 for the kernel at 192. The kernel breaks even at 120-160 bytes, depending on the start +address, so the threshold could move lower. ### 6.4 Code size diff --git a/src/include_private/checksum_private/arm/internet.hpp b/src/include_private/checksum_private/arm/internet.hpp index 88db974..d6c1083 100644 --- a/src/include_private/checksum_private/arm/internet.hpp +++ b/src/include_private/checksum_private/arm/internet.hpp @@ -26,7 +26,8 @@ inline constexpr bool block_sum_available = true; #if defined(__ARM_NEON) -// Where the kernel overtakes the portable loop on a Cortex-A72: the 64-bit loop is fast, the 32-bit one is not. +// Above where the kernel overtakes the portable loop on a Cortex-A72, about 370 bytes in AArch64 and 110 in AArch32: +// the 64-bit loop is fast, the 32-bit one is not. #if defined(__aarch64__) inline constexpr std::size_t block_sum_minimum_size = 512; #else diff --git a/src/include_private/checksum_private/x86_64/internet.hpp b/src/include_private/checksum_private/x86_64/internet.hpp index c86ae3f..b08bdbd 100644 --- a/src/include_private/checksum_private/x86_64/internet.hpp +++ b/src/include_private/checksum_private/x86_64/internet.hpp @@ -18,7 +18,7 @@ namespace checksum::internet_detail { inline constexpr bool block_sum_available = true; -// Below about 450 bytes the portable loop is faster on a Core Ultra 7 155H: the kernel pays for the call and the reduction. +// Below about 350 bytes the portable loop is faster on a Core Ultra 7 155H: the kernel pays for the call and the reduction. inline constexpr std::size_t block_sum_minimum_size = 512; inline constexpr std::size_t vector_block_size = 64;