Comms CCF
This is a simple communication layer based on COBS, CBOR and FNV-1A
Loading...
Searching...
No Matches
fnv1a.hpp File Reference

Simple non-cryptographic hash with decent performance. More...

#include "ndebug.hpp"
#include <stddef.h>
#include <stdint.h>
#include <span>
#include "debug_end.hpp"

Go to the source code of this file.

Functions

constexpr uint32_t Fnv1a::feed (uint32_t hash, uint8_t byte)
 Update the hash with the given byte.
template<size_t Size>
constexpr uint32_t Fnv1a::checksum (std::span< uint8_t, Size > span, uint32_t hash=initialHash)
 Compute the hash over the given span.
template<size_t Size>
constexpr void Fnv1a::putAtEnd (std::span< uint8_t, Size > span, uint32_t hash=initialHash)
template<size_t Size>
constexpr bool Fnv1a::checkAtEnd (std::span< uint8_t, Size > span, uint32_t hash=initialHash)

Variables

constexpr uint32_t Fnv1a::initialHash = 0x811c9dc5
constexpr size_t Fnv1a::size = sizeof(initialHash)

Detailed Description

Simple non-cryptographic hash with decent performance.

FNV-1A hash

To verify message integrity, you need some kind of a checksum or hash. I have chosen the FNV-1A hash because it is extremely simple to implement in software (only marginally more complicated than the "add every byte" hash sometimes known as lose-lose because of its terrible performance).

There are faster hashes (they tend to be faster because they work more than a byte at a time) but when the input is slowly coming over UART this works perfectly fine.

This isn't meant to be a cryptographic hash (FNV-1A was never intended to be that). So it isn't used for signing, only to detect errors.

For a simple comparison of other hashes, see test/hash_comparison.py but for a much better one see https://softwareengineering.stackexchange.com/a/145633

Function Documentation

◆ checkAtEnd()

template<size_t Size>
bool Fnv1a::checkAtEnd ( std::span< uint8_t, Size > span,
uint32_t hash = initialHash )
constexpr

Checks that the span[:-4] sums to the same has as is stored at span[-4:].

◆ putAtEnd()

template<size_t Size>
void Fnv1a::putAtEnd ( std::span< uint8_t, Size > span,
uint32_t hash = initialHash )
constexpr

Computes the hash on span[:-4] and places it at the end of the span.