[M108 Migration][VD] Support set time and time zone offset
[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/pickle.h"
10 #include "base/rand_util.h"
11 #include "base/strings/stringprintf.h"
12 #include "third_party/abseil-cpp/absl/types/optional.h"
13
14 namespace base {
15
16 // static
17 Token Token::CreateRandom() {
18   Token token;
19
20   // Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
21   // base version directly, and to prevent the dependency from base/ to crypto/.
22   base::RandBytes(&token, sizeof(token));
23   return token;
24 }
25
26 std::string Token::ToString() const {
27   return base::StringPrintf("%016" PRIX64 "%016" PRIX64, words_[0], words_[1]);
28 }
29
30 // static
31 absl::optional<Token> Token::FromString(StringPiece string_representation) {
32   if (string_representation.size() != 32) {
33     return absl::nullopt;
34   }
35   uint64_t words[2];
36   for (size_t i = 0; i < 2; i++) {
37     uint64_t word = 0;
38     // This j loop is similar to HexStringToUInt64 but we are intentionally
39     // strict about case, accepting 'A' but rejecting 'a'.
40     for (size_t j = 0; j < 16; j++) {
41       const char c = string_representation[(16 * i) + j];
42       if (('0' <= c) && (c <= '9')) {
43         word = (word << 4) | static_cast<uint64_t>(c - '0');
44       } else if (('A' <= c) && (c <= 'F')) {
45         word = (word << 4) | static_cast<uint64_t>(c - 'A' + 10);
46       } else {
47         return absl::nullopt;
48       }
49     }
50     words[i] = word;
51   }
52   return absl::optional<Token>(absl::in_place, words[0], words[1]);
53 }
54
55 void WriteTokenToPickle(Pickle* pickle, const Token& token) {
56   pickle->WriteUInt64(token.high());
57   pickle->WriteUInt64(token.low());
58 }
59
60 absl::optional<Token> ReadTokenFromPickle(PickleIterator* pickle_iterator) {
61   uint64_t high;
62   if (!pickle_iterator->ReadUInt64(&high))
63     return absl::nullopt;
64
65   uint64_t low;
66   if (!pickle_iterator->ReadUInt64(&low))
67     return absl::nullopt;
68
69   return Token(high, low);
70 }
71
72 }  // namespace base