OSDN Git Service

Add a hash function for bluetooth addresses
[android-x86/system-bt.git] / btcore / src / bdaddr.c
1 /******************************************************************************
2  *
3  *  Copyright (C) 2014 Google, Inc.
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 #include <assert.h>
20 #include <ctype.h>
21 #include <stdio.h>
22 #include <string.h>
23
24 #include "bdaddr.h"
25
26 bool bdaddr_is_empty(const bt_bdaddr_t *addr) {
27   assert(addr != NULL);
28
29   uint8_t zero[sizeof(bt_bdaddr_t)] = { 0 };
30   return memcmp(addr, &zero, sizeof(bt_bdaddr_t)) == 0;
31 }
32
33 bool bdaddr_equals(const bt_bdaddr_t *first, const bt_bdaddr_t *second) {
34   assert(first != NULL);
35   assert(second != NULL);
36
37   return memcmp(first, second, sizeof(bt_bdaddr_t)) == 0;
38 }
39
40 const char *bdaddr_to_string(const bt_bdaddr_t *addr, char *string, size_t size) {
41   assert(addr != NULL);
42   assert(string != NULL);
43
44   if (size < 18)
45     return NULL;
46
47   const uint8_t *ptr = addr->address;
48   sprintf(string, "%02x:%02x:%02x:%02x:%02x:%02x",
49            ptr[0], ptr[1], ptr[2],
50            ptr[3], ptr[4], ptr[5]);
51   return string;
52 }
53
54 bool string_is_bdaddr(const char *string) {
55   assert(string != NULL);
56
57   size_t len = strlen(string);
58   if (len != 17)
59     return false;
60
61   for (size_t i = 0; i < len; ++i) {
62     // Every 3rd char must be ':'.
63     if (((i + 1) % 3) == 0 && string[i] != ':')
64       return false;
65
66     // All other chars must be a hex digit.
67     if (((i + 1) % 3) != 0 && !isxdigit(string[i]))
68       return false;
69   }
70   return true;
71 }
72
73 bool string_to_bdaddr(const char *string, bt_bdaddr_t *addr) {
74   assert(string != NULL);
75   assert(addr != NULL);
76
77   bt_bdaddr_t new_addr;
78   uint8_t *ptr = new_addr.address;
79   bool ret = sscanf(string, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
80       &ptr[0], &ptr[1], &ptr[2], &ptr[3], &ptr[4], &ptr[5]) == 6;
81
82   if (ret)
83     memcpy(addr, &new_addr, sizeof(bt_bdaddr_t));
84
85   return ret;
86 }
87
88 hash_index_t hash_function_bdaddr(const void *key) {
89   hash_index_t hash = 5381;
90   const char *bytes = (const char *)key;
91   for (size_t i = 0; i < sizeof(bt_bdaddr_t); ++i)
92     hash = ((hash << 5) + hash) + bytes[i];
93   return hash;
94 }