/* trealloc.c (emx+gcc) -- Copyright (c) 1995 by Eberhard Mattes */

#include <stdlib.h>
#include "tmalloc.h"

void *_trealloc (void *mem, size_t new_size)
{
  void *p;
  size_t copy;

  /* First handle the trivial cases: if MEM is NULL, _trealloc()
     behaves like _tmalloc(). */

  if (mem == NULL)
    return _tmalloc (new_size);

  /* If the new size is 0, free the block. */

  if (new_size == 0)
    {
      _tfree (mem);
      return NULL;
    }

  /* Do not attempt to call realloc() and hope for proper alignment.
     If the new block is not properly aligned, we have to call
     _tmalloc().  If that fails, we are in trouble as we cannot safely
     restore the original block with proper alignment. */

  /* Allocate a new block. */

  p = _tmalloc (new_size);
  if (p == NULL)
    return NULL;
  copy = TM_HEADER (mem)->size;
  if (new_size < copy)
    copy = new_size;
  memcpy (p, mem, copy);
  _tfree (mem);
  return p;
}
