summaryrefslogtreecommitdiff
path: root/server/zstring.c
blob: 575adc93594d1b48a10fbe9ec4d6a605d47ef4b0 (plain)
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/*
 * Copyright (C) 1991 by the Massachusetts Institute of Technology.
 * For copying and distribution information, see the file "mit-copyright.h".
 *
 *	$Source$
 *	$Id$
 *	$Author$
 */

#include <mit-copyright.h>

#include <ctype.h>
#ifdef __STDC__
#include <stdlib.h>
#endif
#include <string.h>
#include "zstring.h"

static ZSTRING *zhash[ZSTRING_HASH_TABLE_SIZE];

#ifdef __STDC__
# define        P(s) s
#else
# define P(s) ()
#endif

extern unsigned long hash P((const char *s));
extern char *strsave P((const char *s));
#undef P

ZSTRING *
make_zstring(s, downcase)
     char *s;
     int downcase;
{
  char *new_s,*p;
  ZSTRING *new_z,*hp;
  int hash_val;

  if (downcase) {
    new_s = strsave(s);
    p = new_s;
    while(*p) {
      if (isascii(*p) && isupper(*p))
	*p = tolower(*p);
      p++;
    }
  } else {
    new_s = s;
  }

  new_z = find_zstring(new_s,0);
  if (new_z != NULL) {
    if (downcase)
      free(new_s);
    new_z->ref_count++;
    return(new_z);
  }

  /* Initialize new ZSTRING */

  if (!downcase)
    new_s = strsave(s);
  new_z = malloc(sizeof(ZSTRING));
  new_z->string = new_s;
  new_z->len = strlen(new_s);
  new_z->ref_count = 1;
  
  /* Add to beginning of hash table */
  hash_val = hash(new_s) % ZSTRING_HASH_TABLE_SIZE;
  hp = zhash[hash_val];
  new_z->next = hp;
  if (hp != NULL)
    hp->prev = new_z;
  new_z->prev = NULL;
  zhash[hash_val] = new_z;

  return(new_z);
}

void
free_zstring(z)
     ZSTRING *z;
{
  ZSTRING *hp;
  int hash_val;

  z->ref_count--;
  if (z->ref_count > 0)
    return;

  /* delete zstring completely */
  if(z->prev == NULL)
    zhash[hash(z->string) % ZSTRING_HASH_TABLE_SIZE] = z->next;
  else
    z->prev->next = z->next;
  
  if (z->next != NULL)
    z->next->prev = z->prev;

  free(z->string);
  free(z);
  return;
}

ZSTRING *
find_zstring(s,downcase)
     char *s;
     int downcase;
{
  char *new_s,*p;
  ZSTRING *z;

  if (downcase) {
    new_s = strsave(s);
    p = new_s;
    while (*p) {
      if (isascii(*p) && isupper(*p))
	*p = tolower(*p);
      p++;
    }
  } else {
    new_s = s;
  }

  z = zhash[hash(new_s) % ZSTRING_HASH_TABLE_SIZE];
  while (z != (ZSTRING *)NULL) {
    if (strcmp(new_s,z->string) == 0)
      break;
    z = z->next;
  }

  if (downcase)
    free(new_s);

  return(z);
}

int
eq_zstring(a,b)
     ZSTRING *a, *b;
{
  return(a == b);
}