1 // Copyright 2023 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 "components/metrics/structured/lib/key_util.h" 6 7 #include <utility> 8 9 #include "base/check_op.h" 10 #include "base/unguessable_token.h" 11 12 namespace metrics::structured::util { 13 namespace { 14 15 constexpr std::string_view kKeyString = "key"; 16 constexpr std::string_view kLastRotationString = "last_rotation"; 17 constexpr std::string_view kRotationPeriodString = "rotation_period"; 18 19 } // namespace 20 GenerateNewKey()21std::string GenerateNewKey() { 22 const std::string key = base::UnguessableToken::Create().ToString(); 23 CHECK_EQ(key.size(), kKeySize); 24 return key; 25 } 26 CreateValueFromKeyProto(const KeyProto & proto)27base::Value CreateValueFromKeyProto(const KeyProto& proto) { 28 base::Value::Dict key = 29 base::Value::Dict() 30 .Set(kKeyString, proto.key()) 31 // last_rotation and rotation_period are represented as int64's but 32 // should never exceed int. 33 .Set(kLastRotationString, static_cast<int>(proto.last_rotation())) 34 .Set(kRotationPeriodString, 35 static_cast<int>(proto.rotation_period())); 36 37 return base::Value(std::move(key)); 38 } 39 CreateKeyProtoFromValue(const base::Value::Dict & value)40std::optional<KeyProto> CreateKeyProtoFromValue( 41 const base::Value::Dict& value) { 42 const std::string* key = value.FindString(kKeyString); 43 if (!key) { 44 return std::nullopt; 45 } 46 47 std::optional<int> last_rotation = value.FindInt(kLastRotationString); 48 if (!last_rotation.has_value()) { 49 return std::nullopt; 50 } 51 52 std::optional<int> rotation_period = value.FindInt(kRotationPeriodString); 53 if (!rotation_period.has_value()) { 54 return std::nullopt; 55 } 56 57 KeyProto proto; 58 proto.set_key(*key); 59 proto.set_last_rotation(*last_rotation); 60 proto.set_rotation_period(*rotation_period); 61 62 return proto; 63 } 64 65 } // namespace metrics::structured::util 66