blob: 71d9ee17ec8f423148bcd0dd949c8a83e11c5d0f [file] [log] [blame]
// Copyright 2019 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/algorithms/privacy/hash.h"
#include <farmhash.h>
#include <vector>
namespace cobalt {
namespace {
size_t TruncateDigest(uint64_t digest, size_t max) {
// TODO(fxbug.dev/87118): Use a truncation method that preserves the uniformity of
// the distribution even if max is not a power of 2.
return digest % max;
}
} // namespace
// TODO(fxbug.dev/85571): NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
uint64_t Hash64WithSeed(const uint8_t* data, size_t len, uint64_t seed) {
std::vector<uint8_t> seeded_data(sizeof(uint64_t) + len);
*(reinterpret_cast<uint64_t*>(seeded_data.data())) = seed;
std::copy(data, data + len, seeded_data.data() + sizeof(uint64_t));
return farmhash::Fingerprint64(reinterpret_cast<char*>(seeded_data.data()), seeded_data.size());
}
uint64_t Hash64WithSeed(const std::string& data, uint64_t seed) {
return Hash64WithSeed(reinterpret_cast<const uint8_t*>(data.data()), data.size(), seed);
}
size_t TruncatedDigest(const uint8_t* data, size_t len, uint64_t seed, size_t max) {
return TruncateDigest(Hash64WithSeed(data, len, seed), max);
}
size_t TruncatedDigest(const std::string& data, uint64_t seed, size_t max) {
return TruncateDigest(Hash64WithSeed(data, seed), max);
}
} // namespace cobalt