1 // Copyright 2018 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
13 #include "base/base_export.h"
14 #include "base/hash.h"
18 // A Token is a randomly chosen 128-bit integer. This class supports generation
19 // from a cryptographically strong random source, or constexpr construction over
20 // fixed values (e.g. to store a pre-generated constant value). Tokens are
21 // similar in spirit and purpose to UUIDs, without many of the constraints and
22 // expectations (such as byte layout and string representation) clasically
23 // associated with UUIDs.
24 class BASE_EXPORT Token {
26 // Constructs a zero Token.
27 constexpr Token() : high_(0), low_(0) {}
29 // Constructs a Token with |high| and |low| as its contents.
30 constexpr Token(uint64_t high, uint64_t low) : high_(high), low_(low) {}
32 // Constructs a new Token with random |high| and |low| values taken from a
33 // cryptographically strong random source.
34 static Token CreateRandom();
36 // The high and low 64 bits of this Token.
37 uint64_t high() const { return high_; }
38 uint64_t low() const { return low_; }
40 bool is_zero() const { return high_ == 0 && low_ == 0; }
42 bool operator==(const Token& other) const {
43 return high_ == other.high_ && low_ == other.low_;
46 bool operator!=(const Token& other) const { return !(*this == other); }
48 bool operator<(const Token& other) const {
49 return std::tie(high_, low_) < std::tie(other.high_, other.low_);
52 // Generates a string representation of this Token useful for e.g. logging.
53 std::string ToString() const;
56 // Note: Two uint64_t are used instead of uint8_t[16] in order to have a
57 // simpler implementation, paricularly for |ToString()|, |is_zero()|, and
58 // constexpr value construction.
63 // For use in std::unordered_map.
65 size_t operator()(const base::Token& token) const {
66 return base::HashInts64(token.high(), token.low());
72 #endif // BASE_TOKEN_H_