LibQuicR
Loading...
Searching...
No Matches
hash.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (c) 2024 Cisco Systems
2// SPDX-License-Identifier: BSD-2-Clause
3
4#pragma once
5
6#include "quicr/detail/span.h"
7#include <array>
8#include <string_view>
9#include <vector>
10
11namespace quicr {
13 static const std::array<std::uint64_t, 256> crc_table = [] {
14 std::array<std::uint64_t, 256> table;
15 for (std::uint64_t c = 0; c < 256; ++c) {
16 std::uint64_t crc = c;
17 for (std::uint64_t i = 0; i < 8; ++i) {
18 std::uint64_t b = (crc & 1);
19 crc >>= 1;
20 crc ^= (0 - b) & 0xc96c5795d7870f42ull;
21 }
22 table[c] = crc;
23 }
24
25 return table;
26 }();
27
34 static constexpr std::uint64_t hash(const Span<const uint8_t> bytes)
35 {
36
37 constexpr size_t word_len = sizeof(std::uint64_t);
38 std::uint64_t crc = 0;
39
40 if (bytes.size() <= word_len) {
41 std::memcpy(&crc, bytes.data(), bytes.size());
42 return crc;
43 }
44
45 /*
46 const auto word_count = bytes.size() / word_len;
47
48 auto start_it = bytes.begin();
49 for (size_t i = 0; i < word_count; ++i) {
50 uint64_t* word = (uint64_t*)&*start_it;
51
52 crc = crc_table[(crc ^ *word) & 0xFF] ^ (crc >> 8);
53
54 start_it += word_len;
55 }
56
57 for (size_t i = word_count * word_len; i < bytes.size(); i++) {
58 crc = crc_table[(crc & 0xFF) ^ bytes[i]] ^ (crc >> 8);
59 }
60 */
61
62 for (const auto& b : bytes) {
63 crc = crc_table[(crc & 0xFF) ^ b] ^ (crc >> 8);
64 }
65
66 return crc;
67 }
68
76 [[maybe_unused]]
77 static std::uint64_t hash(const std::string_view& str)
78 {
79 return hash(std::vector<uint8_t>{ str.begin(), str.end() });
80 }
81
91 inline void hash_combine(uint64_t& existing_hash, const uint64_t& add_hash)
92 {
93 existing_hash ^= add_hash + 0x9e3779b9 + (existing_hash << 6) + (add_hash >> 2);
94 }
95
96}
Definition transport.h:26
void hash_combine(uint64_t &existing_hash, const uint64_t &add_hash)
Combine (aka add) hash to existing hash.
Definition hash.h:91