| // Copyright 2020 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| #include "src/lib/util/hash.h" |
| |
| #include <farmhash.h> |
| |
| #include <cstddef> |
| #include <cstdint> |
| #include <initializer_list> |
| #include <string> |
| |
| namespace cobalt::util { |
| namespace { |
| |
| constexpr uint32_t kBytesPerInt64 = 8; |
| constexpr uint32_t kSingleByteMask = 0xFF; |
| |
| char GetByte(const uint64_t value, const size_t idx) { |
| return static_cast<char>(value >> (kBytesPerInt64 * idx) & kSingleByteMask); |
| } |
| |
| std::string LittleEndianBytes(const std::initializer_list<uint64_t> values) { |
| std::string bytes(kBytesPerInt64 * values.size(), '\0'); |
| size_t vi = 0; |
| for (const uint64_t value : values) { |
| for (size_t i = 0; i < kBytesPerInt64; ++i) { |
| bytes[vi + i] = GetByte(value, i); |
| } |
| vi += kBytesPerInt64; |
| } |
| return bytes; |
| } |
| |
| } // namespace |
| |
| std::string FarmhashFingerprint(const std::string &data) { |
| const farmhash::uint128_t fingerprint = farmhash::Fingerprint128(data); |
| return LittleEndianBytes({ |
| farmhash::Uint128Low64(fingerprint), |
| farmhash::Uint128High64(fingerprint), |
| }); |
| } |
| |
| std::string FarmhashFingerprint64(const std::string &data) { |
| return LittleEndianBytes({ |
| farmhash::Fingerprint64(data), |
| }); |
| } |
| |
| uint64_t Farmhash64(const std::string &data) { return farmhash::Fingerprint64(data); } |
| |
| } // namespace cobalt::util |