blob: c9af068eda15e5f3f9417ee9f6733451f5fa1116 [file] [log] [blame]
Ken Rockot8c6991c72018-11-07 21:23:191// 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"
Daniel Chengc0581992019-03-29 04:52:5614#include "base/hash/hash.h"
Collin Bakerffe1d0eb2019-08-05 23:00:4515#include "base/optional.h"
Ken Rockot8c6991c72018-11-07 21:23:1916
17namespace 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.
25class 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.
65struct TokenHash {
66 size_t operator()(const base::Token& token) const {
67 return base::HashInts64(token.high(), token.low());
68 }
69};
70
Collin Bakerffe1d0eb2019-08-05 23:00:4571class Pickle;
72class PickleIterator;
73
74// For serializing and deserializing Token values.
75BASE_EXPORT void WriteTokenToPickle(Pickle* pickle, const Token& token);
76BASE_EXPORT Optional<Token> ReadTokenFromPickle(
77 PickleIterator* pickle_iterator);
78
Ken Rockot8c6991c72018-11-07 21:23:1979} // namespace base
80
81#endif // BASE_TOKEN_H_