3 /* dict - a generic dictionnary, variation over the B-tree concept */
5 /* Copyright (c) 2003,2004 Martin Quinson. All rights reserved. */
7 /* This program is free software; you can redistribute it and/or modify it
8 * under the terms of the license (GNU LGPL) which comes with this package. */
13 #include "dict_private.h"
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict,xbt,
16 "Dictionaries provide the same functionnalities than hash tables");
17 /*####[ Private prototypes ]#################################################*/
19 /*####[ Code ]###############################################################*/
23 * \return pointer to the destination
24 * \see xbt_dict_new_ext(), xbt_dict_free()
26 * Creates and initialize a new dictionnary with a default hashtable size.
28 xbt_dict_t xbt_dict_new(void) {
29 return xbt_dict_new_ext(256);
33 * \brief Create a new dictionary with the specified hashtable size
34 * \param hashsize the hashtable size
35 * \return a pointer to the created object
36 * \see xbt_dict_new(), xbt_dict_free()
38 xbt_dict_t xbt_dict_new_ext(int hashsize) {
40 xbt_dict_t dict = xbt_new0(s_xbt_dict_t, 1);
41 dict->table_size = hashsize;
42 dict->table = xbt_new0(xbt_dictelm_t, dict->table_size);
44 for (i = 0; i < hashsize; i++) {
45 dict->table[i] = NULL;
53 * \param dict the dictionnary to be freed
55 * Frees a dictionary with all the data
57 void xbt_dict_free(xbt_dict_t *dict) {
59 xbt_dictelm_t current, previous;
60 if (dict != NULL && *dict != NULL) {
61 for (i = 0; i < (*dict)->table_size; i++) {
62 current = (*dict)->table[i];
63 while (current != NULL) {
65 current = current->next;
66 xbt_dictelm_free(previous);
69 xbt_free((*dict)->table);
76 * \brief Change the hashtable size
77 * \param dict a dictionary
78 * \param hashsize the new hashtable size
80 * Change the hashtable size is a long operation, so it's better
81 * to use xbt_dict_new_ext or to call xbt_dict_hashsize_set when
82 * the dictionary is empty.
84 void xbt_dict_hashsize_set(xbt_dict_t dict, int hashsize) {
85 xbt_dict_t new_dict = xbt_dict_new_ext(hashsize);
86 xbt_dictelm_t element, next;
89 for (i = 0; i < dict->table_size; i++) {
90 element = dict->table[i];
91 while (element != NULL) {
92 next = element->next; /* save the next because it will be lost */
93 xbt_dict_add_element(new_dict, element); /* no new xbt_dictelm_t is mallocated */
98 xbt_free(dict->table);
99 dict->table = new_dict->table;
100 dict->table_size = hashsize;
105 * Returns the hash code of a string.
107 unsigned int xbt_dict_hash(const char *str) {
108 /* fast implementation of djb2 algorithm */
109 unsigned int hash = 5381;
112 while ((c = *str++)) {
113 hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
120 * \brief Add data to the dict (arbitrary key)
121 * \param dict the container
122 * \param key the key to set the new data
123 * \param key_len the size of the \a key
124 * \param data the data to add in the dict
125 * \param free_ctn function to call with (\a key as argument) when
126 * \a key is removed from the dictionnary
128 * Set the \a data in the structure under the \a key, which can be any kind
129 * of data, as long as its length is provided in \a key_len.
131 void xbt_dict_set_ext(xbt_dict_t dict,
135 void_f_pvoid_t *free_ctn) {
138 unsigned int hash_code = xbt_dict_hash(key) % dict->table_size;
139 xbt_dictelm_t current, previous = NULL;
141 current = dict->table[hash_code];
142 while (current != NULL &&
143 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
145 current = current->next;
148 if (current == NULL) {
149 /* this key doesn't exist yet */
150 current = xbt_dictelm_new(key, key_len, data, free_ctn, NULL);
151 if (previous == NULL) {
152 dict->table[hash_code] = current;
155 previous->next = current;
159 /* there is already an element with the same key: we overwrite it */
160 if (current->content != NULL && current->free_f != NULL) {
161 current->free_f(current->content);
163 current->content = data;
164 current->free_f = free_ctn;
169 * \brief Add data to the dict (null-terminated key)
171 * \param dict the head of the dict
172 * \param key the key to set the new data
173 * \param data the data to add in the dict
174 * \param free_ctn function to call with (\a key as argument) when
175 * \a key is removed from the dictionnary
177 * set the \a data in the structure under the \a key, which is a
178 * null terminated string.
180 void xbt_dict_set(xbt_dict_t dict,
183 void_f_pvoid_t *free_ctn) {
187 xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn);
191 * \brief Retrieve data from the dict (arbitrary key)
193 * \param dict the dealer of data
194 * \param key the key to find data
195 * \param key_len the size of the \a key
196 * \return the data that we are looking for
198 * Search the given \a key. Throws not_found_error when not found.
200 void *xbt_dict_get_ext(xbt_dict_t dict,
205 unsigned int hash_code = xbt_dict_hash(key) % dict->table_size;
206 xbt_dictelm_t current;
208 current = dict->table[hash_code];
209 while (current != NULL &&
210 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
211 current = current->next;
214 if (current == NULL) {
215 THROW2(not_found_error, 0, "key %.*s not found", key_len, key);
218 return current->content;
222 * \brief Retrieve data from the dict (null-terminated key)
224 * \param dict the dealer of data
225 * \param key the key to find data
226 * \return the data that we are looking for
228 * Search the given \a key. Throws not_found_error when not found.
229 * Check xbt_dict_get_or_null() for a version returning NULL without exception when
232 void *xbt_dict_get(xbt_dict_t dict,
236 return xbt_dict_get_ext(dict, key, strlen(key));
240 * \brief like xbt_dict_get(), but returning NULL when not found
242 void *xbt_dict_get_or_null(xbt_dict_t dict,
247 result = xbt_dict_get(dict, key);
249 if (e.category != not_found_error)
259 * \brief Remove data from the dict (arbitrary key)
261 * \param dict the trash can
262 * \param key the key of the data to be removed
263 * \param key_len the size of the \a key
265 * Remove the entry associated with the given \a key (throws not_found)
267 void xbt_dict_remove_ext(xbt_dict_t dict,
272 unsigned int hash_code = xbt_dict_hash(key) % dict->table_size;
273 xbt_dictelm_t current, previous = NULL;
275 current = dict->table[hash_code];
276 while (current != NULL &&
277 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
278 previous = current; /* save the previous node */
279 current = current->next;
282 if (current == NULL) {
283 THROW2(not_found_error, 0, "key %.*s not found", key_len, key);
286 if (previous != NULL) {
287 xbt_assert0(previous->next == current, "previous-next != current");
288 previous->next = current->next;
291 dict->table[hash_code] = current->next;
294 xbt_dictelm_free(current);
298 * \brief Remove data from the dict (null-terminated key)
300 * \param dict the head of the dict
301 * \param key the key of the data to be removed
303 * Remove the entry associated with the given \a key
305 void xbt_dict_remove(xbt_dict_t dict,
308 THROW1(arg_error, 0, "Asked to remove key %s from NULL dict", key);
310 xbt_dict_remove_ext(dict, key, strlen(key));
314 * Add an already mallocated element to a dictionary.
316 void xbt_dict_add_element(xbt_dict_t dict, xbt_dictelm_t element) {
319 int hashcode = xbt_dict_hash(element->key) % dict->table_size;
320 element->next = dict->table[hashcode];
321 dict->table[hashcode] = element;
325 * \brief Outputs the content of the structure (debuging purpose)
327 * \param dict the exibitionist
328 * \param output a function to dump each data in the tree
330 * Ouputs the content of the structure. (for debuging purpose). \a ouput is a
331 * function to output the data. If NULL, data won't be displayed.
334 void xbt_dict_dump(xbt_dict_t dict,
335 void_f_pvoid_t *output) {
337 xbt_dictelm_t element;
338 printf("Dict %p:\n", dict);
340 for (i = 0; i < dict->table_size; i++) {
341 element = dict->table[i];
342 while (element != NULL) {
343 printf("%s -> ", element->key);
344 if (output != NULL) {
345 output(element->content);
348 element = element->next;
357 #include "portable.h"
359 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
360 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
362 XBT_TEST_SUITE("dict","Dict data container");
364 static void print_str(void *str) {
365 printf("%s",(char*)PRINTF_STR(str));
368 static void debuged_add(xbt_dict_t head,const char*key)
370 char *data=xbt_strdup(key);
372 xbt_test_log1("Add %s",PRINTF_STR(key));
374 xbt_dict_set(head,key,data,&free);
375 if (XBT_LOG_ISENABLED(xbt_dict,xbt_log_priority_debug)) {
376 xbt_dict_dump(head,(void (*)(void*))&printf);
381 static void fill(xbt_dict_t *head) {
382 xbt_test_add0("Fill in the dictionnary");
384 *head = xbt_dict_new();
385 debuged_add(*head,"12");
386 debuged_add(*head,"12a");
387 debuged_add(*head,"12b");
388 debuged_add(*head,"123");
389 debuged_add(*head,"123456");
390 /* Child becomes child of what to add */
391 debuged_add(*head,"1234");
392 /* Need of common ancestor */
393 debuged_add(*head,"123457");
396 static void search(xbt_dict_t head,const char*key) {
399 xbt_test_add1("Search %s",key);
400 data=xbt_dict_get(head,key);
401 xbt_test_log1("Found %s",(char *)data);
403 xbt_test_assert0(!strcmp((char*)data,key),"Key and data do not match");
406 static void debuged_remove(xbt_dict_t head,const char*key) {
408 xbt_test_add1("Remove '%s'",PRINTF_STR(key));
409 xbt_dict_remove(head,key);
410 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
414 static void traverse(xbt_dict_t head) {
415 xbt_dict_cursor_t cursor=NULL;
419 xbt_dict_foreach(head,cursor,key,data) {
420 xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data));
421 xbt_test_assert2(!data || !strcmp(key,data),
422 "Key(%s) != value(%s). Abording\n",key,data);
426 static void search_not_found(xbt_dict_t head, const char *data) {
429 xbt_test_add1("Search %s (expected not to be found)",data);
432 data = xbt_dict_get(head,"Can't be found");
433 THROW1(unknown_error,0,"Found something which shouldn't be there (%s)",data);
435 if (e.category != not_found_error)
436 xbt_test_exception(e);
442 xbt_dict_t head=NULL;
446 XBT_TEST_UNIT("basic",test_dict_basic,"Basic usage: change, retrieve, traverse"){
447 xbt_test_add0("Traversal the empty dictionnary");
450 xbt_test_add0("Traverse the full dictionnary");
456 xbt_test_add0("Free the dictionnary (twice)");
457 xbt_dict_free(&head);
458 xbt_dict_free(&head);
462 xbt_test_add0("Change 123 to 'Changed 123'");
463 xbt_dict_set(head,"123",strdup("Changed 123"),&free);
465 xbt_test_add0("Change 123 back to '123'");
466 xbt_dict_set(head,"123",strdup("123"),&free);
468 xbt_test_add0("Change 12a to 'Dummy 12a'");
469 xbt_dict_set(head,"12a",strdup("Dummy 12a"),&free);
471 xbt_test_add0("Change 12a to '12a'");
472 xbt_dict_set(head,"12a",strdup("12a"),&free);
474 xbt_test_add0("Traverse the resulting dictionnary");
478 xbt_test_add0("Search 123");
479 data = xbt_dict_get(head,"123");
480 xbt_test_assert(data);
481 xbt_test_assert(!strcmp("123",data));
483 search_not_found(head,"Can't be found");
484 search_not_found(head,"123 Can't be found");
485 search_not_found(head,"12345678 NOT");
490 search(head,"123456");
492 search(head,"123457");
494 xbt_test_add0("Traverse the resulting dictionnary");
497 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
499 xbt_test_add0("Free the dictionnary twice");
500 xbt_dict_free(&head);
501 xbt_dict_free(&head);
503 xbt_test_add0("Traverse the resulting dictionnary");
507 XBT_TEST_UNIT("remove",test_dict_remove,"Removing some values"){
509 xbt_test_add0("Remove non existing data");
511 debuged_remove(head,"Does not exist");
513 if (e.category != not_found_error)
514 xbt_test_exception(e);
519 xbt_dict_free(&head);
521 xbt_test_add0("Remove data from the NULL dict");
523 debuged_remove(head,"12345");
525 if (e.category != arg_error)
526 xbt_test_exception(e);
530 xbt_test_add0("Remove each data manually (traversing the resulting dictionnary each time)");
532 debuged_remove(head,"12a"); traverse(head);
533 debuged_remove(head,"12b"); traverse(head);
534 debuged_remove(head,"12"); traverse(head);
535 debuged_remove(head,"123456"); traverse(head);
537 debuged_remove(head,"12346");
539 if (e.category != not_found_error)
540 xbt_test_exception(e);
544 debuged_remove(head,"1234"); traverse(head);
545 debuged_remove(head,"123457"); traverse(head);
546 debuged_remove(head,"123"); traverse(head);
548 debuged_remove(head,"12346");
550 if (e.category != not_found_error)
551 xbt_test_exception(e);
555 xbt_test_add0("Free the dictionnary twice");
556 xbt_dict_free(&head);
557 xbt_dict_free(&head);
560 XBT_TEST_UNIT("nulldata",test_dict_nulldata,"NULL data management"){
563 xbt_test_add0("Store NULL under 'null'");
564 xbt_dict_set(head,"null",NULL,NULL);
567 xbt_test_add0("Check whether I see it while traversing...");
569 xbt_dict_cursor_t cursor=NULL;
573 xbt_dict_foreach(head,cursor,key,data) {
574 xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data));
575 if (!strcmp(key,"null"))
578 xbt_test_assert0(found,"the key 'null', associated to NULL is not found");
580 xbt_dict_free(&head);
584 #define SIZEOFKEY 1024
585 static int countelems(xbt_dict_t head) {
586 xbt_dict_cursor_t cursor;
591 xbt_dict_foreach(head,cursor,key,data) {
597 XBT_TEST_UNIT("crash",test_dict_crash,"Crash test"){
598 xbt_dict_t head=NULL;
603 srand((unsigned int)time(NULL));
605 xbt_test_add0("CRASH test");
606 xbt_test_log0("Fill the struct, count its elems and frees the structure (x10)");
607 xbt_test_log1("using 1000 elements with %d chars long randomized keys.",SIZEOFKEY);
611 // if (i%10) printf("."); else printf("%d",i/10); fflush(stdout);
613 for (j=0;j<1000;j++) {
614 key=xbt_malloc(SIZEOFKEY);
616 for (k=0;k<SIZEOFKEY-1;k++)
617 key[k]=rand() % ('z' - 'a') + 'a';
619 /* printf("[%d %s]\n",j,key); */
620 xbt_dict_set(head,key,key,&free);
622 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
623 nb = countelems(head);
624 xbt_test_assert1(nb == 1000,"found %d elements instead of 1000",nb);
626 xbt_dict_free(&head);
627 xbt_dict_free(&head);
632 xbt_test_add1("Fill %d elements, with keys being the number of element",NB_ELM);
633 for (j=0;j<NB_ELM;j++) {
634 // if (!(j%1000)) { printf("."); fflush(stdout); }
636 key = xbt_malloc(10);
639 xbt_dict_set(head,key,key,&free);
642 xbt_test_add0("Count the elements (retrieving the key and data for each)");
643 i = countelems(head);
644 xbt_test_log1("There is %d elements",i);
646 xbt_test_add1("Search my %d elements 20 times",NB_ELM);
649 // if (i%10) printf("."); else printf("%d",i/10); fflush(stdout);
650 for (j=0;j<NB_ELM;j++) {
653 data = xbt_dict_get(head,key);
654 xbt_test_assert2(!strcmp(key,(char*)data),
655 "key=%s != data=%s\n",key,(char*)data);
660 xbt_test_add1("Remove my %d elements",NB_ELM);
662 for (j=0;j<NB_ELM;j++) {
663 //if (!(j%10000)) printf("."); fflush(stdout);
666 xbt_dict_remove(head,key);
671 xbt_test_add0("Free the structure (twice)");
672 xbt_dict_free(&head);
673 xbt_dict_free(&head);
676 static void str_free(void *s) {
681 XBT_TEST_UNIT("multicrash",test_dict_multicrash,"Multi-dict crash test"){
684 #define NB_ELM 100 /*00*/
687 #define NB_TEST 20 /*20*/
690 xbt_dict_t mdict = NULL;
692 xbt_dynar_t keys = xbt_dynar_new(sizeof(char*),str_free);
697 xbt_test_add0("Generic multicache CRASH test");
698 xbt_test_log4(" Fill the struct and frees it %d times, using %d elements, "
699 "depth of multicache=%d, key size=%d",
700 NB_TEST,NB_ELM,DEPTH,KEY_SIZE);
702 for (l=0 ; l<DEPTH ; l++) {
703 key=xbt_malloc(KEY_SIZE);
704 xbt_dynar_push(keys,&key);
707 for (i=0;i<NB_TEST;i++) {
708 mdict = xbt_dict_new();
709 VERB1("mdict=%p",mdict);
711 printf("Test %d\n",i);
712 /* else if (i%10) printf("."); else printf("%d",i/10);*/
714 for (j=0;j<NB_ELM;j++) {
715 if (verbose>0) printf (" Add {");
717 for (l=0 ; l<DEPTH ; l++) {
718 key=*(char**)xbt_dynar_get_ptr(keys,l);
720 for (k=0;k<KEY_SIZE-1;k++)
721 key[k]=rand() % ('z' - 'a') + 'a';
725 if (verbose>0) printf("%p=%s %s ",key, key,(l<DEPTH-1?";":"}"));
727 if (verbose>0) printf("in multitree %p.\n",mdict);
729 xbt_multidict_set(mdict,keys,xbt_strdup(key),free);
731 data = xbt_multidict_get(mdict,keys);
733 xbt_test_assert2(data && !strcmp((char*)data,key),
734 "Retrieved value (%s) does not match the entrered one (%s)\n",
737 xbt_dict_free(&mdict);
740 xbt_dynar_free(&keys);
743 xbt_dict_dump(mdict,&xbt_dict_print);*/
745 xbt_dict_free(&mdict);
746 xbt_dynar_free(&keys);
749 #endif /* SIMGRID_TEST */