/*
 *
 * UNICON - The Console Chinese & I18N
 * Copyright (c) 1999-2000
 *
 * This file is part of UNICON, a console Chinese & I18N
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * See the file COPYING directory of this archive
 * Author: see CREDITS
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <TLS_MemBlock.hpp>

#define DYN_BLOCK_NUMBER   32

TLS_CMemBlock::TLS_CMemBlock (u_int BlockSize0)
{
    BlockSize = BlockSize0;
    MaxBlock = DYN_BLOCK_NUMBER;
    pBuf = (char **) malloc (MaxBlock * sizeof (char *));
    for (u_int i = 0; i < MaxBlock; i++)
    {
        pBuf[i] = (char *) malloc (BlockSize);
        if (pBuf[i] == NULL)
        {
            printf ("No enough memory to run CMemPhrase ()\n");
            exit (-1);
         }
    }
    nBuf = 0;
    nCurPos = 0;
}

TLS_CMemBlock::~TLS_CMemBlock ()
{
    for (u_int i = 0; i < MaxBlock; i++)
         free (pBuf[i]);
    free (pBuf);
}

char *TLS_CMemBlock::Malloc (u_int Size)
{
    if (nCurPos + Size > BlockSize)
    {
        nBuf ++, nCurPos = 0;
        if (nBuf >= MaxBlock)
        {
            u_int i = MaxBlock;
            MaxBlock += DYN_BLOCK_NUMBER;
            pBuf = (char **) realloc (pBuf, MaxBlock * sizeof (char *));
            if (pBuf == (char **) NULL)
            {
                printf ("No enough memory to run CMemPhrase ()\n");
                exit (-1);
            } 
            for (; i < MaxBlock; i++)
            {
                pBuf[i] = (char *) malloc (BlockSize);
                if (pBuf[i] == NULL)
                {
                    printf ("No enough memory to run CMemPhrase ()\n");
                    exit (-1);
                 }
            }
        }
    }
    char *p = pBuf[nBuf] + nCurPos;
    nCurPos += Size;
    return p;
}

char *TLS_CMemBlock::MemDup (char *p, u_int Size)
{
    char *q = (char *) Malloc (Size);
    memcpy (q, p, Size);
    return q;
}

