Coverage Report

Created: 2025-11-16 07:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/Userland/Libraries/LibCrypto/Checksum/CRC16.h
Line
Count
Source
1
/*
2
 * Copyright (c) 2023, kleines Filmröllchen <filmroellchen@serenityos.org>.
3
 *
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 */
6
7
#pragma once
8
9
#include <AK/Endian.h>
10
#include <AK/Format.h>
11
#include <AK/Types.h>
12
#include <LibCrypto/Checksum/ChecksumFunction.h>
13
14
namespace Crypto::Checksum {
15
16
// A generic 16-bit Cyclic Redundancy Check.
17
// Just like CRC32, this class receives its polynomial little-endian.
18
// For example, the polynomial x¹⁶ + x¹² + x⁵ + 1 is represented as 0x8408.
19
template<u16 polynomial>
20
class CRC16 : public ChecksumFunction<u16> {
21
public:
22
    static constexpr u16 be_polynomial = bitswap(polynomial);
23
24
    // This is a big endian table, while CRC-32 uses a little endian table.
25
    static constexpr auto generate_table()
26
0
    {
27
0
        Array<u16, 256> data {};
28
0
        data[0] = 0;
29
0
        u16 value = 0x8000;
30
0
        auto i = 1u;
31
0
        do {
32
0
            if ((value & 0x8000) != 0) {
33
0
                value = be_polynomial ^ (value << 1);
34
0
            } else {
35
0
                value = value << 1;
36
0
            }
37
0
38
0
            for (auto j = 0u; j < i; ++j) {
39
0
                data[i + j] = value ^ data[j];
40
0
            }
41
0
            i <<= 1;
42
0
        } while (i < 256);
43
0
44
0
        return data;
45
0
    }
46
47
    static constexpr auto table = generate_table();
48
49
    virtual ~CRC16() = default;
50
51
114k
    CRC16() = default;
52
    CRC16(ReadonlyBytes data)
53
    {
54
        update(data);
55
    }
56
57
    CRC16(u16 initial_state, ReadonlyBytes data)
58
        : m_state(initial_state)
59
    {
60
        update(data);
61
    }
62
63
    // FIXME: This implementation is naive and slow.
64
    //        Figure out how to adopt the slicing-by-8 algorithm (see CRC32) for 16-bit polynomials.
65
    virtual void update(ReadonlyBytes data) override
66
4.72M
    {
67
9.44M
        for (size_t i = 0; i < data.size(); i++) {
68
4.72M
            size_t table_index = ((m_state >> 8) ^ data.at(i)) & 0xFF;
69
4.72M
            m_state = (table[table_index] ^ (static_cast<u32>(m_state) << 8)) & 0xFFFF;
70
4.72M
        }
71
4.72M
    }
72
73
    virtual u16 digest() override
74
114k
    {
75
114k
        return m_state;
76
114k
    }
77
78
private:
79
    u16 m_state { 0 };
80
};
81
82
}