/* -*- Mode: C; c-file-style: "gnu" -*-
   alloc.c -- our wrappers with exceptions for *alloc(), free() and strdup()
   Created: Petter Reinholdtsen <pere@td.org.uit.no>, 1998-07-16
*/
/*
  This file is part of Japhar, the GNU Virtual Machine for Java Bytecodes.
  Japhar is a project of The Hungry Programmers, GNU, and OryxSoft.

  Copyright (C) 1997, 1998, 1999 The Hungry Programmers

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "alloc.h"
#include "exceptions.h"

#include <stdlib.h>
#include <string.h>

#define OutOfMemoryError	"java/lang/OutOfMemoryError"
#define NullPointerException	"java/lang/NullPointerException"

void *
jmalloc(JNIEnv *env, size_t size)
{
  void *ptr = malloc(size);

  if (NULL == ptr)
    throw_Exception(env, OutOfMemoryError, "malloc() failed");

  return ptr;
}

void *
jcalloc(JNIEnv *env, size_t nmemb, size_t size)
{
  void *ptr = calloc(nmemb, size);

  if (NULL == ptr)
    throw_Exception(env, OutOfMemoryError, "calloc() failed");

  return ptr;
}

void
jfree(JNIEnv *env, void *ptr)
{
  if (NULL == ptr)
    return; /* XXX Should this throw NullPointerException? [pere] */
  free(ptr);
}

void *
jrealloc(JNIEnv *env, void *ptr, size_t size)
{
  void *retptr;

  if (size == 0)
    return NULL; /* XXX Should this throw NullPointerException? [pere] */

  retptr = realloc(ptr, size);

  if (NULL == retptr)
    throw_Exception(env, OutOfMemoryError, "realloc() failed");

  return retptr;
}

char *
jstrdup(JNIEnv *env, const char *str)
{
  char *ptr;
  if (NULL == str)
    {
      throw_Exception(env, NullPointerException, "strdup() failed");
      return NULL;
    }

  ptr = strdup(str);

  if (NULL == ptr)
    throw_Exception(env, OutOfMemoryError, "strdup() failed");

  return ptr;
}
