f necessary */ for (i = 0; i elem = m->elems + curr; if (elem->used == used_1) { if (!strcmp(elem->key, key)) { *value = (elem->data); return HMAP_S_OK; } } curr = (curr + 1) % m->table_size; } *value = NULL; return HMAP_E_NOTFOUND; } /** * Iterate the function parameter over each element in the hashmap. The * additional void_ptr argument is passed to the function as its first * argument and the hashmap element is the second. */ int hashmap_iterate(hmap_t in, hmap_callback_func fnIterValue, void_ptr arg) { int i; hashmap_elem_t *elem; hashmap_map_t *m = (hashmap_map_t*) in; if (hashmap_size(m) <= 0) { return HMAP_E_NOTFOUND; } for (i = 0; i< m->table_size; i++) { elem = m->elems+i; if(elem->used == used_1) { int status = fnIterValue(elem->data, arg); if (status != HMAP_S_OK) { return status; } } } return HMAP_S_OK; } /** * Remove an element with that key from the map */ int hashmap_remove(hmap_t in, char* key, void_ptr *outValue){ int i, curr; hashmap_map_t* m; hashmap_elem_t *elem; /* Cast the hashmap */ m = (hashmap_map_t *) in; if (outValue) { *outValue = NULL; } /* Find key */ curr = _find_hash_index(m, key); /* Linear probing, if necessary */ for (i = 0; i elem = m->elems + curr; if (elem->used == used_1){ if (!strcmp(elem->key, key)){ /* Blank out the fields */ elem->used = unused_0; elem->key = NULL; if (outValue) { *outValue = elem->data; } elem->data = NULL; /* Reduce the size */ m->size--; return HMAP_S_OK; } } curr = (curr + 1) % m->table_size; } /* Data not found */ return HMAP_E_NOTFOUND; } /** * Deallocate the hashmap */ void hashmap_destroy(hmap_t in, hmap_callback_func fnFreeva lue, void_ptr arg){ hashmap_elem_t *elem; void_ptr data; hashmap_map_t* m = (hashmap_map_t*) in; while (m->table_size-->0) { elem = m->elems+(m->table_size); if (elem->used == used_1) { elem->used = unused_0; elem->key = NULL; data = elem->data; elem->data = NULL; if (fnFreeva lue) { fnFreeva lue(data, arg); } } } free(m->elems); free(m); } /** * Return the length of the hashmap */ int hashmap_size(hmap_t in){ hashmap_map_t* m = (hashmap_map_t *) in; if (m) { return m->size; } else { return 0; } }
[cpp] /** * main.c * * Detecting memory leaks only for windows . * Place the following snippet where leak to be tested: * #if defined(_CRTDBG_MAP_ALLOC) * _CrtDumpMemoryLeaks(); * #endif */ #if defined(WIN32) && defined(_DEBUG) #ifndef _CRTDBG_MAP_ALLOC #pragma message( __FILE__": _CRTDBG_MAP_ALLOC defined only for DEBUG on Win32." ) #define _CRTDBG_MAP_ALLOC #include #include #endif #endif #include #include #include #include "hashmap.h" typedef struct userelem_t { char key[20]; char *value; } userelem; typedef struct userdata_t { char name[20]; hmap_t map; /* userelem map */ } userdata; static int iter_elem(void* elem, void *arg) { userelem *el = (userelem *) elem; printf("key=%s; value=%s\n", el->key, el->value); return 0; } static int free_elem(void* elem, void *arg) { userelem *el = (userelem *) elem; free(el->value); free(el); return 0; } static int f |