src/map.c

changeset 327
fbc33813265b
parent 287
98da78a1e69a
child 328
2bf1da3c411e
equal deleted inserted replaced
326:3dd7d21fb76b 327:fbc33813265b
152 152
153 int ucx_map_put(UcxMap *map, UcxKey key, void *data) { 153 int ucx_map_put(UcxMap *map, UcxKey key, void *data) {
154 UcxAllocator *allocator = map->allocator; 154 UcxAllocator *allocator = map->allocator;
155 155
156 if (key.hash == 0) { 156 if (key.hash == 0) {
157 key.hash = ucx_hash((char*)key.data, key.len); 157 key.hash = ucx_hash(key.data, key.len);
158 } 158 }
159 159
160 size_t slot = key.hash%map->size; 160 struct UcxMapKey mapkey;
161 mapkey.hash = key.hash;
162
163 size_t slot = mapkey.hash%map->size;
161 UcxMapElement *elm = map->map[slot]; 164 UcxMapElement *elm = map->map[slot];
162 UcxMapElement *prev = NULL; 165 UcxMapElement *prev = NULL;
163 166
164 while (elm && elm->key.hash < key.hash) { 167 while (elm && elm->key.hash < mapkey.hash) {
165 prev = elm; 168 prev = elm;
166 elm = elm->next; 169 elm = elm->next;
167 } 170 }
168 171
169 if (!elm || elm->key.hash != key.hash) { 172 if (!elm || elm->key.hash != mapkey.hash) {
170 UcxMapElement *e = (UcxMapElement*)almalloc( 173 UcxMapElement *e = (UcxMapElement*)almalloc(
171 allocator, sizeof(UcxMapElement)); 174 allocator, sizeof(UcxMapElement));
172 if (!e) { 175 if (!e) {
173 return -1; 176 return -1;
174 } 177 }
186 void *kd = almalloc(allocator, key.len); 189 void *kd = almalloc(allocator, key.len);
187 if (!kd) { 190 if (!kd) {
188 return -1; 191 return -1;
189 } 192 }
190 memcpy(kd, key.data, key.len); 193 memcpy(kd, key.data, key.len);
191 key.data = kd; 194 mapkey.data = kd;
192 elm->key = key; 195 mapkey.len = key.len;
196 elm->key = mapkey;
193 map->count++; 197 map->count++;
194 } 198 }
195 elm->data = data; 199 elm->data = data;
196 200
197 return 0; 201 return 0;
237 241
238 void *ucx_map_remove(UcxMap *map, UcxKey key) { 242 void *ucx_map_remove(UcxMap *map, UcxKey key) {
239 return ucx_map_get_and_remove(map, key, 1); 243 return ucx_map_get_and_remove(map, key, 1);
240 } 244 }
241 245
242 UcxKey ucx_key(void *data, size_t len) { 246 UcxKey ucx_key(const void *data, size_t len) {
243 UcxKey key; 247 UcxKey key;
244 key.data = data; 248 key.data = data;
245 key.len = len; 249 key.len = len;
246 key.hash = ucx_hash((const char*) data, len); 250 key.hash = ucx_hash(data, len);
247 return key; 251 return key;
248 } 252 }
249 253
250 254
251 int ucx_hash(const char *data, size_t len) { 255 int ucx_hash(const char *data, size_t len) {
310 while (i->index < i->map->size) { 314 while (i->index < i->map->size) {
311 if (e) { 315 if (e) {
312 if (e->data) { 316 if (e->data) {
313 i->cur = e; 317 i->cur = e;
314 *elm = e->data; 318 *elm = e->data;
315 *key = e->key; 319 key->data = e->key.data;
320 key->hash = e->key.hash;
321 key->len = e->key.len;
316 return 1; 322 return 1;
317 } 323 }
318 324
319 e = e->next; 325 e = e->next;
320 } else { 326 } else {

mercurial