| 1 | /* |
| 2 | * SPDX-License-Identifier: MIT |
| 3 | * |
| 4 | * Copyright (c) 2018 EfficiOS Inc. and Linux Foundation |
| 5 | * Copyright (c) 2018 Philippe Proulx <pproulx@efficios.com> |
| 6 | */ |
| 7 | |
| 8 | #define BT_LOG_TAG "CTF-WRITER/OBJECT-POOL" |
| 9 | #include "logging.h" |
| 10 | |
| 11 | #include <stdint.h> |
| 12 | |
| 13 | #include "common/assert.h" |
| 14 | |
| 15 | #include "object-pool.h" |
| 16 | |
| 17 | BT_EXPORT |
| 18 | int bt_ctf_object_pool_initialize(struct bt_ctf_object_pool *pool, |
| 19 | bt_ctf_object_pool_new_object_func new_object_func, |
| 20 | bt_ctf_object_pool_destroy_object_func destroy_object_func, |
| 21 | void *data) |
| 22 | { |
| 23 | int ret = 0; |
| 24 | |
| 25 | BT_ASSERT_DBG(new_object_func); |
| 26 | BT_ASSERT_DBG(destroy_object_func); |
| 27 | BT_LOGD("Initializing object pool: addr=%p, data-addr=%p", |
| 28 | pool, data); |
| 29 | pool->objects = g_ptr_array_new(); |
| 30 | if (!pool->objects) { |
| 31 | BT_LOGE_STR("Failed to allocate a GPtrArray."); |
| 32 | goto error; |
| 33 | } |
| 34 | |
| 35 | pool->funcs.new_object = new_object_func; |
| 36 | pool->funcs.destroy_object = destroy_object_func; |
| 37 | pool->data = data; |
| 38 | pool->size = 0; |
| 39 | BT_LOGD("Initialized object pool."); |
| 40 | goto end; |
| 41 | |
| 42 | error: |
| 43 | if (pool) { |
| 44 | bt_ctf_object_pool_finalize(pool); |
| 45 | } |
| 46 | |
| 47 | ret = -1; |
| 48 | |
| 49 | end: |
| 50 | return ret; |
| 51 | } |
| 52 | |
| 53 | BT_EXPORT |
| 54 | void bt_ctf_object_pool_finalize(struct bt_ctf_object_pool *pool) |
| 55 | { |
| 56 | uint64_t i; |
| 57 | |
| 58 | BT_ASSERT_DBG(pool); |
| 59 | BT_LOGD("Finalizing object pool."); |
| 60 | |
| 61 | if (pool->objects) { |
| 62 | for (i = 0; i < pool->size; i++) { |
| 63 | void *obj = pool->objects->pdata[i]; |
| 64 | |
| 65 | if (obj) { |
| 66 | pool->funcs.destroy_object(obj, pool->data); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | g_ptr_array_free(pool->objects, TRUE); |
| 71 | pool->objects = NULL; |
| 72 | } |
| 73 | } |