OLD | NEW |
(Empty) | |
| 1 // Copyright 2016 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 "content/common/bluetooth/bluetooth_device_id.h" |
| 6 |
| 7 #include "base/base64.h" |
| 8 #include "base/strings/string_util.h" |
| 9 #include "crypto/random.h" |
| 10 |
| 11 namespace content { |
| 12 |
| 13 namespace { |
| 14 |
| 15 enum { kDeviceIdLength = 16 /* 128 bits */ }; |
| 16 |
| 17 } // namespace |
| 18 |
| 19 BluetoothDeviceId::BluetoothDeviceId() {} |
| 20 |
| 21 BluetoothDeviceId::BluetoothDeviceId(std::string device_id) |
| 22 : device_id_(std::move(device_id)) { |
| 23 DCHECK(IsValid(device_id_)); |
| 24 } |
| 25 |
| 26 BluetoothDeviceId::~BluetoothDeviceId() {} |
| 27 |
| 28 const std::string& BluetoothDeviceId::str() const { |
| 29 DCHECK(IsValid(device_id_)); |
| 30 return device_id_; |
| 31 } |
| 32 |
| 33 // static |
| 34 BluetoothDeviceId BluetoothDeviceId::Create() { |
| 35 std::string bytes( |
| 36 kDeviceIdLength + 1 /* to avoid bytes being reallocated by WriteInto */, |
| 37 '\0'); |
| 38 |
| 39 crypto::RandBytes(base::WriteInto(&bytes /* str */, |
| 40 kDeviceIdLength + 1 /* length_with_null */), |
| 41 kDeviceIdLength); |
| 42 |
| 43 base::Base64Encode(bytes, &bytes); |
| 44 |
| 45 return BluetoothDeviceId(bytes); |
| 46 } |
| 47 |
| 48 // static |
| 49 bool BluetoothDeviceId::IsValid(const std::string& device_id) { |
| 50 std::string decoded; |
| 51 if (!base::Base64Decode(device_id, &decoded)) { |
| 52 return false; |
| 53 } |
| 54 |
| 55 if (decoded.size() != kDeviceIdLength) { |
| 56 return false; |
| 57 } |
| 58 |
| 59 return true; |
| 60 } |
| 61 |
| 62 bool BluetoothDeviceId::operator==(const BluetoothDeviceId& device_id) const { |
| 63 return str() == device_id.str(); |
| 64 } |
| 65 |
| 66 bool BluetoothDeviceId::operator!=(const BluetoothDeviceId& device_id) const { |
| 67 return !(*this == device_id); |
| 68 } |
| 69 |
| 70 std::ostream& operator<<(std::ostream& out, |
| 71 const BluetoothDeviceId& device_id) { |
| 72 return out << device_id.str(); |
| 73 } |
| 74 |
| 75 } // namespace content |
OLD | NEW |