Imported Upstream version 1.46.0
[platform/upstream/nghttp2.git] / third-party / mruby / src / crc.c
1 /*
2 ** crc.c - calculate CRC
3 **
4 ** See Copyright Notice in mruby.h
5 */
6
7 #include <limits.h>
8 #include <stdint.h>
9 #include <stddef.h>
10
11 /* Calculate CRC (CRC-16-CCITT)
12 **
13 **  0000_0000_0000_0000_0000_0000_0000_0000
14 **          ^|------- CRC -------|- work --|
15 **        carry
16 */
17 #define  CRC_16_CCITT       0x11021ul        /* x^16+x^12+x^5+1 */
18 #define  CRC_XOR_PATTERN    (CRC_16_CCITT << 8)
19 #define  CRC_CARRY_BIT      (0x01000000)
20
21 uint16_t
22 calc_crc_16_ccitt(const uint8_t *src, size_t nbytes, uint16_t crc)
23 {
24   size_t ibyte;
25   uint32_t ibit;
26   uint32_t crcwk = crc << 8;
27
28   for (ibyte = 0; ibyte < nbytes; ibyte++) {
29     crcwk |= *src++;
30     for (ibit = 0; ibit < CHAR_BIT; ibit++) {
31       crcwk <<= 1;
32       if (crcwk & CRC_CARRY_BIT) {
33         crcwk ^= CRC_XOR_PATTERN;
34       }
35     }
36   }
37   return (uint16_t)(crcwk >> 8);
38 }
39