ucx/map.c

changeset 53
e533c170bfb8
parent 52
34f50d0bada4
child 67
27e67e725d35
equal deleted inserted replaced
52:34f50d0bada4 53:e533c170bfb8
104 UcxMapElement *e = (UcxMapElement*)malloc(sizeof(UcxMapElement)); 104 UcxMapElement *e = (UcxMapElement*)malloc(sizeof(UcxMapElement));
105 if(e == NULL) { 105 if(e == NULL) {
106 return -1; 106 return -1;
107 } 107 }
108 e->key.data = NULL; 108 e->key.data = NULL;
109 if (prev == NULL) { 109 if (prev) {
110 prev->next = e;
111 } else {
110 map->map[slot] = e; 112 map->map[slot] = e;
111 } else {
112 prev->next = e;
113 } 113 }
114 e->next = elm; 114 e->next = elm;
115 elm = e; 115 elm = e;
116 } 116 }
117 117
128 elm->data = data; 128 elm->data = data;
129 129
130 return 0; 130 return 0;
131 } 131 }
132 132
133 void* ucx_map_get(UcxMap *map, UcxKey key) { 133 void* ucx_map_get_and_remove(UcxMap *map, UcxKey key, _Bool remove) {
134 if(key.hash == 0) { 134 if(key.hash == 0) {
135 key.hash = ucx_hash((char*)key.data, key.len); 135 key.hash = ucx_hash((char*)key.data, key.len);
136 } 136 }
137 137
138 UcxMapElement *elm = map->map[key.hash%map->size]; 138 size_t slot = key.hash%map->size;
139 while (elm != NULL && elm->key.hash <= key.hash) { 139 UcxMapElement *elm = map->map[slot];
140 UcxMapElement *pelm = NULL;
141 while (elm && elm->key.hash <= key.hash) {
140 if(elm->key.hash == key.hash) { 142 if(elm->key.hash == key.hash) {
141 int n = (key.len > elm->key.len) ? elm->key.len : key.len; 143 int n = (key.len > elm->key.len) ? elm->key.len : key.len;
142 if (memcmp(elm->key.data, key.data, n) == 0) { 144 if (memcmp(elm->key.data, key.data, n) == 0) {
143 return elm->data; 145 void *data = elm->data;
144 } 146 if (remove) {
145 } 147 if (pelm) {
146 elm = elm->next; 148 pelm->next = elm->next;
149 } else {
150 map->map[slot] = elm->next;
151 }
152 free(elm);
153 map->count--;
154 }
155
156 return data;
157 }
158 }
159 pelm = elm;
160 elm = pelm->next;
147 } 161 }
148 162
149 return NULL; 163 return NULL;
164 }
165
166 void *ucx_map_get(UcxMap *map, UcxKey key) {
167 return ucx_map_get_and_remove(map, key, 0);
168 }
169
170 void *ucx_map_remove(UcxMap *map, UcxKey key) {
171 return ucx_map_get_and_remove(map, key, 1);
150 } 172 }
151 173
152 UcxKey ucx_key(void *data, size_t len) { 174 UcxKey ucx_key(void *data, size_t len) {
153 UcxKey key; 175 UcxKey key;
154 key.data = data; 176 key.data = data;

mercurial