001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v2.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.kryo;
015
016/**
017 * CRC-16/CCITT-FALSE ({@code poly=0x1021}, {@code init=0xFFFF}, no xorout, unreflected).
018 *
019 * <p>Known vector: {@code "123456789"} → {@code 0x29B1}.
020 *
021 * <p>One payload byte is one table lookup, not an 8-step bit loop.
022 */
023public final class Crc16 {
024
025    public static final int POLY = 0x1021;
026    public static final int INIT = 0xFFFF;
027
028    private static final int[] TABLE = new int[256];
029
030    static {
031        for (int i = 0; i < 256; i++) {
032            int c = i << 8;
033            for (int bit = 0; bit < 8; bit++) {
034                if ((c & 0x8000) != 0) {
035                    c = (c << 1) ^ POLY;
036                } else {
037                    c <<= 1;
038                }
039                c &= 0xFFFF;
040            }
041            TABLE[i] = c;
042        }
043    }
044
045    private int crc = INIT;
046
047    public void update(int b) {
048        crc = ((crc << 8) ^ TABLE[((crc >>> 8) ^ (b & 0xFF)) & 0xFF]) & 0xFFFF;
049    }
050
051    public void update(byte[] data) {
052        update(data, 0, data.length);
053    }
054
055    public void update(byte[] data, int off, int len) {
056        int c = crc;
057        int end = off + len;
058        for (int i = off; i < end; i++) {
059            c = ((c << 8) ^ TABLE[((c >>> 8) ^ (data[i] & 0xFF)) & 0xFF]) & 0xFFFF;
060        }
061        crc = c;
062    }
063
064    public int getValue() {
065        return crc & 0xFFFF;
066    }
067
068    public static int of(byte[] data) {
069        Crc16 crc = new Crc16();
070        crc.update(data);
071        return crc.getValue();
072    }
073}