Comms CCF
This is a simple communication layer based on COBS, CBOR and FNV-1A
Loading...
Searching...
No Matches
fnv1a.hpp
Go to the documentation of this file.
1
24
25#pragma once
26
27#if defined(DEBUG_FNV1A)
28#include DEBUG_FNV1A
29#else
30#include "ndebug.hpp"
31#endif
32
33#include <stddef.h>
34#include <stdint.h>
35
36#include <span>
37
38namespace Fnv1a
39{
40 constexpr uint32_t initialHash = 0x811c9dc5;
41 constexpr size_t size = sizeof(initialHash);
42
44 constexpr uint32_t feed(uint32_t hash, uint8_t byte)
45 {
46 hash ^= byte;
47 hash *= 0x01000193;
48 return hash;
49 }
50
52 template<size_t Size>
53 constexpr uint32_t checksum(std::span<uint8_t, Size> span, uint32_t hash = initialHash)
54 {
55 for (auto c : span)
56 {
57 hash = feed(hash, c);
58 }
59 return hash;
60 }
61
64 template<size_t Size>
65 constexpr void putAtEnd(std::span<uint8_t, Size> span, uint32_t hash = initialHash)
66 {
67 size_t end = span.size();
68 if (end < 4)
69 {
70 return;
71 }
72 const uint32_t got = checksum(span.first(end - 4), hash);
73 span[end - 4] = static_cast<uint8_t>(got >> 0);
74 span[end - 3] = static_cast<uint8_t>(got >> 8);
75 span[end - 2] = static_cast<uint8_t>(got >> 16);
76 span[end - 1] = static_cast<uint8_t>(got >> 24);
77 }
78
81 template<size_t Size>
82 constexpr bool checkAtEnd(std::span<uint8_t, Size> span, uint32_t hash = initialHash)
83 {
84 size_t end = span.size();
85 if (end < 4)
86 {
87 return false;
88 }
89 const uint32_t got = checksum(span.first(end - 4), hash);
90 const uint32_t expected =
91 (static_cast<uint32_t>(span[end - 4]) << 0) |
92 (static_cast<uint32_t>(span[end - 3]) << 8) |
93 (static_cast<uint32_t>(span[end - 2]) << 16) |
94 (static_cast<uint32_t>(span[end - 1]) << 24);
95 if (got == expected)
96 {
97 debugf(INFO "Checksum OK" END LOGLEVEL_ARGS);
98 }
99 else
100 {
101 debugf(INFO "Checksum got %08X expected %08X" END LOGLEVEL_ARGS, got, expected);
102 }
103 return got == expected;
104 }
105};
106
107// This is a header, undefine the debugf macro
108#include "debug_end.hpp"
constexpr void putAtEnd(std::span< uint8_t, Size > span, uint32_t hash=initialHash)
Definition fnv1a.hpp:65
constexpr bool checkAtEnd(std::span< uint8_t, Size > span, uint32_t hash=initialHash)
Definition fnv1a.hpp:82
constexpr uint32_t feed(uint32_t hash, uint8_t byte)
Update the hash with the given byte.
Definition fnv1a.hpp:44
constexpr uint32_t checksum(std::span< uint8_t, Size > span, uint32_t hash=initialHash)
Compute the hash over the given span.
Definition fnv1a.hpp:53
#define debugf(...)
Definition ndebug.hpp:23
#define END
Terminator of log message at the end.
Definition ndebug.hpp:50
#define LOGLEVEL_ARGS
Definition ndebug.hpp:28