#include "altmalloc.h"

alt_allocater_t alt_malloc = malloc;

alt_allocater_t
alt_set_allocater(alt_allocater_t new)
{
  alt_allocater_t old;

  old = alt_malloc;
  alt_malloc = new;
  return old;
}

alt_allocater_t alt_malloc_atomic = malloc;

alt_allocater_t
alt_set_atomic_allocater(alt_allocater_t new)
{
  alt_allocater_t old;

  old = alt_malloc_atomic;
  alt_malloc_atomic = new;
  return old;
}

alt_reallocater_t alt_realloc = realloc;

alt_reallocater_t
alt_set_reallocater(alt_reallocater_t new)
{
  alt_reallocater_t old;

  old = alt_realloc;
  alt_realloc = new;
  return old;
}

alt_freer_t alt_free = free;

alt_freer_t
alt_set_freer(alt_freer_t new)
{
  alt_freer_t old;

  old = alt_free;
  alt_free = new;
  return old;
}

int
alt_malloc_vs(ptrdiff_t *p_size, ptrdiff_t n, ptrdiff_t limit, ...)
{
  va_list ap;

  va_start(ap, limit);

  if (n >= *p_size) {
    ptrdiff_t newsize;
    ptrdiff_t elem_size, isatomic;
    void **p_v, *newv;

    newsize = (n / 2 + 1) * 3;

    if (limit > 0) {
      if (n >= limit)
	return -1;

      if (newsize > limit)
	newsize = limit;
    }

    while ((p_v = va_arg(ap, void **))) {
      elem_size = va_arg(ap, ptrdiff_t);
      isatomic = va_arg(ap, int);

      if (*p_v)
	newv = alt_call_realloc(*p_v, elem_size * newsize);
      else if (isatomic)
	newv = alt_call_malloc_atomic(elem_size * newsize);
      else
	newv = alt_call_malloc(elem_size * newsize);

      if (!newv)
	return -1;

      memset((char *)newv + elem_size * n, 0, elem_size * (newsize - n));
      *p_v = newv;
    }

    *p_size = newsize;
  }

  va_end(ap);
  return 0;
}
