/*
Copyright (C) 1997-2001 Id Software, Inc.

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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/
// hunk.c

#include <stdlib.h>
#include <errno.h>

#include "dynarea.h"

#ifdef GCCBROKENRELATIVEPATHS
#include "../../qcommon/qcommon.h"
#else
#include "../qcommon/qcommon.h"
#endif

DynamicArea * currentHunk;
char        * membase;
int           maxhunksize;
int           curhunksize;

#define BASE_OFFSET (sizeof(DynamicArea*))

void *Hunk_Begin (int maxsize, char * type)
{
    _kernel_oserror * e;
    DynamicArea * newArea = NULL;

    if ((e = DynamicArea_Create(type, maxsize + BASE_OFFSET, &newArea)) != NULL)
    {
        Com_Error (ERR_FATAL, "Error in Hunk_Begin: %s\n", e->errmess);
    }

    currentHunk = newArea;
    maxhunksize = maxsize;
    curhunksize = 0;

    membase = (char*)newArea->base;

    // Store dynamic area address in base of hunk
    if ((e = DynamicArea_SetSize(currentHunk, BASE_OFFSET)) != NULL)
    {
        Com_Error (ERR_FATAL, "Error in Hunk_Begin: %s\n", e->errmess);
    }

    *((DynamicArea**)membase) = newArea;
    membase += BASE_OFFSET;

    return membase;
}

void *Hunk_Alloc (int size)
{
    _kernel_oserror * e;
    char *buf;

    // round up to cacheline
    size = (size+31)&~31;

    if (curhunksize + size > maxhunksize)
    {
        Com_Error (ERR_FATAL, "Hunk_Alloc overflow\n");
    }

    buf          = membase + curhunksize;
    curhunksize += size;

    if ((e = DynamicArea_SetSize(currentHunk, curhunksize + BASE_OFFSET)) != NULL)
    {
        Com_Error (ERR_FATAL, "Error in Hunk_Alloc: %s\n", e->errmess);
    }

    memset(buf, 0, size);

    return buf;
}

void Hunk_Free (void *buf)
{
    if (buf)
    {
        DynamicArea * area = *(DynamicArea**)(((char*)buf) - 4);

        DynamicArea_Destroy(area);
    }
}

int Hunk_End (void)
{
    return curhunksize;
}
