1 /*
2 * Copyright (C) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "raw_address.h"
17 #include <cstring>
18 #include <vector>
19 #include "securec.h"
20
21 namespace bluetooth {
ConvertToUint8(uint8_t * dst,const size_t size) const22 void RawAddress::ConvertToUint8(uint8_t *dst, const size_t size) const
23 {
24 if (dst != nullptr && address_.length() == BT_ADDRESS_STR_LEN && size >= BT_ADDRESS_BYTE_LEN) {
25 std::vector<std::string> token;
26 std::size_t startPostion = 0;
27 std::size_t colonPosition = address_.find(':', startPostion);
28 while (colonPosition != std::string::npos) {
29 token.push_back(address_.substr(startPostion, colonPosition - startPostion));
30 startPostion = colonPosition + BT_COLON_BYTE_SIZE;
31 colonPosition = address_.find(':', startPostion);
32 }
33 if (startPostion != BT_ADDRESS_STR_LEN) {
34 token.push_back(address_.substr(startPostion));
35 }
36 if (token.size() != BT_ADDRESS_BYTE_LEN) {
37 return;
38 }
39 for (int i = 0; i < BT_ADDRESS_BYTE_LEN; ++i) {
40 char *tmp = nullptr;
41 dst[i] = strtol(token[BT_ADDRESS_BYTE_LEN - 1 - i].c_str(), &tmp, BT_ADDRESS_STR_LEN - 1);
42 if (tmp[0] != '\0') {
43 return;
44 }
45 }
46 }
47 }
48
ConvertToString(const uint8_t * src,const size_t size)49 RawAddress RawAddress::ConvertToString(const uint8_t *src, const size_t size)
50 {
51 char token[BT_ADDRESS_STR_LEN + 1] = {0};
52 if (size >= BT_ADDRESS_BYTE_LEN) {
53 (void)sprintf_s(token,
54 BT_ADDRESS_STR_LEN + 1,
55 "%02X:%02X:%02X:%02X:%02X:%02X",
56 src[BT_LAP_HIGH_BYTE],
57 src[BT_LAP_MIDDLE_BYTE],
58 src[BT_LAP_LOW_BYTE],
59 src[BT_UAP_BYTE],
60 src[BT_NAP_HIGH_BYTE],
61 src[BT_NAP_LOW_BYTE]);
62 }
63 return RawAddress(token);
64 }
65
operator <(const RawAddress & rhs) const66 bool RawAddress::operator<(const RawAddress &rhs) const
67 {
68 return (address_.compare(rhs.address_) < 0);
69 }
70
operator ==(const RawAddress & rhs) const71 bool RawAddress::operator==(const RawAddress &rhs) const
72 {
73 return (address_.compare(rhs.address_) == 0);
74 }
75 } // namespace bluetooth