1 /******************************************************************************
3 * Copyright (C) 2014 Google, Inc.
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:
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 ******************************************************************************/
19 #define LOG_TAG "bt_osi_data_dispatcher"
22 #include <utils/Log.h>
24 #include "data_dispatcher.h"
28 #define DEFAULT_TABLE_BUCKETS 10
30 struct data_dispatcher_t {
32 hash_map_t *dispatch_table;
33 fixed_queue_t *default_queue; // We don't own this queue
36 static hash_index_t default_hash_function(const void *key);
38 data_dispatcher_t *data_dispatcher_new(const char *name) {
41 data_dispatcher_t *ret = calloc(1, sizeof(data_dispatcher_t));
43 ALOGE("%s unable to allocate memory for new data dispatcher.", __func__);
47 ret->dispatch_table = hash_map_new(DEFAULT_TABLE_BUCKETS, default_hash_function, NULL, NULL);
48 if (!ret->dispatch_table) {
49 ALOGE("%s unable to create dispatch table.", __func__);
53 ret->name = strdup(name);
55 ALOGE("%s unable to duplicate provided name.", __func__);
62 data_dispatcher_free(ret);
66 void data_dispatcher_free(data_dispatcher_t *dispatcher) {
70 hash_map_free(dispatcher->dispatch_table);
73 free(dispatcher->name);
78 void data_dispatcher_register(data_dispatcher_t *dispatcher, data_dispatcher_type_t type, fixed_queue_t *queue) {
79 assert(dispatcher != NULL);
81 hash_map_erase(dispatcher->dispatch_table, (void *)type);
83 hash_map_set(dispatcher->dispatch_table, (void *)type, queue);
86 void data_dispatcher_register_default(data_dispatcher_t *dispatcher, fixed_queue_t *queue) {
87 assert(dispatcher != NULL);
89 dispatcher->default_queue = queue;
92 bool data_dispatcher_dispatch(data_dispatcher_t *dispatcher, data_dispatcher_type_t type, void *data) {
93 assert(dispatcher != NULL);
96 fixed_queue_t *queue = hash_map_get(dispatcher->dispatch_table, (void *)type);
98 queue = dispatcher->default_queue;
101 fixed_queue_enqueue(queue, data);
103 ALOGW("%s has no handler for type (%d) in data dispatcher named: %s", __func__, type, dispatcher->name);
105 return queue != NULL;
108 static hash_index_t default_hash_function(const void *key) {
109 hash_index_t hash_key = (hash_index_t)key;