svfield.c
2.75 KB
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
/*
* sieve header field cache.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include "svfield.h"
static int
sv_hash_field_name (const char *name)
{
int x = 0;
/* all CHAR up to the first that is ' ', :, or a ctrl char */
for (; !iscntrl (*name) && (*name != ' ') && (*name != ':'); name++)
{
x *= 256;
x += tolower (*name);
x %= SV_FIELD_CACHE_SIZE;
}
return x;
}
/*
The body is kept, the name is still the caller's.
*/
int
sv_field_cache_add (sv_field_cache_t * m, const char *name, char *body)
{
int cl, clinit;
/* put it in the hash table */
clinit = cl = sv_hash_field_name (name);
while (m->cache[cl] != NULL && strcasecmp (name, m->cache[cl]->name))
{
cl++; /* resolve collisions linearly */
cl %= SV_FIELD_CACHE_SIZE;
if (cl == clinit)
break; /* gone all the way around, so bail */
}
/* found where to put it, so insert it into a list */
if (m->cache[cl])
{
/* add this body on */
m->cache[cl]->contents[m->cache[cl]->ncontents++] = body;
/* whoops, won't have room for the null at the end! */
if (!(m->cache[cl]->ncontents % 8))
{
/* increase the size */
sv_field_t* field = (sv_field_t *) realloc (
m->cache[cl],
sizeof(sv_field_t) +
((8 + m->cache[cl]->ncontents) * sizeof(char *))
);
if (field == NULL)
{
return ENOMEM;
}
m->cache[cl] = field;
}
}
else
{
/* create a new entry in the hash table */
sv_field_t* field = (sv_field_t *) malloc (sizeof (sv_field_t) +
8 * sizeof (char *));
if (field)
{
return ENOMEM;
}
m->cache[cl] = field;
m->cache[cl]->name = strdup (name);
m->cache[cl]->contents[0] = body;
m->cache[cl]->ncontents = 1;
}
/* we always want a NULL at the end */
m->cache[cl]->contents[m->cache[cl]->ncontents] = NULL;
return 0;
}
int
sv_field_cache_get (sv_field_cache_t * m,
const char *name, const char ***body)
{
int rc = ENOENT;
int clinit, cl;
clinit = cl = sv_hash_field_name (name);
while (m->cache[cl] != NULL)
{
if (strcasecmp (name, m->cache[cl]->name) == 0)
{
*body = (const char **) m->cache[cl]->contents;
rc = 0;
break;
}
cl++; /* try next hash bin */
cl %= SV_FIELD_CACHE_SIZE;
if (cl == clinit)
break; /* gone all the way around */
}
return rc;
}
void
sv_field_cache_release (sv_field_cache_t * m)
{
int i;
for (i = 0; i < SV_FIELD_CACHE_SIZE; i++)
{
if (m->cache[i])
{
int j;
for (j = 0; m->cache[i]->contents[j]; j++)
{
free (m->cache[i]->contents[j]);
}
free (m->cache[i]);
}
}
}