blob: 4bd9892a50223b9be1ff1aa93e2f0163cadeee3b [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 <vector>
#include "third_party/github.com/google/farmhash/src/farmhash.h"
namespace cobalt {
namespace {
size_t TruncateDigest(uint64_t digest, size_t max) {
// TODO(azani): Use a truncation method that preserves the uniformity of
// the distribution even if max is not a power of 2.
return digest % max;
}
} // namespace
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