1 /******************************************************************************
2 *
3 * Copyright 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 #define LOG_TAG "bt_osi_future"
20
21 #include "osi/include/future.h"
22
23 #include <bluetooth/log.h>
24
25 #include "os/log.h"
26 #include "osi/include/allocator.h"
27 #include "osi/include/osi.h"
28 #include "osi/semaphore.h"
29
30 using namespace bluetooth;
31
32 struct future_t {
33 bool ready_can_be_called;
34 semaphore_t* semaphore; // NULL semaphore means immediate future
35 void* result;
36 };
37
38 static void future_free(future_t* future);
39
future_new(void)40 future_t* future_new(void) {
41 future_t* ret = static_cast<future_t*>(osi_calloc(sizeof(future_t)));
42
43 ret->semaphore = semaphore_new(0);
44 if (!ret->semaphore) {
45 log::error("unable to allocate memory for the semaphore.");
46 goto error;
47 }
48
49 ret->ready_can_be_called = true;
50 return ret;
51 error:;
52 future_free(ret);
53 return NULL;
54 }
55
future_new_immediate(void * value)56 future_t* future_new_immediate(void* value) {
57 future_t* ret = static_cast<future_t*>(osi_calloc(sizeof(future_t)));
58
59 ret->result = value;
60 ret->ready_can_be_called = false;
61 return ret;
62 }
63
future_ready(future_t * future,void * value)64 void future_ready(future_t* future, void* value) {
65 log::assert_that(future != NULL, "assert failed: future != NULL");
66 log::assert_that(future->ready_can_be_called,
67 "assert failed: future->ready_can_be_called");
68
69 future->ready_can_be_called = false;
70 future->result = value;
71 semaphore_post(future->semaphore);
72 }
73
future_await(future_t * future)74 void* future_await(future_t* future) {
75 log::assert_that(future != NULL, "assert failed: future != NULL");
76
77 // If the future is immediate, it will not have a semaphore
78 if (future->semaphore) semaphore_wait(future->semaphore);
79
80 void* result = future->result;
81 future_free(future);
82 return result;
83 }
84
future_free(future_t * future)85 static void future_free(future_t* future) {
86 if (!future) return;
87
88 semaphore_free(future->semaphore);
89 osi_free(future);
90 }
91