| 1 | /* |
| 2 | * SPDX-License-Identifier: MIT |
| 3 | * |
| 4 | * Copyright (c) 2018 Philippe Proulx <pproulx@efficios.com> |
| 5 | */ |
| 6 | |
| 7 | #define BT_LOG_TAG "LIB/OBJECT-POOL" |
| 8 | #include "lib/logging.h" |
| 9 | |
| 10 | #include <stdint.h> |
| 11 | #include "common/assert.h" |
| 12 | #include "lib/object-pool.h" |
| 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 | |
| 21 | BT_ASSERT(pool); |
| 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) { |
| 28 | BT_LIB_LOGE_APPEND_CAUSE("Failed to allocate a GPtrArray."); |
| 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: |
| 40 | bt_object_pool_finalize(pool); |
| 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 | } |