Branch data Line data Source code
1 : : /* SPDX-License-Identifier: BSD-3-Clause 2 : : * Copyright(c) 2025 Huawei Technologies Co., Ltd 3 : : */ 4 : : 5 : : #include "internal.h" 6 : : #include <stdlib.h> 7 : : 8 : : 9 : : /* Needs to be a power of two. */ 10 : : #define START_CAPACITY (1u << 3) 11 : : 12 : : size_t 13 : 0 : alloc_list_append(struct alloc_list *alloc_list, void *ptr) 14 : : { 15 : 0 : if (alloc_list->count == 0) { 16 : : RTE_ASSERT(alloc_list->ptrs == NULL); 17 : 0 : alloc_list->ptrs = malloc( 18 : : sizeof(alloc_list->ptrs[0]) * START_CAPACITY); 19 : 0 : RTE_VERIFY(alloc_list->ptrs != NULL); 20 : 0 : } else if (alloc_list->count >= START_CAPACITY && 21 : : /* Power of two detection */ 22 : 0 : (alloc_list->count & (alloc_list->count - 1)) == 0) { 23 : : /* 24 : : * We allocate in powers of two, and current count is one of 25 : : * these powers, so need to reallocate to larger capacity. 26 : : */ 27 : : RTE_ASSERT(alloc_list->ptrs != NULL); 28 : : const size_t new_capacity = alloc_list->count * 2; 29 : 0 : alloc_list->ptrs = realloc(alloc_list->ptrs, 30 : : sizeof(alloc_list->ptrs[0]) * new_capacity); 31 : 0 : RTE_VERIFY(alloc_list->ptrs != NULL); 32 : : } 33 : 0 : alloc_list->ptrs[alloc_list->count] = ptr; 34 : 0 : return alloc_list->count++; 35 : : } 36 : : 37 : 0 : void alloc_list_replace(struct alloc_list *alloc_list, size_t index, void *ptr) 38 : : { 39 : : RTE_ASSERT(index < alloc_list->count); 40 : 0 : alloc_list->ptrs[index] = ptr; 41 : 0 : } 42 : : 43 : 0 : void alloc_list_free_all(struct alloc_list *alloc_list) 44 : : { 45 : : /* Copy and clear fields first in case alloc_list itself gets freed. */ 46 : 0 : size_t count = alloc_list->count; 47 : 0 : void ** const ptrs = alloc_list->ptrs; 48 : 0 : *alloc_list = (struct alloc_list){}; 49 : : 50 : 0 : while (count != 0) 51 : 0 : free(ptrs[--count]); 52 : 0 : free(ptrs); 53 : 0 : }