~moody/mpl

mpl/dat.c -rw-r--r-- 2.0 KiB
7309e0f2 — Jacob Moody Archive and point to zuke 6 months ago
                                                                                
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include <u.h>
#include <libc.h>
#include <thread.h>
#include <draw.h>

#include "dat.h"
#include "fncs.h"

uvlong
string2hash(char *s)
{
	uvlong hash;
	hash = 7;
	for(;*s;s++)
		hash = hash*31 + *s;
	return hash;
}

Hmap*
allocmap(int size)
{
	Hmap *h = emalloc(sizeof(Hmap));
	h->size = size;
	h->nodes = emalloc(sizeof(Hnode)*size);
	return h;
}

void
mapinsert(Hmap *h, char *key, void *val)
{
	Hnode *n;

	wlock(h);
	n = h->nodes+(string2hash(key)%h->size);
	assert(n != nil);
	for(;;){
		if(n->key == nil)
			goto empty;
		if(strcmp(key, n->key) == 0)
			goto found;
		if(n->next == nil)
			break;
		n = n->next;
	}

	/* create new node */
	n->next = emalloc(sizeof(Hnode));
	n = n->next;

empty:
	n->key = strdup(key);

found:
	n->val = val;

	wunlock(h);
}

void*
mapget(Hmap *h, char *key)
{
	Hnode *n;

	rlock(h);
	n = h->nodes+(string2hash(key)%h->size);
	for(;n!=nil;n=n->next){
		if(n->key == nil)
			continue;
		if(strcmp(key, n->key) == 0){
			runlock(h);
			return n->val;
		}
	}

	runlock(h);
	return nil;
}

int
mapdel(Hmap *h, char *key)
{
	Hnode *n;
	wlock(h);
	n = h->nodes+(string2hash(key)%h->size);
	for(;n!=nil;n=n->next){
		if(n->key == nil)
			continue;
		if(strcmp(key, n->key) == 0){
			free(n->key);
			n->key = nil;
			wunlock(h);
			return 1;
		}
	}

	wunlock(h);
	return 0;
}

int
mapdump(Hmap *h, void **buf, int size)
{
	Hnode *n;
	int i, c;

	rlock(h);
	for(i=c=0;i<h->size;i++)
		for(n=h->nodes+i;n!=nil && n->key!=nil;n=n->next){
			if(c >= size)
				goto done;
			buf[c++] = n->val;
		}
done:
	runlock(h);
	return c;
}

int
mapdumpkey(Hmap *h, char **buf, int size)
{
	Hnode *n;
	int i, c;

	rlock(h);
	for(i=c=0;i<h->size;i++)
		for(n=h->nodes+i;n!=nil && n->key!=nil;n=n->next){
			if(c >= size)
				goto done;
			buf[c++] = n->key;
		}
done:
	runlock(h);
	return c;
}

void
mapclear(Hmap *h)
{
	Hnode *n;
	int i;

	wlock(h);
	for(i=0;i<h->size;i++)
		for(n=h->nodes+i;n!=nil;n=n->next)
			if(n->key != nil){
				free(n->key);
				n->key=nil;
			}
	wunlock(h);
}

void
freemap(Hmap *h)
{
	mapclear(h);
	free(h->nodes);
	free(h);
}