github.com/goccy/go-jit@v0.0.0-20200514131505-ff78d45cf6af/internal/ccall/jit-pool.c (about) 1 /* 2 * jit-pool.c - Functions for managing memory pools. 3 * 4 * Copyright (C) 2004 Southern Storm Software, Pty Ltd. 5 * 6 * This file is part of the libjit library. 7 * 8 * The libjit library is free software: you can redistribute it and/or 9 * modify it under the terms of the GNU Lesser General Public License 10 * as published by the Free Software Foundation, either version 2.1 of 11 * the License, or (at your option) any later version. 12 * 13 * The libjit library is distributed in the hope that it will be useful, 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 * Lesser General Public License for more details. 17 * 18 * You should have received a copy of the GNU Lesser General Public 19 * License along with the libjit library. If not, see 20 * <http://www.gnu.org/licenses/>. 21 */ 22 23 #include "jit-internal.h" 24 25 void _jit_memory_pool_init(jit_memory_pool *pool, unsigned int elem_size) 26 { 27 pool->elem_size = elem_size; 28 pool->elems_per_block = 4000 / elem_size; 29 pool->elems_in_last = pool->elems_per_block; 30 pool->blocks = 0; 31 pool->free_list = 0; 32 } 33 34 void _jit_memory_pool_free(jit_memory_pool *pool, jit_meta_free_func func) 35 { 36 jit_pool_block_t block; 37 while(pool->blocks != 0) 38 { 39 block = pool->blocks; 40 pool->blocks = block->next; 41 if(func) 42 { 43 while(pool->elems_in_last > 0) 44 { 45 --(pool->elems_in_last); 46 (*func)(block->data + pool->elems_in_last * pool->elem_size); 47 } 48 } 49 jit_free(block); 50 pool->elems_in_last = pool->elems_per_block; 51 } 52 pool->free_list = 0; 53 } 54 55 void *_jit_memory_pool_alloc(jit_memory_pool *pool) 56 { 57 void *data; 58 if(pool->free_list) 59 { 60 /* Reclaim an item that was previously deallocated */ 61 data = pool->free_list; 62 pool->free_list = *((void **)data); 63 jit_memzero(data, pool->elem_size); 64 return data; 65 } 66 if(pool->elems_in_last >= pool->elems_per_block) 67 { 68 data = (void *)jit_calloc(1, sizeof(struct jit_pool_block) + 69 pool->elem_size * pool->elems_per_block - 1); 70 if(!data) 71 { 72 return 0; 73 } 74 ((jit_pool_block_t)data)->next = pool->blocks; 75 pool->blocks = (jit_pool_block_t)data; 76 pool->elems_in_last = 0; 77 } 78 data = (void *)(pool->blocks->data + 79 pool->elems_in_last * pool->elem_size); 80 ++(pool->elems_in_last); 81 return data; 82 } 83 84 void _jit_memory_pool_dealloc(jit_memory_pool *pool, void *item) 85 { 86 *((void **)item) = pool->free_list; 87 pool->free_list = item; 88 }