OpenMS
Loading...
Searching...
No Matches
HashUtils.h
Go to the documentation of this file.
1// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
2// SPDX-License-Identifier: BSD-3-Clause
3//
4// --------------------------------------------------------------------------
5// $Maintainer: OpenMS Team $
6// $Authors: OpenMS Team $
7// --------------------------------------------------------------------------
8
9#pragma once
10
11#include <cstddef>
12#include <cstdint>
13#include <functional>
14#include <string>
15#include <type_traits>
16
17namespace OpenMS
18{
48 inline std::size_t fnv1a_hash_bytes(const void* data, std::size_t size) noexcept
49 {
50 const auto* bytes = static_cast<const unsigned char*>(data);
51 // FNV-1a 64-bit constants
52 std::size_t hash = 14695981039346656037ull; // FNV offset basis
53 for (std::size_t i = 0; i < size; ++i)
54 {
55 hash ^= bytes[i];
56 hash *= 1099511628211ull; // FNV prime
57 }
58 return hash;
59 }
60
70 inline std::size_t fnv1a_hash_string(const std::string& s) noexcept
71 {
72 return fnv1a_hash_bytes(s.data(), s.size());
73 }
74
87 inline void hash_combine(std::size_t& seed, std::size_t value) noexcept
88 {
89 seed ^= value + 0x9e3779b97f4a7c15 + (seed << 6) + (seed >> 2);
90 }
91
106 template<typename T>
107 inline std::size_t hash_int(T value) noexcept
108 {
109 static_assert(std::is_integral_v<T>, "hash_int requires an integral type");
110 return fnv1a_hash_bytes(&value, sizeof(T));
111 }
112
119 inline std::size_t hash_char(char c) noexcept
120 {
121 // Apply FNV-1a algorithm for single character
122 std::size_t hash = 14695981039346656037ull;
123 hash ^= static_cast<unsigned char>(c);
124 hash *= 1099511628211ull;
125 return hash;
126 }
127
141 template<typename T>
142 inline std::size_t hash_float(T value) noexcept
143 {
144 static_assert(std::is_floating_point_v<T>, "hash_float requires a floating point type");
145 // Normalize -0.0 to +0.0 (they compare equal but have different bit patterns)
146 if (value == T(0)) value = T(0);
147 return fnv1a_hash_bytes(&value, sizeof(T));
148 }
149
150} // namespace OpenMS
std::size_t fnv1a_hash_bytes(const void *data, std::size_t size) noexcept
Hash utilities for OpenMS classes.
Definition HashUtils.h:48
Main OpenMS namespace.
Definition openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h:19
std::size_t hash_int(T value) noexcept
Hash for an integer type.
Definition HashUtils.h:107
void hash_combine(std::size_t &seed, std::size_t value) noexcept
Combine a hash value with additional data using golden ratio mixing.
Definition HashUtils.h:87
std::size_t hash_char(char c) noexcept
Hash for a character.
Definition HashUtils.h:119
std::size_t hash_float(T value) noexcept
Hash for a floating point type (float or double).
Definition HashUtils.h:142
std::size_t fnv1a_hash_string(const std::string &s) noexcept
FNV-1a hash for a string.
Definition HashUtils.h:70