Commit | Line | Data |
---|---|---|
312c056a | 1 | /* |
0235b0db | 2 | * SPDX-License-Identifier: MIT |
312c056a | 3 | * |
0235b0db | 4 | * Copyright (c) 2018 Philippe Proulx <pproulx@efficios.com> |
312c056a PP |
5 | */ |
6 | ||
350ad6c1 | 7 | #define BT_LOG_TAG "LIB/OBJECT-POOL" |
c2d9d9cf | 8 | #include "lib/logging.h" |
312c056a PP |
9 | |
10 | #include <stdint.h> | |
578e048b | 11 | #include "common/assert.h" |
578e048b | 12 | #include "lib/object-pool.h" |
312c056a PP |
13 | |
14 | int bt_object_pool_initialize(struct bt_object_pool *pool, | |
15 | bt_object_pool_new_object_func new_object_func, | |
16 | bt_object_pool_destroy_object_func destroy_object_func, | |
17 | void *data) | |
18 | { | |
19 | int ret = 0; | |
20 | ||
701406be | 21 | BT_ASSERT(pool); |
312c056a PP |
22 | BT_ASSERT(new_object_func); |
23 | BT_ASSERT(destroy_object_func); | |
24 | BT_LOGD("Initializing object pool: addr=%p, data-addr=%p", | |
25 | pool, data); | |
26 | pool->objects = g_ptr_array_new(); | |
27 | if (!pool->objects) { | |
870631a2 | 28 | BT_LIB_LOGE_APPEND_CAUSE("Failed to allocate a GPtrArray."); |
312c056a PP |
29 | goto error; |
30 | } | |
31 | ||
32 | pool->funcs.new_object = new_object_func; | |
33 | pool->funcs.destroy_object = destroy_object_func; | |
34 | pool->data = data; | |
35 | pool->size = 0; | |
36 | BT_LIB_LOGD("Initialized object pool: %!+o", pool); | |
37 | goto end; | |
38 | ||
39 | error: | |
701406be | 40 | bt_object_pool_finalize(pool); |
312c056a PP |
41 | ret = -1; |
42 | ||
43 | end: | |
44 | return ret; | |
45 | } | |
46 | ||
47 | void bt_object_pool_finalize(struct bt_object_pool *pool) | |
48 | { | |
49 | uint64_t i; | |
50 | ||
51 | BT_ASSERT(pool); | |
52 | BT_LIB_LOGD("Finalizing object pool: %!+o", pool); | |
53 | ||
54 | if (pool->objects) { | |
55 | for (i = 0; i < pool->size; i++) { | |
56 | void *obj = pool->objects->pdata[i]; | |
57 | ||
58 | if (obj) { | |
59 | pool->funcs.destroy_object(obj, pool->data); | |
60 | } | |
61 | } | |
62 | ||
63 | g_ptr_array_free(pool->objects, TRUE); | |
64 | pool->objects = NULL; | |
65 | } | |
66 | } |