summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibCrypto/Checksum/CRC32.h
blob: 6bb87ef82e645884ab29660578867e892adc8bf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Copyright (c) 2020, the SerenityOS developers
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Span.h>
#include <AK/Types.h>
#include <LibCrypto/Checksum/ChecksumFunction.h>

namespace Crypto::Checksum {

struct Table {
    u32 data[256];

    constexpr Table()
        : data()
    {
        for (auto i = 0; i < 256; i++) {
            u32 value = i;

            for (auto j = 0; j < 8; j++) {
                if (value & 1) {
                    value = 0xEDB88320 ^ (value >> 1);
                } else {
                    value = value >> 1;
                }
            }

            data[i] = value;
        }
    }

    constexpr u32 operator[](int index) const
    {
        return data[index];
    }
};

constexpr static auto table = Table();

class CRC32 : public ChecksumFunction<u32> {
public:
    CRC32() { }
    CRC32(ReadonlyBytes data)
    {
        update(data);
    }

    CRC32(u32 initial_state, ReadonlyBytes data)
        : m_state(initial_state)
    {
        update(data);
    }

    void update(ReadonlyBytes data);
    u32 digest();

private:
    u32 m_state { ~0u };
};

}