1 // Copyright 2014 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.
5 #include "device/bluetooth/bluetooth_uuid.h"
7 #include "base/basictypes.h"
8 #include "base/logging.h"
9 #include "base/strings/string_util.h"
15 const char* kCommonUuidPostfix
= "-0000-1000-8000-00805f9b34fb";
16 const char* kCommonUuidPrefix
= "0000";
17 const int kUuidSize
= 36;
19 // Returns the canonical, 128-bit canonical, and the format of the UUID
20 // in |canonical|, |canonical_128|, and |format| based on |uuid|.
21 void GetCanonicalUuid(std::string uuid
,
22 std::string
* canonical
,
23 std::string
* canonical_128
,
24 BluetoothUUID::Format
* format
) {
25 // Initialize the values for the failure case.
27 canonical_128
->clear();
28 *format
= BluetoothUUID::kFormatInvalid
;
33 if (uuid
.size() < 11 && uuid
.find("0x") == 0)
34 uuid
= uuid
.substr(2);
36 if (!(uuid
.size() == 4 || uuid
.size() == 8 || uuid
.size() == 36))
39 if (uuid
.size() == 4 || uuid
.size() == 8) {
40 for (size_t i
= 0; i
< uuid
.size(); ++i
) {
41 if (!IsHexDigit(uuid
[i
]))
44 if (uuid
.size() == 4) {
45 canonical
->assign(uuid
);
46 canonical_128
->assign(kCommonUuidPrefix
+ uuid
+ kCommonUuidPostfix
);
47 *format
= BluetoothUUID::kFormat16Bit
;
50 canonical
->assign(uuid
);
51 canonical_128
->assign(uuid
+ kCommonUuidPostfix
);
52 *format
= BluetoothUUID::kFormat32Bit
;
56 for (int i
= 0; i
< kUuidSize
; ++i
) {
57 if (i
== 8 || i
== 13 || i
== 18 || i
== 23) {
61 if (!IsHexDigit(uuid
[i
]))
63 uuid
[i
] = tolower(uuid
[i
]);
67 canonical
->assign(uuid
);
68 canonical_128
->assign(uuid
);
69 *format
= BluetoothUUID::kFormat128Bit
;
75 BluetoothUUID::BluetoothUUID(const std::string
& uuid
) {
76 GetCanonicalUuid(uuid
, &value_
, &canonical_value_
, &format_
);
79 BluetoothUUID::BluetoothUUID() : format_(kFormatInvalid
) {
82 BluetoothUUID::~BluetoothUUID() {
85 bool BluetoothUUID::IsValid() const {
86 return format_
!= kFormatInvalid
;
89 bool BluetoothUUID::operator<(const BluetoothUUID
& uuid
) const {
90 return canonical_value_
< uuid
.canonical_value_
;
93 bool BluetoothUUID::operator==(const BluetoothUUID
& uuid
) const {
94 return canonical_value_
== uuid
.canonical_value_
;
97 bool BluetoothUUID::operator!=(const BluetoothUUID
& uuid
) const {
98 return canonical_value_
!= uuid
.canonical_value_
;
101 void PrintTo(const BluetoothUUID
& uuid
, std::ostream
* out
) {
102 *out
<< uuid
.canonical_value();
105 } // namespace device