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. 4 5 #ifndef BASE_TOKEN_H_ 6 #define BASE_TOKEN_H_ 7 8 #include <stdint.h> 9 10 #include <iosfwd> 11 #include <tuple> 12 13 #include "base/base_export.h" 14 #include "base/hash.h" 15 16 namespace base { 17 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 { 25 public: 26 // Constructs a zero Token. Token()27 constexpr Token() : high_(0), low_(0) {} 28 29 // Constructs a Token with |high| and |low| as its contents. Token(uint64_t high,uint64_t low)30 constexpr Token(uint64_t high, uint64_t low) : high_(high), low_(low) {} 31 32 // Constructs a new Token with random |high| and |low| values taken from a 33 // cryptographically strong random source. 34 static Token CreateRandom(); 35 36 // The high and low 64 bits of this Token. high()37 uint64_t high() const { return high_; } low()38 uint64_t low() const { return low_; } 39 is_zero()40 bool is_zero() const { return high_ == 0 && low_ == 0; } 41 42 bool operator==(const Token& other) const { 43 return high_ == other.high_ && low_ == other.low_; 44 } 45 46 bool operator!=(const Token& other) const { return !(*this == other); } 47 48 bool operator<(const Token& other) const { 49 return std::tie(high_, low_) < std::tie(other.high_, other.low_); 50 } 51 52 // Generates a string representation of this Token useful for e.g. logging. 53 std::string ToString() const; 54 55 private: 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. 59 uint64_t high_; 60 uint64_t low_; 61 }; 62 63 // For use in std::unordered_map. 64 struct TokenHash { operatorTokenHash65 size_t operator()(const base::Token& token) const { 66 return base::HashInts64(token.high(), token.low()); 67 } 68 }; 69 70 } // namespace base 71 72 #endif // BASE_TOKEN_H_