| 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/hash.h" |
| 15 | #include "base/optional.h" |
| 16 |
| 17 | namespace base { |
| 18 |
| 19 | // A Token is a randomly chosen 128-bit integer. This class supports generation |
| 20 | // from a cryptographically strong random source, or constexpr construction over |
| 21 | // fixed values (e.g. to store a pre-generated constant value). Tokens are |
| 22 | // similar in spirit and purpose to UUIDs, without many of the constraints and |
| 23 | // expectations (such as byte layout and string representation) clasically |
| 24 | // associated with UUIDs. |
| 25 | class BASE_EXPORT Token { |
| 26 | public: |
| 27 | // Constructs a zero Token. |
| 28 | constexpr Token() : high_(0), low_(0) {} |
| 29 |
| 30 | // Constructs a Token with |high| and |low| as its contents. |
| 31 | constexpr Token(uint64_t high, uint64_t low) : high_(high), low_(low) {} |
| 32 |
| 33 | // Constructs a new Token with random |high| and |low| values taken from a |
| 34 | // cryptographically strong random source. |
| 35 | static Token CreateRandom(); |
| 36 |
| 37 | // The high and low 64 bits of this Token. |
| 38 | uint64_t high() const { return high_; } |
| 39 | uint64_t low() const { return low_; } |
| 40 |
| 41 | bool is_zero() const { return high_ == 0 && low_ == 0; } |
| 42 |
| 43 | bool operator==(const Token& other) const { |
| 44 | return high_ == other.high_ && low_ == other.low_; |
| 45 | } |
| 46 |
| 47 | bool operator!=(const Token& other) const { return !(*this == other); } |
| 48 |
| 49 | bool operator<(const Token& other) const { |
| 50 | return std::tie(high_, low_) < std::tie(other.high_, other.low_); |
| 51 | } |
| 52 |
| 53 | // Generates a string representation of this Token useful for e.g. logging. |
| 54 | std::string ToString() const; |
| 55 |
| 56 | private: |
| 57 | // Note: Two uint64_t are used instead of uint8_t[16] in order to have a |
| 58 | // simpler implementation, paricularly for |ToString()|, |is_zero()|, and |
| 59 | // constexpr value construction. |
| 60 | uint64_t high_; |
| 61 | uint64_t low_; |
| 62 | }; |
| 63 |
| 64 | // For use in std::unordered_map. |
| 65 | struct TokenHash { |
| 66 | size_t operator()(const base::Token& token) const { |
| 67 | return base::HashInts64(token.high(), token.low()); |
| 68 | } |
| 69 | }; |
| 70 |
| 71 | class Pickle; |
| 72 | class PickleIterator; |
| 73 |
| 74 | // For serializing and deserializing Token values. |
| 75 | BASE_EXPORT void WriteTokenToPickle(Pickle* pickle, const Token& token); |
| 76 | BASE_EXPORT Optional<Token> ReadTokenFromPickle( |
| 77 | PickleIterator* pickle_iterator); |
| 78 |
| 79 | } // namespace base |
| 80 |
| 81 | #endif // BASE_TOKEN_H_ |
| 82 |