// Copyright 1994 by Jon Dart.  All Rights Reserved.

#ifndef POOL_H
#define POOL_H

#include <stddef.h>
#include "types.h"

    enum { BLOCK_SIZE = 4096 };
    struct block;
    typedef struct block *block_ptr;
    struct block
    {
#ifdef _WINDOWS
        HGLOBAL hMem;
#endif
        char mem[BLOCK_SIZE];
    };

    struct chunk;
    typedef struct chunk *chunk_ptr;
    struct chunk
    {
        block_ptr blk;
        chunk_ptr next;
    };

    struct alloc;
    typedef struct alloc *alloc_ptr;
    struct alloc
    {
        alloc_ptr next;
        char *mem;
    };

class Pool
{
   // This class defines a simple memory allocator.  Memory is allocated
   // in large chunks, and doled out by "new" into smaller chunks.  Freed
   // memory goes into a free list.  Actual deletion of memory doesn't
   // occur until freeAll() is called.

public:
    Pool();
    
    virtual ~Pool();

    void *allocate( size_t size );

    void free( void *p );

    void freeAll(BOOL final = FALSE);

private:
    chunk * memChain;
    chunk * freeChunks;
    char *nextMem;
    alloc_ptr freeChain;
    CRITICAL_SECTION memCriticalSection;
};

#endif
