/
hash.c
100 lines (73 loc) · 2.08 KB
/
hash.c
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
/*
Copyright (C) 2006 by Jonas Kramer
Published under the terms of the GNU General Public License (GPL).
*/
#define _GNU_SOURCE
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "hash.h"
#include "util.h"
void set(struct hash * hash, const char * key, const char * value) {
unset(hash, key);
hash->content =
realloc(hash->content, sizeof(struct pair) * (hash->size + 1));
assert(hash->content != NULL);
assert((hash->content[hash->size].key = strdup(key)) != NULL);
assert((hash->content[hash->size].value = strdup(value)) != NULL);
++hash->size;
}
const char * value(struct hash * hash, const char * key) {
unsigned index = haskey(hash, key);
return index > 0 ? hash->content[index - 1].value : "";
}
void unset(struct hash * hash, const char * key) {
unsigned index = haskey(hash, key);
if(index > 0) {
--index;
if(hash->content[index].key != NULL)
free(hash->content[index].key);
if(hash->content[index].value != NULL)
free(hash->content[index].value);
memcpy(
& hash->content[index],
& hash->content[--hash->size],
sizeof(struct pair));
hash->content = realloc(hash->content, sizeof(struct pair) * hash->size);
assert(hash->content != NULL);
}
}
void empty(struct hash * hash) {
if(hash != NULL) {
if(hash->content != NULL) {
while(hash->size > 0) {
--hash->size;
if(hash->content[hash->size].key != NULL)
free(hash->content[hash->size].key);
if(hash->content[hash->size].value != NULL)
free(hash->content[hash->size].value);
}
free(hash->content);
}
memset(hash, 0, sizeof(struct hash));
}
}
int haskey(struct hash * hash, const char * key) {
register unsigned x;
assert(hash != NULL);
assert(key != NULL);
if(!hash->size || !hash->content)
return 0;
for(x = 0; x < hash->size; ++x)
if(hash->content[x].key != NULL && !strcmp(hash->content[x].key, key))
return x + 1;
return 0;
}
void dump_hash(struct hash * h) {
unsigned n;
assert(h != NULL);
for(n = 0; n < h->size; ++n) {
debug("dump_hash: <%s> = <%s>\n", h->content[n].key, h->content[n].value);
}
}