token.h 2.4 KB

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