ucx/map.c

changeset 53
e533c170bfb8
parent 52
34f50d0bada4
child 67
27e67e725d35
     1.1 --- a/ucx/map.c	Fri Oct 05 16:59:14 2012 +0200
     1.2 +++ b/ucx/map.c	Mon Oct 08 12:29:27 2012 +0200
     1.3 @@ -106,10 +106,10 @@
     1.4              return -1;
     1.5          }
     1.6          e->key.data = NULL;
     1.7 -        if (prev == NULL) {
     1.8 +        if (prev) {
     1.9 +            prev->next = e;
    1.10 +        } else {
    1.11              map->map[slot] = e;
    1.12 -        } else {
    1.13 -            prev->next = e;
    1.14          }
    1.15          e->next = elm;
    1.16          elm = e;
    1.17 @@ -130,25 +130,47 @@
    1.18      return 0;
    1.19  }
    1.20  
    1.21 -void* ucx_map_get(UcxMap *map, UcxKey key) {
    1.22 +void* ucx_map_get_and_remove(UcxMap *map, UcxKey key, _Bool remove) {
    1.23      if(key.hash == 0) {
    1.24          key.hash = ucx_hash((char*)key.data, key.len);
    1.25      }
    1.26      
    1.27 -    UcxMapElement *elm = map->map[key.hash%map->size];
    1.28 -    while (elm != NULL && elm->key.hash <= key.hash) {
    1.29 +    size_t slot = key.hash%map->size;
    1.30 +    UcxMapElement *elm = map->map[slot];
    1.31 +    UcxMapElement *pelm = NULL;
    1.32 +    while (elm && elm->key.hash <= key.hash) {
    1.33          if(elm->key.hash == key.hash) {
    1.34              int n = (key.len > elm->key.len) ? elm->key.len : key.len;
    1.35              if (memcmp(elm->key.data, key.data, n) == 0) {
    1.36 -                return elm->data;
    1.37 +                void *data = elm->data;
    1.38 +                if (remove) {
    1.39 +                    if (pelm) {
    1.40 +                        pelm->next = elm->next;
    1.41 +                    } else {
    1.42 +                        map->map[slot] = elm->next;
    1.43 +                    }
    1.44 +                    free(elm);
    1.45 +                    map->count--;
    1.46 +                }
    1.47 +
    1.48 +                return data;
    1.49              }
    1.50          }
    1.51 -        elm = elm->next;
    1.52 +        pelm = elm;
    1.53 +        elm = pelm->next;
    1.54      }
    1.55  
    1.56      return NULL;
    1.57  }
    1.58  
    1.59 +void *ucx_map_get(UcxMap *map, UcxKey key) {
    1.60 +    return ucx_map_get_and_remove(map, key, 0);
    1.61 +}
    1.62 +
    1.63 +void *ucx_map_remove(UcxMap *map, UcxKey key) {
    1.64 +    return ucx_map_get_and_remove(map, key, 1);
    1.65 +}
    1.66 +
    1.67  UcxKey ucx_key(void *data, size_t len) {
    1.68      UcxKey key;
    1.69      key.data = data;

mercurial