ucx/map.c

changeset 52
34f50d0bada4
parent 51
1c78cd19fb6b
child 53
e533c170bfb8
equal deleted inserted replaced
51:1c78cd19fb6b 52:34f50d0bada4
42 } 42 }
43 free(map->map); 43 free(map->map);
44 free(map); 44 free(map);
45 } 45 }
46 46
47 int ucx_map_copy(UcxMap *from, UcxMap *to, copy_func fnc, void *data) {
48 UcxMapIterator i = ucx_map_iterator(from);
49 void *value;
50 UCX_MAP_FOREACH(value, i) {
51 int ret = ucx_map_put(to, i.cur->key, fnc ? fnc(value, data) : value);
52 if(ret != 0) {
53 return 1;
54 }
55 }
56 return 0;
57 }
58
47 UcxMap *ucx_map_clone(UcxMap *map, copy_func fnc, void *data) { 59 UcxMap *ucx_map_clone(UcxMap *map, copy_func fnc, void *data) {
48 size_t bs = (map->count * 5) >> 1; 60 size_t bs = (map->count * 5) >> 1;
49 UcxMap *newmap = ucx_map_new(bs > map->size ? bs : map->size); 61 UcxMap *newmap = ucx_map_new(bs > map->size ? bs : map->size);
50 UcxMapIterator i = ucx_map_iterator(map); 62 if(newmap == NULL) {
51 void *value; 63 return NULL;
52 UCX_MAP_FOREACH(value, i) { 64 }
53 ucx_map_put(newmap, i.cur->key, fnc ? fnc(value, data) : value); 65 ucx_map_copy(map, newmap, fnc, data);
54 }
55 return newmap; 66 return newmap;
56 } 67 }
57 68
58 UcxMap *ucx_map_rehash(UcxMap *map) { 69 int ucx_map_rehash(UcxMap *map) {
59 size_t load = (map->size * 3) >> 2; 70 size_t load = (map->size * 3) >> 2;
60 if (map->count > load) { 71 if (map->count > load) {
61 UcxMap *newmap = ucx_map_clone(map, NULL, NULL); 72 UcxMap oldmap;
62 ucx_map_free(map); 73 oldmap.map = map->map;
63 return newmap; 74 oldmap.size = map->size;
64 } else { 75 oldmap.count = map->count;
65 return map; 76
66 } 77 map->size = (map->count * 5) >> 1;
78 map->map = (UcxMapElement**)calloc(map->size, sizeof(UcxMapElement*));
79 if(map->map == NULL) {
80 *map = oldmap;
81 return 1;
82 }
83 map->count = 0;
84 ucx_map_copy(&oldmap, map, NULL, NULL);
85 }
86 return 0;
67 } 87 }
68 88
69 int ucx_map_put(UcxMap *map, UcxKey key, void *data) { 89 int ucx_map_put(UcxMap *map, UcxKey key, void *data) {
70 if(key.hash == 0) { 90 if(key.hash == 0) {
71 key.hash = ucx_hash((char*)key.data, key.len); 91 key.hash = ucx_hash((char*)key.data, key.len);

mercurial