-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.c
108 lines (92 loc) · 1.99 KB
/
map.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
101
102
103
104
105
106
107
/**
* @brief a simple integer to pointer map
* @author Sunniwell
* @date 2015-08-27 created
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "map.h"
struct _map
{
int max_key;
void **keys;
};
map_t* map_create(int max_key)
{
map_t *h = (map_t *)malloc(sizeof(map_t));
if (h == NULL)
{
printf("[map] malloc FAILED! %d\n", (int)sizeof(map_t));
return NULL;
}
memset(h, 0, sizeof(*h));
h->max_key = max_key;
h->keys = malloc(sizeof(void *) * (max_key + 1));
if (h->keys == NULL)
{
free(h);
printf("[map] malloc FAILED! %d\n", (int)sizeof(void *) * (max_key + 1));
return NULL;
}
memset(h->keys, 0, sizeof(void *) * (max_key + 1));
return h;
}
void map_destroy(map_t *h)
{
free(h->keys);
free(h);
}
int map_add(map_t *h, int key, void *value)
{
if (key < 0 || key > h->max_key)
{
printf("[map add] key [%d] exceed max_key [%d]\n", key, h->max_key);
return -1;
}
if (h->keys[key] != NULL)
{
printf("[map add] key [%d] already exist\n", key);
return -1;
}
h->keys[key] = value;
return 0;
}
int map_remove(map_t *h, int key)
{
if (key < 0 || key > h->max_key)
{
printf("[map remove] key [%d] exceed max_key [%d]\n", key, h->max_key);
return -1;
}
if (h->keys[key] == NULL)
{
printf("[map remove] key [%d] doesn't exist\n", key);
return -1;
}
h->keys[key] = NULL;
return 0;
}
void* map_get(map_t *h, int key)
{
if (key < 0 || key > h->max_key)
{
printf("[map get] key [%d] exceed max_key [%d]\n", key, h->max_key);
return NULL;
}
return h->keys[key];
}
int map_get_next(map_t *h, int curr_key, int *key, void **value)
{
int k;
for (k = curr_key + 1; k <= h->max_key; k++)
{
if (h->keys[k] != NULL)
{
*key = k;
*value = h->keys[k];
return 0;
}
}
return -1;
}