blob: 3793d9abdc3afdcde0ae328bb34d6a62ebe05d58 [file] [log] [blame]
Patrick Ventureef3aead2018-09-12 08:53:29 -07001#pragma once
2
3#include <cstdint>
4
5namespace blobs
6{
7
8using std::size_t;
9using std::uint16_t;
10using std::uint32_t;
11using std::uint8_t;
12
13constexpr uint16_t crc16Ccitt = 0x1021;
14/* Value from: http://srecord.sourceforge.net/crc16-ccitt.html for
15 * implementation without explicit bit adding.
16 */
17constexpr uint16_t crc16Initial = 0xFFFF;
18
19class CrcInterface
20{
21 public:
22 virtual ~CrcInterface() = default;
23
24 /**
25 * Reset the crc.
26 */
27 virtual void clear() = 0;
28
29 /**
30 * Provide bytes against which to compute the crc. This method is
31 * meant to be only called once between clear() and get().
32 *
33 * @param[in] bytes - the data against which to compute.
34 * @param[in] length - the number of bytes.
35 */
36 virtual void compute(const uint8_t* bytes, uint32_t length) = 0;
37
38 /**
39 * Read back the current crc value.
40 *
41 * @return the crc16 value.
42 */
43 virtual uint16_t get() const = 0;
44};
45
46class Crc16 : public CrcInterface
47{
48 public:
49 Crc16() : poly(crc16Ccitt), value(crc16Initial){};
50 ~Crc16() = default;
51
52 void clear() override;
53 void compute(const uint8_t* bytes, uint32_t length) override;
54 uint16_t get() const override;
55
56 private:
57 uint16_t poly;
58 uint16_t value;
59};
60} // namespace blobs