11#pragma once
22
3+ #include < bit>
4+ #include < concepts>
5+ #include < cstddef>
36#include < cstdint>
47#include < memory>
58
6- #if __cplusplus >= 202'002L
7- // #error Take into use C++20 std::integral instead of this macro logic
8- #endif
9-
10- #define SUM8_INT_FN (Type ) \
11- constexpr uint8_t Sum8 (Type data) \
12- { \
13- uint8_t result = 0 ; \
14- for (int i = 0 ; i < sizeof (Type); ++i) { \
15- result += static_cast <uint8_t >((data >> (i * 8 )) & 0xFF ); \
16- } \
17- return result; \
18- }
19-
209namespace OpenShock ::Checksum {
10+
11+ // ------------------------------------------------------------
12+ // Raw byte span checksum
13+ // ------------------------------------------------------------
2114 constexpr uint8_t Sum8 (const uint8_t * data, std::size_t size)
2215 {
2316 uint8_t checksum = 0 ;
@@ -26,19 +19,32 @@ namespace OpenShock::Checksum {
2619 }
2720 return checksum;
2821 }
22+
23+ // ------------------------------------------------------------
24+ // Generic integral overload (C++20 concepts)
25+ // ------------------------------------------------------------
26+ template <std::integral T>
27+ constexpr uint8_t Sum8 (T value)
28+ {
29+ uint8_t result = 0 ;
30+
31+ for (std::size_t i = 0 ; i < sizeof (T); ++i) {
32+ result += static_cast <uint8_t >((value >> (i * 8 )) & 0xFF );
33+ }
34+
35+ return result;
36+ }
37+
38+ // ------------------------------------------------------------
39+ // Generic trivially copyable object overload
40+ // ------------------------------------------------------------
2941 template <typename T>
42+ requires (!std::integral<T> && std::is_trivially_copyable_v<T>)
3043 constexpr uint8_t Sum8 (const T& data)
3144 {
3245 return Sum8 (reinterpret_cast <const uint8_t *>(std::addressof (data)), sizeof (T));
3346 }
3447
35- SUM8_INT_FN (int16_t )
36- SUM8_INT_FN (uint16_t )
37- SUM8_INT_FN (int32_t )
38- SUM8_INT_FN (uint32_t )
39- SUM8_INT_FN (int64_t )
40- SUM8_INT_FN (uint64_t )
41-
4248 /* *
4349 * Make sure the uint8 only has its high bits (0x0F) set before using this function
4450 */
0 commit comments