/* -*- Mode: C; c-file-style: "gnu" -*-
   string.c -- native methods for java/lang/String.
   Created: Chris Toshok <toshok@hungry.com>, 13-Apr-1998
 */
/*
  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 "jniint.h"

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

typedef struct _interned_string {
  struct _interned_string *next;

  char *string;
  jstring java_string;
} interned_string;

static PRMonitor* lock = NULL;
static interned_string *strs;

jstring
Java_java_lang_String_intern(JNIEnv *env,
			     jobject obj)
{
  char *string_value;
  int string_value_length;
  const jbyte *string_value_bytes;
  interned_string *str;

  if (NULL == lock)
    lock = PR_NewMonitor();

  string_value_bytes = (*env)->GetStringUTFChars(env, obj, NULL);

  string_value_length = (*env)->GetStringUTFLength(env, obj) + 1;
  string_value = (char*)malloc(string_value_length * sizeof(char));

  strncpy(string_value, (char*)string_value_bytes, string_value_length);

  PR_EnterMonitor(lock);
  for (str = strs; str != NULL; str = str->next)
    if (!strcmp(string_value, str->string))
      return str->java_string;

  str = (interned_string*)calloc(1, sizeof(interned_string));
  str->string = string_value;
  str->java_string = (*env)->NewGlobalRef(env, obj);

  str->next = strs;
  strs = str;
  PR_ExitMonitor(lock);

  return str->java_string;
}
