/src/serenity/Userland/Libraries/LibCrypto/Checksum/CRC8.h
Line | Count | Source (jump to first uncovered line) |
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/Types.h> |
10 | | #include <LibCrypto/Checksum/ChecksumFunction.h> |
11 | | |
12 | | namespace Crypto::Checksum { |
13 | | |
14 | | // A generic 8-bit Cyclic Redundancy Check. |
15 | | // Note that as opposed to CRC32, this class operates with MSB first, so the polynomial must not be reversed. |
16 | | // For example, the polynomial x⁸ + x² + x + 1 is represented as 0x07 and not 0xE0. |
17 | | template<u8 polynomial> |
18 | | class CRC8 : public ChecksumFunction<u8> { |
19 | | public: |
20 | | // This is a big endian table, while CRC-32 uses a little endian table. |
21 | | static constexpr auto generate_table() |
22 | 0 | { |
23 | 0 | Array<u8, 256> data {}; |
24 | 0 | u8 value = 0x80; |
25 | 0 | auto i = 1u; |
26 | 0 | do { |
27 | 0 | if ((value & 0x80) != 0) { |
28 | 0 | value = polynomial ^ (value << 1); |
29 | 0 | } else { |
30 | 0 | value = value << 1; |
31 | 0 | } |
32 | 0 |
|
33 | 0 | for (auto j = 0u; j < i; ++j) { |
34 | 0 | data[i + j] = value ^ data[j]; |
35 | 0 | } |
36 | 0 | i <<= 1; |
37 | 0 | } while (i < 256); |
38 | 0 | return data; |
39 | 0 | } |
40 | | |
41 | | static constexpr auto table = generate_table(); |
42 | | |
43 | | virtual ~CRC8() = default; |
44 | | |
45 | 70.3k | CRC8() = default; |
46 | | CRC8(ReadonlyBytes data) |
47 | | { |
48 | | update(data); |
49 | | } |
50 | | |
51 | | CRC8(u8 initial_state, ReadonlyBytes data) |
52 | | : m_state(initial_state) |
53 | | { |
54 | | update(data); |
55 | | } |
56 | | |
57 | | // FIXME: This implementation is naive and slow. |
58 | | // Figure out how to adopt the slicing-by-8 algorithm (see CRC32) for 8 bit polynomials. |
59 | | virtual void update(ReadonlyBytes data) override |
60 | 5.03M | { |
61 | 10.0M | for (size_t i = 0; i < data.size(); i++) { |
62 | 5.03M | size_t table_index = (m_state ^ data.at(i)) & 0xFF; |
63 | 5.03M | m_state = (table[table_index] ^ (static_cast<u32>(m_state) << 8)) & 0xFF; |
64 | 5.03M | } |
65 | 5.03M | } |
66 | | |
67 | | virtual u8 digest() override |
68 | 70.2k | { |
69 | 70.2k | return m_state; |
70 | 70.2k | } |
71 | | |
72 | | private: |
73 | | u8 m_state { 0 }; |
74 | | }; |
75 | | |
76 | | } |