View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.kryo;
15  
16  /**
17   * CRC-16/CCITT-FALSE ({@code poly=0x1021}, {@code init=0xFFFF}, no xorout, unreflected).
18   *
19   * <p>Known vector: {@code "123456789"} → {@code 0x29B1}.
20   *
21   * <p>One payload byte is one table lookup, not an 8-step bit loop.
22   */
23  public final class Crc16 {
24  
25      public static final int POLY = 0x1021;
26      public static final int INIT = 0xFFFF;
27  
28      private static final int[] TABLE = new int[256];
29  
30      static {
31          for (int i = 0; i < 256; i++) {
32              int c = i << 8;
33              for (int bit = 0; bit < 8; bit++) {
34                  if ((c & 0x8000) != 0) {
35                      c = (c << 1) ^ POLY;
36                  } else {
37                      c <<= 1;
38                  }
39                  c &= 0xFFFF;
40              }
41              TABLE[i] = c;
42          }
43      }
44  
45      private int crc = INIT;
46  
47      public void update(int b) {
48          crc = ((crc << 8) ^ TABLE[((crc >>> 8) ^ (b & 0xFF)) & 0xFF]) & 0xFFFF;
49      }
50  
51      public void update(byte[] data) {
52          update(data, 0, data.length);
53      }
54  
55      public void update(byte[] data, int off, int len) {
56          int c = crc;
57          int end = off + len;
58          for (int i = off; i < end; i++) {
59              c = ((c << 8) ^ TABLE[((c >>> 8) ^ (data[i] & 0xFF)) & 0xFF]) & 0xFFFF;
60          }
61          crc = c;
62      }
63  
64      public int getValue() {
65          return crc & 0xFFFF;
66      }
67  
68      public static int of(byte[] data) {
69          Crc16 crc = new Crc16();
70          crc.update(data);
71          return crc.getValue();
72      }
73  }