blob: 6b9f3f9b72a3d7700e3ecbe74ccc3895a15e8614 [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#include "base/token.h"
6
7#include <inttypes.h>
8
Collin Bakerffe1d0eb2019-08-05 23:00:459#include "base/pickle.h"
Ken Rockot8c6991c72018-11-07 21:23:1910#include "base/rand_util.h"
11#include "base/strings/stringprintf.h"
Anton Bikineev7dd58ad2021-05-18 01:01:3912#include "third_party/abseil-cpp/absl/types/optional.h"
Ken Rockot8c6991c72018-11-07 21:23:1913
14namespace base {
15
16// static
17Token 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
26std::string Token::ToString() const {
Liza Burakovae7e943012021-07-16 14:09:0527 return base::StringPrintf("%016" PRIX64 "%016" PRIX64, words_[0], words_[1]);
Ken Rockot8c6991c72018-11-07 21:23:1928}
29
Collin Bakerffe1d0eb2019-08-05 23:00:4530void WriteTokenToPickle(Pickle* pickle, const Token& token) {
31 pickle->WriteUInt64(token.high());
32 pickle->WriteUInt64(token.low());
33}
34
Anton Bikineev7dd58ad2021-05-18 01:01:3935absl::optional<Token> ReadTokenFromPickle(PickleIterator* pickle_iterator) {
Collin Bakerffe1d0eb2019-08-05 23:00:4536 uint64_t high;
37 if (!pickle_iterator->ReadUInt64(&high))
Anton Bikineev7dd58ad2021-05-18 01:01:3938 return absl::nullopt;
Collin Bakerffe1d0eb2019-08-05 23:00:4539
40 uint64_t low;
41 if (!pickle_iterator->ReadUInt64(&low))
Anton Bikineev7dd58ad2021-05-18 01:01:3942 return absl::nullopt;
Collin Bakerffe1d0eb2019-08-05 23:00:4543
44 return Token(high, low);
45}
46
Ken Rockot8c6991c72018-11-07 21:23:1947} // namespace base