1 // Copyright 2014 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "base/metrics/metrics_hashes.h" 6 7 #include <string.h> 8 9 #include <string_view> 10 11 #include "base/check_op.h" 12 #include "base/containers/span.h" 13 #include "base/hash/md5.h" 14 #include "base/hash/sha1.h" 15 #include "base/numerics/byte_conversions.h" 16 17 namespace base { 18 namespace { 19 20 // Converts the 8-byte prefix of an MD5 hash into a uint64_t value. DigestToUInt64(const MD5Digest & digest)21inline uint64_t DigestToUInt64(const MD5Digest& digest) { 22 return U64FromBigEndian(span(digest.a).first<8u>()); 23 } 24 25 // Converts the 4-byte prefix of an MD5 hash into a uint32_t value. DigestToUInt32(const MD5Digest & digest)26inline uint32_t DigestToUInt32(const MD5Digest& digest) { 27 return U32FromBigEndian(span(digest.a).first<4u>()); 28 } 29 30 } // namespace 31 HashMetricName(std::string_view name)32uint64_t HashMetricName(std::string_view name) { 33 // Corresponding Python code for quick look up: 34 // 35 // import struct 36 // import hashlib 37 // struct.unpack('>Q', hashlib.md5(name.encode('utf-8')).digest()[:8])[0] 38 // 39 MD5Digest digest; 40 MD5Sum(as_byte_span(name), &digest); 41 return DigestToUInt64(digest); 42 } 43 HashMetricNameAs32Bits(std::string_view name)44uint32_t HashMetricNameAs32Bits(std::string_view name) { 45 MD5Digest digest; 46 MD5Sum(as_byte_span(name), &digest); 47 return DigestToUInt32(digest); 48 } 49 HashFieldTrialName(std::string_view name)50uint32_t HashFieldTrialName(std::string_view name) { 51 // SHA-1 is designed to produce a uniformly random spread in its output space, 52 // even for nearly-identical inputs. 53 SHA1Digest sha1_hash = SHA1HashSpan(as_byte_span(name)); 54 return U32FromLittleEndian(span(sha1_hash).first<4u>()); 55 } 56 57 } // namespace base 58