Пример #1
0
/* If this function succeeds, then we guarantee that there will be at
 * least one object in mp->free_list. */
void
cork_mempool_new_block(struct cork_mempool *mp)
{
    /* Allocate the new block and add it to mp's block list. */
    struct cork_mempool_block  *block;
    void  *vblock;
    DEBUG("Allocating new %zu-byte block\n", mp->block_size);
    block = cork_malloc(mp->block_size);
    block->next_block = mp->blocks;
    mp->blocks = block;
    vblock = block;

    /* Divide the block's memory region into a bunch of objects. */
    size_t  index = sizeof(struct cork_mempool_block);
    for (index = sizeof(struct cork_mempool_block);
         (index + cork_mempool_object_size(mp)) <= mp->block_size;
         index += cork_mempool_object_size(mp)) {
        struct cork_mempool_object  *obj = vblock + index;
        DEBUG("  New object at %p[%p]\n", cork_mempool_get_object(obj), obj);
        if (mp->init_object != NULL) {
            mp->init_object(cork_mempool_get_object(obj));
        }
        obj->next_free = mp->free_list;
        mp->free_list = obj;
    }
}
Пример #2
0
void
cork_array_ensure_size_(void *varray, size_t desired_count, size_t element_size)
{
    struct cork_array_private  *array = varray;

    if ((array->allocated_size == 0) &&
        (desired_count < CORK_INTERNAL_COUNT_FROM_SIZE(element_size))) {
        /* There's already enough space in our internal storage, which
         * we're still using. */
        return;
    }

    /* Otherwise reallocate if there's not enough space in our
     * heap-allocated array. */
    size_t  desired_size = desired_count * element_size;

    if (array->allocated_size == 0) {
        size_t  old_size =
            element_size * CORK_INTERNAL_COUNT_FROM_SIZE(element_size);
        size_t  new_size = CORK_ARRAY_SIZE;
        if (desired_size > new_size) {
            new_size = desired_size;
        }

        DEBUG("--- Array %p: Allocating %zu->%zu bytes",
              array, old_size, new_size);
        array->items = cork_malloc(new_size);
        memcpy(array->items, &array->internal, old_size);
        array->allocated_size = new_size;
    }

    else if (desired_size > array->allocated_size) {
        size_t  new_size = array->allocated_size * 2;
        if (desired_size > new_size) {
            new_size = desired_size;
        }

        DEBUG("--- Array %p: Reallocating %zu->%zu bytes",
              array, array->allocated_size, new_size);
        array->items = cork_realloc(array->items, new_size);
        array->allocated_size = new_size;
    }
}