The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

parcel Lucy;

/**
 * Specialized memory allocator.
 *
 * Grab memory from the system in 1 MB chunks.  Don't release it until object
 * destruction.  Parcel the memory out on request.
 *
 * The release mechanism is fast but extremely crude, limiting the use of this
 * class to specific applications.
 */

class Lucy::Util::MemoryPool cnick MemPool
    inherits Lucy::Object::Obj {

    uint32_t     arena_size;
    VArray      *arenas;
    int32_t      tick;
    char        *buf;
    char        *last_buf;
    char        *limit;
    size_t       consumed; /* bytes allocated (not cap) */

    /**
     * @param arena_size The size of each internally allocated memory slab.
     * If 0, it will be set to 1 MiB.
     */
    inert incremented MemoryPool*
    new(uint32_t arena_size);

    inert MemoryPool*
    init(MemoryPool *self, uint32_t arena_size);

    /** Allocate memory from the pool.
     */
    void*
    Grab(MemoryPool *self, size_t amount);

    /** Resize the last allocation. (*Only* the last allocation).
     */
    void
    Resize(MemoryPool *self, void *ptr, size_t revised_amount);

    /** Tell the pool to consider all previous allocations released.
     */
    void
    Release_All(MemoryPool *self);

    /** Take ownership of all the arenas in another MemoryPool.  Can only be
     * called when the original memory pool has no outstanding allocations,
     * typically just after a call to Release_All.  The purpose is to support
     * bulk reallocation.
     */
    void
    Eat(MemoryPool *self, MemoryPool *other);

    size_t
    Get_Consumed(MemoryPool *self);

    public void
    Destroy(MemoryPool *self);
}