| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
#include <aws/checksums/private/crc_util.h> |
| 6 |
#include <stddef.h> |
| 7 |
|
| 8 |
#if defined(__SIZEOF_INT128__) |
| 9 |
static inline int s_msb_128(const __uint128_t x) { |
| 10 |
|
| 11 |
if (x >> 64) { |
| 12 |
return 127 - __builtin_clzll((uint64_t)(x >> 64)); |
| 13 |
} |
| 14 |
return x ? 63 - __builtin_clzll((uint64_t)x) : -1; |
| 15 |
} |
| 16 |
|
| 17 |
static inline int s_lsb_128(const __uint128_t x) { |
| 18 |
|
| 19 |
if ((uint64_t)x) { |
| 20 |
return __builtin_ctzll((uint64_t)x); |
| 21 |
} |
| 22 |
return (x >> 64) ? 64 + __builtin_ctzll((uint64_t)(x >> 64)) : -1; |
| 23 |
} |
| 24 |
|
| 25 |
static inline __uint128_t s_pow_2(const int n) { |
| 26 |
return ((__uint128_t)1) << n; |
| 27 |
} |
| 28 |
|
| 29 |
static inline __uint128_t s_msb_mask(const __uint128_t x) { |
| 30 |
return s_pow_2(s_msb_128(x)); |
| 31 |
} |
| 32 |
|
| 33 |
__uint128_t aws_checksums_multiply_mod_p_reflected(const __uint128_t poly, __uint128_t a, __uint128_t b) { |
| 34 |
|
| 35 |
if (!a || !b) |
| 36 |
return 0; |
| 37 |
__uint128_t hi_bit = s_msb_mask(poly) >> 1; |
| 38 |
|
| 39 |
int swap = s_lsb_128(b) > s_lsb_128(a); |
| 40 |
__uint128_t x = swap ? b : a; |
| 41 |
__uint128_t y = swap ? a : b; |
| 42 |
__uint128_t product = 0; |
| 43 |
|
| 44 |
while (x) { |
| 45 |
|
| 46 |
if (y & 1) { |
| 47 |
|
| 48 |
y ^= poly; |
| 49 |
} |
| 50 |
y >>= 1; |
| 51 |
|
| 52 |
if (x & hi_bit) { |
| 53 |
product ^= y; |
| 54 |
|
| 55 |
x ^= hi_bit; |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
hi_bit >>= 1; |
| 60 |
} |
| 61 |
return product; |
| 62 |
} |
| 63 |
#endif |