summaryrefslogtreecommitdiffstats
path: root/crc.hpp
blob: 3793d9abdc3afdcde0ae328bb34d6a62ebe05d58 (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
#pragma once

#include <cstdint>

namespace blobs
{

using std::size_t;
using std::uint16_t;
using std::uint32_t;
using std::uint8_t;

constexpr uint16_t crc16Ccitt = 0x1021;
/* Value from: http://srecord.sourceforge.net/crc16-ccitt.html for
 * implementation without explicit bit adding.
 */
constexpr uint16_t crc16Initial = 0xFFFF;

class CrcInterface
{
  public:
    virtual ~CrcInterface() = default;

    /**
     * Reset the crc.
     */
    virtual void clear() = 0;

    /**
     * Provide bytes against which to compute the crc.  This method is
     * meant to be only called once between clear() and get().
     *
     * @param[in] bytes - the data against which to compute.
     * @param[in] length - the number of bytes.
     */
    virtual void compute(const uint8_t* bytes, uint32_t length) = 0;

    /**
     * Read back the current crc value.
     *
     * @return the crc16 value.
     */
    virtual uint16_t get() const = 0;
};

class Crc16 : public CrcInterface
{
  public:
    Crc16() : poly(crc16Ccitt), value(crc16Initial){};
    ~Crc16() = default;

    void clear() override;
    void compute(const uint8_t* bytes, uint32_t length) override;
    uint16_t get() const override;

  private:
    uint16_t poly;
    uint16_t value;
};
} // namespace blobs
OpenPOWER on IntegriCloud