From: Mikko Rasa Date: Wed, 17 Nov 2021 12:15:18 +0000 (+0200) Subject: Add some more hash utility functions X-Git-Url: http://git.tdb.fi/?a=commitdiff_plain;h=7533857dc04c1f3a1fd6c509a194b4d7f0ab3cdd;p=libs%2Fcore.git Add some more hash utility functions --- diff --git a/source/core/hash.h b/source/core/hash.h index a7e8cb1..e2201cf 100644 --- a/source/core/hash.h +++ b/source/core/hash.h @@ -62,6 +62,38 @@ struct HashTraits static constexpr bool folded = true; }; +/** +Computes a single round of a hash, adding one byte of data. N must be a native +hash size. +*/ +template +typename HashTraits::ResultType hash_round(typename HashTraits::HashType result, uint8_t byte) +{ + constexpr typename HashTraits::HashType prime = HashTraits::prime; + return (result^byte)*prime; +} + +/** +Updates a previously computed hash by adding bytes to it. N must be a native +hash size. +*/ +template +typename HashTraits::ResultType hash_update(typename HashTraits::HashType result, const void *data, std::size_t size) +{ + const uint8_t *ptr = static_cast(data); + for(unsigned i=0; i(result, *ptr++); + return result; +} + +template +typename HashTraits::ResultType hash_update(typename HashTraits::HashType result, const std::string &str) +{ return hash_update(result, str.data(), str.size()); } + +// For some reason this causes an ambiguity error without the enable_if. +template +typename std::enable_if::value, typename HashTraits::ResultType>::type hash_update(typename HashTraits::HashType result, const T &obj) +{ return hash_update(result, &obj, sizeof(obj)); } /** Manually folds a hash to a smaller size. @@ -86,10 +118,7 @@ template typename HashTraits::ResultType hash(const void *data, std::size_t size) { constexpr unsigned hash_bits = std::numeric_limits::HashType>::digits; - constexpr typename HashTraits::HashType prime = HashTraits::prime; - typename HashTraits::HashType result = HashTraits::offset; - for(unsigned i=0; i(data)+i))*prime; + typename HashTraits::HashType result = hash_update(HashTraits::offset, data, size); if(HashTraits::folded) result = hash_fold(result); return result; @@ -102,6 +131,14 @@ template typename HashTraits::ResultType hash(const std::string &str) { return hash(str.data(), str.size()); } +/** +Convenience function to compute an N-bit hash of any object. The entire object +representation is hashed, including any padding bytes. +*/ +template +typename HashTraits::ResultType hash(const T &obj) +{ return hash(&obj, sizeof(obj)); } + } // namespace Msp #endif