forked from cloudwu/mread
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.c
More file actions
97 lines (89 loc) · 1.44 KB
/
map.c
File metadata and controls
97 lines (89 loc) · 1.44 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
#include "map.h"
#include <stdlib.h>
#include <assert.h>
struct node {
int fd;
int id;
int next;
};
struct map {
int size;
struct node * hash;
};
struct map *
map_new(int max) {
int sz = 1;
while (sz <= max) {
sz *= 2;
}
struct map * m = malloc(sizeof(*m));
m->size = sz;
m->hash = malloc(sizeof(struct node) * sz);
int i;
for (i=0;i<sz;i++) {
m->hash[i].fd = -1;
m->hash[i].id = 0;
m->hash[i].next = -1;
}
return m;
}
void
map_delete(struct map * m) {
free(m->hash);
free(m);
}
int
map_search(struct map * m, int fd) {
int hash = fd & (m->size-1);
struct node * n = &m->hash[hash];
for(;;) {
if (n->fd == fd)
return n->id;
if (n->next < 0)
return -1;
n = &m->hash[n->next];
}
}
void
map_insert(struct map * m, int fd, int id) {
int hash = fd & (m->size-1);
struct node * n = &m->hash[hash];
for (;;) {
if (n->fd < 0) {
n->fd = fd;
n->id = id;
return;
}
if (n->next < 0 ) {
break;
}
n = &m->hash[n->next];
}
int last = (n - m->hash) * 2;
int i;
for (i=0;i<m->size;i++) {
int idx = (i + last + 1) & (m->size - 1);
struct node * temp = &m->hash[idx];
if (temp->fd < 0) {
temp->fd = fd;
temp->id = id;
n->next = idx;
return;
}
}
assert(0);
}
void
map_erase(struct map *m , int fd) {
int hash = fd & (m->size-1);
struct node * n = &m->hash[hash];
for(;;) {
if (n->fd == fd) {
n->fd = -1;
return;
}
if (n->next < 0)
return;
n = &m->hash[n->next];
}
}