/*
    Clif - A C-like Interpreter Framework
    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997 T. Hruz, L. Koren
    1998 L. Koren

    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.

*/
/*
 * allocx.c
 *
 * calloc interface
 *
 */

#include <stdio.h>
#include "config.h"
#include "global.h"
#ifdef STDC_HEADERS
#include <stdlib.h>
#else
#include <malloc.h>
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#endif

#include "allocx.h"

#define MASK 7
#define PAGE 1024
#define K 10

union align
{
  long l;
  char *p;
  double d;
  int (*f) PROTO((void));
};

struct pool_chunk
{
  struct pool_chunk *next;
  char *position;
  char *limit;
};

union header
{
  struct pool_chunk p;
  union align a;
};

static struct pool_chunk first[] = {{ NULL }, { NULL }},
		       *pool[] = { &first[0], &first[1]},
  *freeblock;

char *
callocx (n, size)
     unsigned n, size;
{
  return((char *)calloc(n,size));
}

char *
allocate (n, a)
     unsigned n,a;
{
  register struct pool_chunk *cp;

#ifdef HAVE_ASSERT_H
  assert (a < sizeof(pool)/sizeof(pool[0]));
#endif

  cp = pool[a];

  if (n & MASK)
    n += 8 - (n & MASK);
    
  while (cp->position + n > cp->limit)
    {
      if (NULL != (cp->next = freeblock))
	{
	  freeblock = freeblock->next;
	  cp = cp->next;
	}
      else
	{
	  unsigned m = sizeof(union header) + n + K * PAGE;
	  cp->next = (struct pool_chunk *)callocx (1, m);
	  cp = cp->next;
	  if (NULL == cp)
	    {
	      error_message (4002);
	      exit (1);
	    }
	  cp->limit = (char *)cp + m;
	}
      cp->position = (char *)(cp + sizeof (union header));
      cp->next = NULL;
      pool[a] = cp;
    }
  cp->position += n;
  return cp->position - n;
}

void
deallocate (a)
  unsigned a;
{
#ifdef HAVE_ASSERT_H
  assert (a < sizeof(pool)/sizeof(pool[0]));
#endif

  pool[a]->next = freeblock;
  freeblock = first[a].next;
  first[a].next = NULL;
  pool[a] = &first[a];
}

void
init_zero (p, n)
  char *p;
  unsigned n;
{
  while (n--)
    *p++ = 0;
}

void *
mallocx (size)
  unsigned int size;
{
  register void *res = malloc (size);

  if (res == NULL)
    error_message (4002);
  return res;
}

void *
reallocx (ptr, size)
  void *ptr;
  unsigned size;
{
  register void *res = realloc (ptr, size);

  if (res == NULL)
    error_message (4002);
  return res;
}

void
freex (ptr)
  void *ptr;
{
  return (free (ptr));
}
