1 // 2 // Copyright 2016 The Android Open Source Project 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 // 16 17 #include "bt_address.h" 18 #include <iomanip> 19 #include <vector> 20 using std::vector; 21 22 #include <base/logging.h> 23 24 namespace test_vendor_lib { 25 IsValid(const std::string & addr)26bool BtAddress::IsValid(const std::string& addr) { 27 if (addr.length() < kStringLength) return false; 28 29 for (size_t i = 0; i < kStringLength; i++) { 30 if (i % 3 == 2) { // Every third character must be ':' 31 if (addr[i] != ':') return false; 32 } else { // The rest must be hexadecimal digits 33 if (!isxdigit(addr[i])) return false; 34 } 35 } 36 return true; 37 } 38 FromString(const std::string & str)39bool BtAddress::FromString(const std::string& str) { 40 std::string tok; 41 std::istringstream iss(str); 42 43 if (IsValid(str) == false) return false; 44 45 address_ = 0; 46 for (size_t i = 0; i < kOctets; i++) { 47 getline(iss, tok, ':'); 48 uint64_t octet = std::stoi(tok, nullptr, 16); 49 address_ |= (octet << (8 * ((kOctets - 1) - i))); 50 } 51 return true; 52 } 53 FromVector(const vector<uint8_t> & octets)54bool BtAddress::FromVector(const vector<uint8_t>& octets) { 55 if (octets.size() < kOctets) return false; 56 57 address_ = 0; 58 for (size_t i = 0; i < kOctets; i++) { 59 uint64_t to_shift = octets[i]; 60 address_ |= to_shift << (8 * i); 61 } 62 return true; 63 } 64 ToVector(vector<uint8_t> & octets) const65void BtAddress::ToVector(vector<uint8_t>& octets) const { 66 for (size_t i = 0; i < kOctets; i++) { 67 octets.push_back(address_ >> (8 * i)); 68 } 69 } 70 ToString() const71std::string BtAddress::ToString() const { 72 std::stringstream ss; 73 74 ss << std::hex << std::setfill('0') << std::setw(2); 75 for (size_t i = 0; i < kOctets; i++) { 76 uint64_t octet = (address_ >> (8 * ((kOctets - 1) - i))) & 0xff; 77 ss << std::hex << std::setfill('0') << std::setw(2) << octet; 78 if (i != kOctets - 1) ss << std::string(":"); 79 } 80 81 return ss.str(); 82 } 83 84 } // namespace test_vendor_lib 85