Mon, 23 Jul 2012 15:13:19 +0200
added solaris 10 support
/* * */ #include <stdlib.h> #include <string.h> #include "map.h" UcxMap *ucx_map_new(size_t size) { UcxMap *map = (UcxMap*)malloc(sizeof(UcxMap)); if(map == NULL) { return NULL; } map->map = (UcxMapElement**)calloc(size, sizeof(UcxMapElement*)); if(map->map == NULL) { free(map); return NULL; } map->size = size; return map; } void ucx_map_free(UcxMap *map) { for (size_t n = 0 ; n < map->size ; n++) { UcxMapElement *elem = map->map[n]; if (elem != NULL) { do { UcxMapElement *next = elem->next; free(elem->key.data); free(elem); elem = next; } while (elem != NULL); } } free(map->map); free(map); } int ucx_map_put(UcxMap *map, UcxKey key, void *data) { if(key.hash == 0) { key.hash = ucx_hash((char*)key.data, key.len); } size_t slot = key.hash%map->size; UcxMapElement *elm = map->map[slot]; UcxMapElement *prev = NULL; while (elm != NULL && elm->key.hash < key.hash) { prev = elm; elm = elm->next; } if (elm == NULL || elm->key.hash != key.hash) { UcxMapElement *e = (UcxMapElement*)malloc(sizeof(UcxMapElement)); if(e == NULL) { return -1; } e->key.data = NULL; if (prev == NULL) { map->map[slot] = e; } else { prev->next = e; } e->next = elm; elm = e; } if(elm->key.data == NULL) { void *kd = malloc(key.len); if (kd == NULL) { return -1; } memcpy(kd, key.data, key.len); key.data = kd; elm->key = key; } elm->data = data; return 0; } void* ucx_map_get(UcxMap *map, UcxKey key) { if(key.hash == 0) { key.hash = ucx_hash((char*)key.data, key.len); } UcxMapElement *elm = map->map[key.hash%map->size]; while (elm != NULL && elm->key.hash <= key.hash) { if(elm->key.hash == key.hash) { int n = (key.len > elm->key.len) ? elm->key.len : key.len; if (memcmp(elm->key.data, key.data, n) == 0) { return elm->data; } } elm = elm->next; } return NULL; } UcxKey ucx_key(void *data, size_t len) { UcxKey key; key.data = data; key.len = len; key.hash = ucx_hash(data, len); return key; } int ucx_hash(char *data, size_t len) { /* murmur hash 2 */ int m = 0x5bd1e995; int r = 24; int h = 25 ^ len; int i = 0; while (len >= 4) { int k = data[i + 0] & 0xFF; k |= (data[i + 1] & 0xFF) << 8; k |= (data[i + 2] & 0xFF) << 16; k |= (data[i + 3] & 0xFF) << 24; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; i += 4; len -= 4; } switch (len) { case 3: h ^= (data[i + 2] & 0xFF) << 16; case 2: h ^= (data[i + 1] & 0xFF) << 8; case 1: h ^= (data[i + 0] & 0xFF); h *= m; } h ^= h >> 13; h *= m; h ^= h >> 15; return h; } UcxMapIterator ucx_map_iterator(UcxMap *map) { UcxMapIterator i; i.map = map; i.cur = NULL; i.index = 0; return i; } int ucx_map_iter_next(UcxMapIterator *i, void **elm) { UcxMapElement *e = i->cur; if(e == NULL) { e = i->map->map[0]; } else { e = e->next; } while(i->index < i->map->size) { if(e != NULL) { if(e->data != NULL) { i->cur = e; *elm = e->data; return 0; } e = e->next; } else { i->index++; if(i->index < i->map->size) { e = i->map->map[i->index]; } } } return 1; }