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"
23 #include "osi/include/allocator.h"
24 #include "osi/include/data_dispatcher.h"
25 #include "osi/include/hash_functions.h"
26 #include "osi/include/hash_map.h"
27 #include "osi/include/osi.h"
28 #include "osi/include/log.h"
30 #define DEFAULT_TABLE_BUCKETS 10
32 struct data_dispatcher_t {
34 hash_map_t *dispatch_table;
35 fixed_queue_t *default_queue; // We don't own this queue
38 data_dispatcher_t *data_dispatcher_new(const char *name) {
41 data_dispatcher_t *ret = osi_calloc(sizeof(data_dispatcher_t));
43 LOG_ERROR("%s unable to allocate memory for new data dispatcher.", __func__);
47 ret->dispatch_table = hash_map_new(DEFAULT_TABLE_BUCKETS, hash_function_naive, NULL, NULL, NULL);
48 if (!ret->dispatch_table) {
49 LOG_ERROR("%s unable to create dispatch table.", __func__);
53 ret->name = osi_strdup(name);
55 LOG_ERROR("%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 osi_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 LOG_WARN("%s has no handler for type (%zd) in data dispatcher named: %s", __func__, type, dispatcher->name);
105 return queue != NULL;