Header hash.h

This header provides hash-related helper functions and common hash algorithms. The algorithms are constexpr enabled if possible.

Note

Unless specified otherwise, if the digest type of a hasher is a std::array of unsigned integers (words), the most significant word always comes last (little endian). The individual words are in native byte order, which may not be little endian.

Examples

The following code snippet reads a file and computes SHA-1 hash of the contents:

 1#include <iostream>
 2#include <format>
 3#include <clu/file.h>
 4#include <clu/hash.h>
 5
 6int main()
 7{
 8    const auto bytes = clu::read_all_bytes("my_file.txt");
 9    const auto hash = clu::sha1(bytes);
10    std::cout << std::format("SHA-1: {:08x}{:08x}{:08x}{:08x}{:08x}\n",
11        hash[0], hash[1], hash[2], hash[3], hash[4]);
12}

We cannot use strings in switch-es, but utilizing the constexpr hash algorithms we are able to imitate that feature. Hash conflicts of cases are also detected at compile time which is neat. Just don’t use this on arbitrary user inputs, where weird (read “malicious”) hash clashes may occur.

 1#include <clu/hash.h>
 2
 3int main()
 4{
 5    using namespace clu::literals;     // for enabling the UDLs
 6    switch (clu::fnv1a("second"))      // regular function call
 7    {
 8        case "first"_fnv1a: return 1;  // or use UDLs
 9        case "second"_fnv1a: return 2;
10        case "third"_fnv1a: return 3;
11    }
12}