1 /****************************************************************************** 2 * 3 * Copyright 2017 The Android Open Source Project 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at: 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 ******************************************************************************/ 18 19 #pragma once 20 21 #include <cstring> 22 #include <string> 23 24 /** Bluetooth Address */ 25 class RawAddress final { 26 public: 27 static constexpr unsigned int kLength = 6; 28 29 uint8_t address[kLength]; 30 31 RawAddress() = default; 32 RawAddress(const uint8_t (&addr)[6]); 33 34 bool operator<(const RawAddress& rhs) const { 35 return (std::memcmp(address, rhs.address, sizeof(address)) < 0); 36 } 37 bool operator==(const RawAddress& rhs) const { 38 return (std::memcmp(address, rhs.address, sizeof(address)) == 0); 39 } 40 bool operator>(const RawAddress& rhs) const { return (rhs < *this); } 41 bool operator<=(const RawAddress& rhs) const { return !(*this > rhs); } 42 bool operator>=(const RawAddress& rhs) const { return !(*this < rhs); } 43 bool operator!=(const RawAddress& rhs) const { return !(*this == rhs); } 44 45 bool IsEmpty() const { return *this == kEmpty; } 46 47 std::string ToString() const; 48 49 // Converts |string| to RawAddress and places it in |to|. If |from| does 50 // not represent a Bluetooth address, |to| is not modified and this function 51 // returns false. Otherwise, it returns true. 52 static bool FromString(const std::string& from, RawAddress& to); 53 54 // Copies |from| raw Bluetooth address octets to the local object. 55 // Returns the number of copied octets - should be always RawAddress::kLength 56 size_t FromOctets(const uint8_t* from); 57 58 static bool IsValidAddress(const std::string& address); 59 60 static const RawAddress kEmpty; // 00:00:00:00:00:00 61 static const RawAddress kAny; // FF:FF:FF:FF:FF:FF 62 }; 63 64 inline std::ostream& operator<<(std::ostream& os, const RawAddress& a) { 65 os << a.ToString(); 66 return os; 67 } 68 69 template <> 70 struct std::hash<RawAddress> { 71 std::size_t operator()(const RawAddress& val) const { 72 static_assert(sizeof(uint64_t) >= RawAddress::kLength); 73 uint64_t int_addr = 0; 74 memcpy(reinterpret_cast<uint8_t*>(&int_addr), val.address, 75 RawAddress::kLength); 76 return std::hash<uint64_t>{}(int_addr); 77 } 78 }; 79