~ubuntu-branches/ubuntu/utopic/clif/utopic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
    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;
  }
}