/*
    Clif - A C-like Interpreter Framework
    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997 T. Hruz, 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.

*/

/* 
 symbols.c
 saving a copy of each string
 */

#include <string.h>
#include "allocx.h"

#ifndef PROTO
#if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined(__STDC__)
#define PROTO(ARGS) ARGS
#else
#define PROTO(ARGS) ()
#endif 
#endif

#define SIZE_HAS 1999
#define PAGE 1024
#define K 4

static unsigned int hash PROTO((char *));
char *string PROTO((char *));

static struct string
{
  char *str;
  int len;
  struct string *next;
} *buckets[SIZE_HAS + 1];

static unsigned int
hash (s)
     char *s;
{
  int             c = 0;

  while (*s)
    {
      c = c << 1 ^ (*s);
      s++;
    }
  if (0 > c)
    c = (-c);
  return (c % SIZE_HAS);
}

char *
string (s)
     char *s;
{
  int len = strlen (s);
  unsigned int h;
  struct string *p;
  char *end = s + len;
  
  h = hash (s);
  for (p = buckets[h]; p; p = p->next)
    if (p->len == len)
      {
	char *s1 = s, *s2 = p->str;
	
	do
	  {
	    if (s1 == end)
	      return p->str;
	  } while (*s1++ == *s2++);
      }
  {
    static char *next, *limit;

    if (next + len + 1 >= limit)
      {
	int n = len + K * PAGE;

	next = allocate (n, PERM);
	limit = next + n;
      }
    p = (struct string *)allocate (sizeof (*p), PERM);
    p->len = len;
    for (p->str = next; s < end;)
      *next++ = *s++;
    *next++ = '\0';
    p->next = buckets[h];
    buckets[h] = p;
    return p->str;
  }
}
