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 "xbt/mallocator.h"
14 #include "xbt_modinter.h"
15 #include "dict_private.h"
17 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict,xbt,
18 "Dictionaries provide the same functionnalities than hash tables");
19 /*####[ Private prototypes ]#################################################*/
21 static xbt_mallocator_t dict_mallocator = NULL;
22 static void* dict_mallocator_new_f(void);
23 static void dict_mallocator_free_f(void* dict);
24 static void dict_mallocator_reset_f(void* dict);
27 /*####[ Code ]###############################################################*/
31 * \return pointer to the destination
32 * \see xbt_dict_new_ext(), xbt_dict_free()
34 * Creates and initialize a new dictionnary with a default hashtable size.
36 xbt_dict_t xbt_dict_new(void) {
37 return xbt_dict_new_ext(256);
41 * \brief Create a new dictionary with the specified hashtable size
42 * \param hashsize the hashtable size
43 * \return a pointer to the created object
44 * \see xbt_dict_new(), xbt_dict_free()
46 xbt_dict_t xbt_dict_new_ext(int hashsize) {
49 if (dict_mallocator == NULL) {
51 dict_mallocator = xbt_mallocator_new(256,
52 dict_mallocator_new_f,
53 dict_mallocator_free_f,
54 dict_mallocator_reset_f);
55 dict_elm_mallocator = xbt_mallocator_new(256,
56 dict_elm_mallocator_new_f,
57 dict_elm_mallocator_free_f,
58 dict_elm_mallocator_reset_f);
61 dict = xbt_mallocator_get(dict_mallocator);
62 dict->table_size = hashsize;
63 dict->table = xbt_new0(xbt_dictelm_t, dict->table_size);
71 * \param dict the dictionnary to be freed
73 * Frees a dictionary with all the data
75 void xbt_dict_free(xbt_dict_t *dict) {
77 xbt_dictelm_t current, previous;
81 if (dict != NULL && *dict != NULL) {
82 table_size = (*dict)->table_size;
83 table = (*dict)->table;
84 for (i = 0; i < table_size; i++) {
86 while (current != NULL) {
88 current = current->next;
89 xbt_dictelm_free(previous);
93 xbt_mallocator_release(dict_mallocator, *dict);
99 * \brief Change the hashtable size
100 * \param dict a dictionary
101 * \param hashsize the new hashtable size
103 * Change the hashtable size is a long operation, so it's better
104 * to use xbt_dict_new_ext or to call xbt_dict_hashsize_set when
105 * the dictionary is empty.
107 void xbt_dict_hashsize_set(xbt_dict_t dict, int hashsize) {
108 xbt_dict_t new_dict = xbt_dict_new_ext(hashsize);
109 xbt_dictelm_t element, next;
112 for (i = 0; i < dict->table_size; i++) {
113 element = dict->table[i];
114 while (element != NULL) {
115 next = element->next; /* save the next because it will be lost */
116 xbt_dict_add_element(new_dict, element); /* no new xbt_dictelm_t is mallocated */
121 xbt_free(dict->table);
122 dict->table = new_dict->table;
123 dict->table_size = hashsize;
128 * Returns the hash code of a string.
130 static unsigned int xbt_dict_hash_ext(const char *str, int str_len) {
131 /* fast implementation of djb2 algorithm */
132 unsigned int hash = 5381;
137 hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
143 static unsigned int xbt_dict_hash(const char *str) {
144 /* fast implementation of djb2 algorithm */
145 unsigned int hash = 5381;
148 while ( (c = *str++) ) {
149 hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
156 * \brief Add data to the dict (arbitrary key)
157 * \param dict the container
158 * \param key the key to set the new data
159 * \param key_len the size of the \a key
160 * \param data the data to add in the dict
161 * \param free_ctn function to call with (\a key as argument) when
162 * \a key is removed from the dictionnary
164 * Set the \a data in the structure under the \a key, which can be any kind
165 * of data, as long as its length is provided in \a key_len.
167 void xbt_dict_set_ext(xbt_dict_t dict,
171 void_f_pvoid_t *free_ctn) {
174 unsigned int hash_code = xbt_dict_hash_ext(key,key_len) % dict->table_size;
175 xbt_dictelm_t current, previous = NULL;
177 current = dict->table[hash_code];
178 while (current != NULL &&
179 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
181 current = current->next;
184 if (current == NULL) {
185 /* this key doesn't exist yet */
186 current = xbt_dictelm_new(key, key_len, data, free_ctn, NULL);
187 if (previous == NULL) {
188 dict->table[hash_code] = current;
191 previous->next = current;
196 /* there is already an element with the same key: we overwrite it */
197 if (current->content != NULL && current->free_f != NULL) {
198 current->free_f(current->content);
200 current->content = data;
201 current->free_f = free_ctn;
206 * \brief Add data to the dict (null-terminated key)
208 * \param dict the dict
209 * \param key the key to set the new data
210 * \param data the data to add in the dict
211 * \param free_ctn function to call with (\a key as argument) when
212 * \a key is removed from the dictionnary
214 * set the \a data in the structure under the \a key, which is a
215 * null terminated string.
217 void xbt_dict_set(xbt_dict_t dict,
220 void_f_pvoid_t *free_ctn) {
224 xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn);
228 * \brief Retrieve data from the dict (arbitrary key)
230 * \param dict the dealer of data
231 * \param key the key to find data
232 * \param key_len the size of the \a key
233 * \return the data that we are looking for
235 * Search the given \a key. Throws not_found_error when not found.
237 void *xbt_dict_get_ext(xbt_dict_t dict,
242 unsigned int hash_code = xbt_dict_hash_ext(key,key_len) % dict->table_size;
243 xbt_dictelm_t current;
245 current = dict->table[hash_code];
246 while (current != NULL &&
247 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
248 current = current->next;
251 if (current == NULL) {
252 THROW2(not_found_error, 0, "key %.*s not found", key_len, key);
255 return current->content;
259 * \brief Retrieve data from the dict (null-terminated key)
261 * \param dict the dealer of data
262 * \param key the key to find data
263 * \return the data that we are looking for
265 * Search the given \a key. Throws not_found_error when not found.
266 * Check xbt_dict_get_or_null() for a version returning NULL without exception when
269 void *xbt_dict_get(xbt_dict_t dict,
273 unsigned int hash_code = xbt_dict_hash(key) % dict->table_size;
274 xbt_dictelm_t current;
276 current = dict->table[hash_code];
277 while (current != NULL && (strcmp(key, current->key))) {
278 current = current->next;
281 if (current == NULL) {
282 THROW1(not_found_error, 0, "key %s not found", key);
285 return current->content;
289 * \brief like xbt_dict_get(), but returning NULL when not found
291 void *xbt_dict_get_or_null(xbt_dict_t dict,
296 result = xbt_dict_get(dict, key);
298 if (e.category != not_found_error)
308 * \brief Remove data from the dict (arbitrary key)
310 * \param dict the trash can
311 * \param key the key of the data to be removed
312 * \param key_len the size of the \a key
314 * Remove the entry associated with the given \a key (throws not_found)
316 void xbt_dict_remove_ext(xbt_dict_t dict,
321 unsigned int hash_code = xbt_dict_hash_ext(key,key_len) % dict->table_size;
322 xbt_dictelm_t current, previous = NULL;
324 current = dict->table[hash_code];
325 while (current != NULL &&
326 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
327 previous = current; /* save the previous node */
328 current = current->next;
331 if (current == NULL) {
332 THROW2(not_found_error, 0, "key %.*s not found", key_len, key);
335 if (previous != NULL) {
336 xbt_assert0(previous->next == current, "previous-next != current");
337 previous->next = current->next;
340 dict->table[hash_code] = current->next;
343 xbt_dictelm_free(current);
348 * \brief Remove data from the dict (null-terminated key)
350 * \param dict the dict
351 * \param key the key of the data to be removed
353 * Remove the entry associated with the given \a key
355 void xbt_dict_remove(xbt_dict_t dict,
359 xbt_dict_remove_ext(dict, key, strlen(key));
363 * \brief Remove all data from the dict
364 * \param dict the dict
366 void xbt_dict_reset(xbt_dict_t dict) {
370 xbt_dictelm_t current, previous = NULL;
372 if (dict->count == 0)
375 for (i = 0; i < dict->table_size; i++) {
376 current = dict->table[i];
377 while (current != NULL) {
379 current = current->next;
380 xbt_dictelm_free(previous);
382 dict->table[i] = NULL;
389 * \brief Return the number of elements in the dict.
390 * \param dict a dictionary
392 int xbt_dict_length(xbt_dict_t dict) {
399 * Add an already mallocated element to a dictionary.
401 void xbt_dict_add_element(xbt_dict_t dict, xbt_dictelm_t element) {
404 int hashcode = xbt_dict_hash_ext(element->key,element->key_len) % dict->table_size;
405 element->next = dict->table[hashcode];
406 dict->table[hashcode] = element;
410 * \brief Outputs the content of the structure (debuging purpose)
412 * \param dict the exibitionist
413 * \param output a function to dump each data in the tree
415 * Ouputs the content of the structure. (for debuging purpose). \a ouput is a
416 * function to output the data. If NULL, data won't be displayed.
419 void xbt_dict_dump(xbt_dict_t dict,
420 void_f_pvoid_t *output) {
422 xbt_dictelm_t element;
423 printf("Dict %p:\n", dict);
425 for (i = 0; i < dict->table_size; i++) {
426 element = dict->table[i];
427 while (element != NULL) {
428 printf("%s -> ", element->key);
429 if (output != NULL) {
430 output(element->content);
433 element = element->next;
440 * Destroy the dict mallocators.
441 * This is an internal XBT function called by xbt_exit().
443 void xbt_dict_exit(void) {
444 if (dict_mallocator != NULL) {
445 xbt_mallocator_free(dict_mallocator);
446 xbt_mallocator_free(dict_elm_mallocator);
450 static void* dict_mallocator_new_f(void) {
451 return xbt_new(s_xbt_dict_t, 1);
454 static void dict_mallocator_free_f(void* dict) {
458 static void dict_mallocator_reset_f(void* dict) {
459 /* nothing to do because all fields are
460 * initialized in xbt_dict_new
467 #include "portable.h"
469 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
470 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
472 XBT_TEST_SUITE("dict","Dict data container");
474 static void print_str(void *str) {
475 printf("%s",(char*)PRINTF_STR(str));
478 static void debuged_add_ext(xbt_dict_t head,const char*key,const char*data_to_fill) {
479 char *data=xbt_strdup(data_to_fill);
481 xbt_test_log2("Add %s under %s",PRINTF_STR(data_to_fill),PRINTF_STR(key));
483 xbt_dict_set(head,key,data,&free);
484 if (XBT_LOG_ISENABLED(xbt_dict,xbt_log_priority_debug)) {
485 xbt_dict_dump(head,(void (*)(void*))&printf);
489 static void debuged_add(xbt_dict_t head,const char*key) {
490 debuged_add_ext(head,key,key);
493 static void fill(xbt_dict_t *head) {
494 xbt_test_add0("Fill in the dictionnary");
496 *head = xbt_dict_new();
497 debuged_add(*head,"12");
498 debuged_add(*head,"12a");
499 debuged_add(*head,"12b");
500 debuged_add(*head,"123");
501 debuged_add(*head,"123456");
502 /* Child becomes child of what to add */
503 debuged_add(*head,"1234");
504 /* Need of common ancestor */
505 debuged_add(*head,"123457");
509 static void search_ext(xbt_dict_t head,const char*key, const char *data) {
512 xbt_test_add1("Search %s",key);
513 found=xbt_dict_get(head,key);
514 xbt_test_log1("Found %s",(char *)found);
516 xbt_test_assert1(found,"data do not match expectations: found NULL while searching for %s",data);
518 xbt_test_assert2(!strcmp((char*)data,found),"data do not match expectations: found %s while searching for %s", (char*)found, data);
521 static void search(xbt_dict_t head,const char*key) {
522 search_ext(head,key,key);
525 static void debuged_remove(xbt_dict_t head,const char*key) {
527 xbt_test_add1("Remove '%s'",PRINTF_STR(key));
528 xbt_dict_remove(head,key);
529 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
533 static void traverse(xbt_dict_t head) {
534 xbt_dict_cursor_t cursor=NULL;
538 xbt_dict_foreach(head,cursor,key,data) {
539 xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data));
540 xbt_test_assert2(!data || !strcmp(key,data),
541 "Key(%s) != value(%s). Abording\n",key,data);
545 static void search_not_found(xbt_dict_t head, const char *data) {
549 xbt_test_add1("Search %s (expected not to be found)",data);
552 data = xbt_dict_get(head, data);
553 THROW1(unknown_error,0,"Found something which shouldn't be there (%s)",data);
555 if (e.category != not_found_error)
556 xbt_test_exception(e);
560 xbt_test_assert0(ok,"Exception not raised");
563 static void count(xbt_dict_t dict, int length) {
564 xbt_test_add1("Count elements (expecting %d)", length);
565 xbt_test_assert2(xbt_dict_length(dict) == length, "Length(%d) != %d.", xbt_dict_length(dict), length);
569 xbt_dict_t head=NULL;
573 XBT_TEST_UNIT("basic",test_dict_basic,"Basic usage: change, retrieve, traverse"){
574 xbt_test_add0("Traversal the null dictionnary");
577 xbt_test_add0("Traversal and search the empty dictionnary");
578 head = xbt_dict_new();
581 debuged_remove(head,"12346");
583 if (e.category != not_found_error)
584 xbt_test_exception(e);
587 xbt_dict_free(&head);
589 xbt_test_add0("Traverse the full dictionnary");
593 debuged_add_ext(head,"toto","tutu");
594 search_ext(head,"toto","tutu");
595 debuged_remove(head,"toto");
600 xbt_test_add0("Free the dictionnary (twice)");
601 xbt_dict_free(&head);
602 xbt_dict_free(&head);
607 xbt_test_add0("Change 123 to 'Changed 123'");
608 xbt_dict_set(head,"123",strdup("Changed 123"),&free);
611 xbt_test_add0("Change 123 back to '123'");
612 xbt_dict_set(head,"123",strdup("123"),&free);
615 xbt_test_add0("Change 12a to 'Dummy 12a'");
616 xbt_dict_set(head,"12a",strdup("Dummy 12a"),&free);
619 xbt_test_add0("Change 12a to '12a'");
620 xbt_dict_set(head,"12a",strdup("12a"),&free);
623 xbt_test_add0("Traverse the resulting dictionnary");
627 xbt_test_add0("Search 123");
628 data = xbt_dict_get(head,"123");
629 xbt_test_assert(data);
630 xbt_test_assert(!strcmp("123",data));
632 search_not_found(head,"Can't be found");
633 search_not_found(head,"123 Can't be found");
634 search_not_found(head,"12345678 NOT");
639 search(head,"123456");
641 search(head,"123457");
643 xbt_test_add0("Traverse the resulting dictionnary");
646 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
648 xbt_test_add0("Free the dictionnary twice");
649 xbt_dict_free(&head);
650 xbt_dict_free(&head);
652 xbt_test_add0("Traverse the resulting dictionnary");
656 XBT_TEST_UNIT("remove",test_dict_remove,"Removing some values"){
659 xbt_test_add0("Remove non existing data");
661 debuged_remove(head,"Does not exist");
663 if (e.category != not_found_error)
664 xbt_test_exception(e);
669 xbt_dict_free(&head);
671 xbt_test_add0("Remove each data manually (traversing the resulting dictionnary each time)");
673 debuged_remove(head,"12a"); traverse(head);
675 debuged_remove(head,"12b"); traverse(head);
677 debuged_remove(head,"12"); traverse(head);
679 debuged_remove(head,"123456"); traverse(head);
682 debuged_remove(head,"12346");
684 if (e.category != not_found_error)
685 xbt_test_exception(e);
689 debuged_remove(head,"1234"); traverse(head);
690 debuged_remove(head,"123457"); traverse(head);
691 debuged_remove(head,"123"); traverse(head);
693 debuged_remove(head,"12346");
695 if (e.category != not_found_error)
696 xbt_test_exception(e);
700 xbt_test_add0("Remove all values");
701 xbt_dict_free(&head);
703 xbt_dict_reset(head);
707 xbt_test_add0("Free the dictionnary twice");
708 xbt_dict_free(&head);
709 xbt_dict_free(&head);
712 XBT_TEST_UNIT("nulldata",test_dict_nulldata,"NULL data management"){
715 xbt_test_add0("Store NULL under 'null'");
716 xbt_dict_set(head,"null",NULL,NULL);
717 search_ext(head,"null",NULL);
719 xbt_test_add0("Check whether I see it while traversing...");
721 xbt_dict_cursor_t cursor=NULL;
725 xbt_dict_foreach(head,cursor,key,data) {
726 xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data));
727 if (!strcmp(key,"null"))
730 xbt_test_assert0(found,"the key 'null', associated to NULL is not found");
732 xbt_dict_free(&head);
736 #define SIZEOFKEY 1024
737 static int countelems(xbt_dict_t head) {
738 xbt_dict_cursor_t cursor;
743 xbt_dict_foreach(head,cursor,key,data) {
749 XBT_TEST_UNIT("crash",test_dict_crash,"Crash test"){
750 xbt_dict_t head=NULL;
755 srand((unsigned int)time(NULL));
757 xbt_test_add0("CRASH test");
758 xbt_test_log0("Fill the struct, count its elems and frees the structure (x10)");
759 xbt_test_log1("using 1000 elements with %d chars long randomized keys.",SIZEOFKEY);
763 /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
765 for (j=0;j<1000;j++) {
766 key=xbt_malloc(SIZEOFKEY);
768 for (k=0;k<SIZEOFKEY-1;k++)
769 key[k]=rand() % ('z' - 'a') + 'a';
771 /* printf("[%d %s]\n",j,key); */
772 xbt_dict_set(head,key,key,&free);
774 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
775 nb = countelems(head);
776 xbt_test_assert1(nb == 1000,"found %d elements instead of 1000",nb);
778 xbt_dict_free(&head);
779 xbt_dict_free(&head);
784 xbt_test_add1("Fill %d elements, with keys being the number of element",NB_ELM);
785 for (j=0;j<NB_ELM;j++) {
786 /* if (!(j%1000)) { printf("."); fflush(stdout); } */
788 key = xbt_malloc(10);
791 xbt_dict_set(head,key,key,&free);
794 xbt_test_add0("Count the elements (retrieving the key and data for each)");
795 i = countelems(head);
796 xbt_test_log1("There is %d elements",i);
798 xbt_test_add1("Search my %d elements 20 times",NB_ELM);
801 /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
802 for (j=0;j<NB_ELM;j++) {
805 data = xbt_dict_get(head,key);
806 xbt_test_assert2(!strcmp(key,(char*)data),
807 "key=%s != data=%s\n",key,(char*)data);
812 xbt_test_add1("Remove my %d elements",NB_ELM);
814 for (j=0;j<NB_ELM;j++) {
815 /* if (!(j%10000)) printf("."); fflush(stdout); */
818 xbt_dict_remove(head,key);
823 xbt_test_add0("Free the structure (twice)");
824 xbt_dict_free(&head);
825 xbt_dict_free(&head);
828 static void str_free(void *s) {
833 XBT_TEST_UNIT("multicrash",test_dict_multicrash,"Multi-dict crash test"){
836 #define NB_ELM 100 /*00*/
839 #define NB_TEST 20 /*20*/
842 xbt_dict_t mdict = NULL;
844 xbt_dynar_t keys = xbt_dynar_new(sizeof(char*),str_free);
849 xbt_test_add0("Generic multicache CRASH test");
850 xbt_test_log4(" Fill the struct and frees it %d times, using %d elements, "
851 "depth of multicache=%d, key size=%d",
852 NB_TEST,NB_ELM,DEPTH,KEY_SIZE);
854 for (l=0 ; l<DEPTH ; l++) {
855 key=xbt_malloc(KEY_SIZE);
856 xbt_dynar_push(keys,&key);
859 for (i=0;i<NB_TEST;i++) {
860 mdict = xbt_dict_new();
861 VERB1("mdict=%p",mdict);
863 printf("Test %d\n",i);
864 /* else if (i%10) printf("."); else printf("%d",i/10);*/
866 for (j=0;j<NB_ELM;j++) {
867 if (verbose>0) printf (" Add {");
869 for (l=0 ; l<DEPTH ; l++) {
870 key=*(char**)xbt_dynar_get_ptr(keys,l);
872 for (k=0;k<KEY_SIZE-1;k++)
873 key[k]=rand() % ('z' - 'a') + 'a';
877 if (verbose>0) printf("%p=%s %s ",key, key,(l<DEPTH-1?";":"}"));
879 if (verbose>0) printf("in multitree %p.\n",mdict);
881 xbt_multidict_set(mdict,keys,xbt_strdup(key),free);
883 data = xbt_multidict_get(mdict,keys);
885 xbt_test_assert2(data && !strcmp((char*)data,key),
886 "Retrieved value (%s) does not match the entrered one (%s)\n",
889 xbt_dict_free(&mdict);
892 xbt_dynar_free(&keys);
895 xbt_dict_dump(mdict,&xbt_dict_print);*/
897 xbt_dict_free(&mdict);
898 xbt_dynar_free(&keys);
901 #endif /* SIMGRID_TEST */