Debian Codegraph @

crt/aws-checksums/source/crc_util.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
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 // __builtin_clzll returns the number of leading zeros (from MSB end) - undefined for x==0 !!!
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 // __builtin_ctzll returns the number of trailing zeros (from LSB end) - undefined for x==0 !!!
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 // Choose the factor with the most trailing zero bits so the loop can exit soonest
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 // Loop through the bits in the x factor
44 while (x) {
45 // Every iteration will keep doubling the y factor using right shifts (it's bit-reflected)
46 if (y & 1) {
47 // But when the field degree bit is set, first reduce using the field polynomial
48 y ^= poly;
49 }
50 y >>= 1;
51
52 if (x & hi_bit) {
53 product ^= y;
54 // Clear the bit in x so the loop will quit when there are no more bits set
55 x ^= hi_bit;
56 }
57
58 // Advance to test the next lowest bit in x
59 hi_bit >>= 1;
60 }
61 return product;
62 }
63 #endif