1 // Copyright (c) 2012 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_utils.h"
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "base/strings/string_util.h"
14 namespace bluetooth_utils
{
18 const char* kCommonUuidPostfix
= "-0000-1000-8000-00805f9b34fb";
19 const char* kCommonUuidPrefix
= "0000";
20 const int kUuidSize
= 36;
22 // Returns the canonical, 128-bit canonical, and the format of the UUID
23 // in |canonical|, |canonical_128|, and |format| based on |uuid|.
24 void GetCanonicalUuid(std::string uuid
,
25 std::string
* canonical
,
26 std::string
* canonical_128
,
27 UUID::Format
* format
) {
28 // Initialize the values for the failure case.
30 canonical_128
->clear();
31 *format
= UUID::kFormatInvalid
;
36 if (uuid
.size() < 11 && uuid
.find("0x") == 0)
37 uuid
= uuid
.substr(2);
39 if (!(uuid
.size() == 4 || uuid
.size() == 8 || uuid
.size() == 36))
42 if (uuid
.size() == 4 || uuid
.size() == 8) {
43 for (size_t i
= 0; i
< uuid
.size(); ++i
) {
44 if (!IsHexDigit(uuid
[i
]))
47 if (uuid
.size() == 4) {
48 canonical
->assign(uuid
);
49 canonical_128
->assign(kCommonUuidPrefix
+ uuid
+ kCommonUuidPostfix
);
50 *format
= UUID::kFormat16Bit
;
53 canonical
->assign(uuid
);
54 canonical_128
->assign(uuid
+ kCommonUuidPostfix
);
55 *format
= UUID::kFormat32Bit
;
59 for (int i
= 0; i
< kUuidSize
; ++i
) {
60 if (i
== 8 || i
== 13 || i
== 18 || i
== 23) {
64 if (!IsHexDigit(uuid
[i
]))
66 uuid
[i
] = tolower(uuid
[i
]);
70 canonical
->assign(uuid
);
71 canonical_128
->assign(uuid
);
72 *format
= UUID::kFormat128Bit
;
78 UUID::UUID(const std::string
& uuid
) {
79 GetCanonicalUuid(uuid
, &value_
, &canonical_value_
, &format_
);
85 bool UUID::IsValid() const {
86 return format_
!= kFormatInvalid
;
89 bool UUID::operator<(const UUID
& uuid
) const {
90 return canonical_value_
< uuid
.canonical_value_
;
93 bool UUID::operator==(const UUID
& uuid
) const {
94 return canonical_value_
== uuid
.canonical_value_
;
97 bool UUID::operator!=(const UUID
& uuid
) const {
98 return canonical_value_
!= uuid
.canonical_value_
;
101 std::string
CanonicalUuid(std::string uuid
) {
103 std::string canonical_value
;
105 GetCanonicalUuid(uuid
, &value
, &canonical_value
, &format
);
106 return canonical_value
;
109 } // namespace bluetooth_utils
110 } // namespace device