fixup! [M120 Migration] Notify media device state to webbrowser
[platform/framework/web/chromium-efl.git] / base / token.cc
1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/token.h"
6
7 #include <inttypes.h>
8
9 #include "base/check.h"
10 #include "base/hash/hash.h"
11 #include "base/pickle.h"
12 #include "base/rand_util.h"
13 #include "base/strings/string_piece.h"
14 #include "base/strings/stringprintf.h"
15 #include "third_party/abseil-cpp/absl/types/optional.h"
16
17 namespace base {
18
19 // static
20 Token Token::CreateRandom() {
21   Token token;
22
23   // Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
24   // base version directly, and to prevent the dependency from base/ to crypto/.
25   base::RandBytes(&token, sizeof(token));
26
27   CHECK(!token.is_zero());
28
29   return token;
30 }
31
32 std::string Token::ToString() const {
33   return base::StringPrintf("%016" PRIX64 "%016" PRIX64, words_[0], words_[1]);
34 }
35
36 // static
37 absl::optional<Token> Token::FromString(StringPiece string_representation) {
38   if (string_representation.size() != 32) {
39     return absl::nullopt;
40   }
41   uint64_t words[2];
42   for (size_t i = 0; i < 2; i++) {
43     uint64_t word = 0;
44     // This j loop is similar to HexStringToUInt64 but we are intentionally
45     // strict about case, accepting 'A' but rejecting 'a'.
46     for (size_t j = 0; j < 16; j++) {
47       const char c = string_representation[(16 * i) + j];
48       if (('0' <= c) && (c <= '9')) {
49         word = (word << 4) | static_cast<uint64_t>(c - '0');
50       } else if (('A' <= c) && (c <= 'F')) {
51         word = (word << 4) | static_cast<uint64_t>(c - 'A' + 10);
52       } else {
53         return absl::nullopt;
54       }
55     }
56     words[i] = word;
57   }
58   return absl::optional<Token>(absl::in_place, words[0], words[1]);
59 }
60
61 void WriteTokenToPickle(Pickle* pickle, const Token& token) {
62   pickle->WriteUInt64(token.high());
63   pickle->WriteUInt64(token.low());
64 }
65
66 absl::optional<Token> ReadTokenFromPickle(PickleIterator* pickle_iterator) {
67   uint64_t high;
68   if (!pickle_iterator->ReadUInt64(&high))
69     return absl::nullopt;
70
71   uint64_t low;
72   if (!pickle_iterator->ReadUInt64(&low))
73     return absl::nullopt;
74
75   return Token(high, low);
76 }
77
78 size_t TokenHash::operator()(const Token& token) const {
79   return HashInts64(token.high(), token.low());
80 }
81
82 }  // namespace base