1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.kryo;
15
16
17
18
19
20
21
22 public final class Crc3 {
23
24 public static final int POLY = 0b1011;
25 public static final int MASK = 0b111;
26
27
28 private static final int[] TABLE = new int[256];
29
30
31 private static final int[] ZERO8 = new int[8];
32
33 static {
34 for (int b = 0; b < 256; b++) {
35 TABLE[b] = crcByteSlow(0, b);
36 }
37 for (int c = 0; c < 8; c++) {
38 ZERO8[c] = crcByteSlow(c, 0);
39 }
40 }
41
42 private int crc;
43
44 static int crcByteSlow(int crc, int b) {
45 int c = crc & MASK;
46 for (int i = 7; i >= 0; i--) {
47 c = step(c, (b >>> i) & 1);
48 }
49 return c;
50 }
51
52 static int step(int crc, int bit) {
53 int mix = ((crc >>> 2) ^ (bit & 1)) & 1;
54 crc = (crc << 1) & MASK;
55 if (mix != 0) {
56 crc ^= 0b011;
57 }
58 return crc;
59 }
60
61 public void updateBit(int bit) {
62 crc = step(crc, bit);
63 }
64
65
66 public void updateBits(int value, int nbits) {
67 for (int i = nbits - 1; i >= 0; i--) {
68 updateBit((value >>> i) & 1);
69 }
70 }
71
72 public void update(int b) {
73 crc = tableByte(crc, b);
74 }
75
76
77 static int tableByte(int crc, int b) {
78 return ZERO8[crc & MASK] ^ TABLE[b & 0xFF];
79 }
80
81 public void update(byte[] data, int off, int len) {
82 int c = crc;
83 int end = off + len;
84 for (int i = off; i < end; i++) {
85 c = ZERO8[c] ^ TABLE[data[i] & 0xFF];
86 }
87 crc = c;
88 }
89
90 public int getValue() {
91 return crc & MASK;
92 }
93
94 public void reset() {
95 crc = 0;
96 }
97 }