// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/hash/hash.h" #include <cstddef> #include <cstdint> #include <limits> #include <string> #include <string_view> #include "base/containers/span.h" #include "base/dcheck_is_on.h" #include "base/notreached.h" #include "base/numerics/safe_conversions.h" #include "base/third_party/cityhash/city.h" // Definition in base/third_party/superfasthash/superfasthash.c. (Third-party // code did not come with its own header file, so declaring the function here.) // Note: This algorithm is also in Blink under Source/wtf/StringHasher.h. extern "C" uint32_t SuperFastHash(const char* data, int len); namespace base { namespace { size_t FastHashImpl(base::span<const uint8_t> data) { … } // Implement hashing for pairs of at-most 32 bit integer values. // When size_t is 32 bits, we turn the 64-bit hash code into 32 bits by using // multiply-add hashing. This algorithm, as described in // Theorem 4.3.3 of the thesis "Über die Komplexität der Multiplikation in // eingeschränkten Branchingprogrammmodellen" by Woelfel, is: // // h32(x32, y32) = (h64(x32, y32) * rand_odd64 + rand16 * 2^16) % 2^64 / 2^32 // // Contact [email protected] for any questions. size_t HashInts32Impl(uint32_t value1, uint32_t value2) { … } // Implement hashing for pairs of up-to 64-bit integer values. // We use the compound integer hash method to produce a 64-bit hash code, by // breaking the two 64-bit inputs into 4 32-bit values: // http://opendatastructures.org/versions/edition-0.1d/ods-java/node33.html#SECTION00832000000000000000 // Then we reduce our result to 32 bits if required, similar to above. size_t HashInts64Impl(uint64_t value1, uint64_t value2) { … } // The random seed is used to perturb the output of base::FastHash() and // base::HashInts() so that it is only deterministic within the lifetime of a // process. This prevents inadvertent dependencies on the underlying // implementation, e.g. anything that persists the hash value and expects it to // be unchanging will break. // // Note: this is the same trick absl uses to generate a random seed. This is // more robust than using base::RandBytes(), which can fail inside a sandboxed // environment. Note that without ASLR, the seed won't be quite as random... #if DCHECK_IS_ON() constexpr const void* kSeed = …; #endif template <typename T> T Scramble(T input) { … } } // namespace size_t FastHash(base::span<const uint8_t> data) { … } uint32_t Hash(base::span<const uint8_t> data) { … } uint32_t Hash(const std::string& str) { … } uint32_t PersistentHash(span<const uint8_t> data) { … } uint32_t PersistentHash(std::string_view str) { … } size_t HashInts32(uint32_t value1, uint32_t value2) { … } size_t HashInts64(uint64_t value1, uint64_t value2) { … } } // namespace base