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(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 */
144 * \brief Add data to the dict (arbitrary key)
145 * \param dict the container
146 * \param key the key to set the new data
147 * \param key_len the size of the \a key
148 * \param data the data to add in the dict
149 * \param free_ctn function to call with (\a key as argument) when
150 * \a key is removed from the dictionnary
152 * Set the \a data in the structure under the \a key, which can be any kind
153 * of data, as long as its length is provided in \a key_len.
155 void xbt_dict_set_ext(xbt_dict_t dict,
159 void_f_pvoid_t *free_ctn) {
162 unsigned int hash_code = xbt_dict_hash(key,key_len) % dict->table_size;
163 xbt_dictelm_t current, previous = NULL;
165 current = dict->table[hash_code];
166 while (current != NULL &&
167 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
169 current = current->next;
172 if (current == NULL) {
173 /* this key doesn't exist yet */
174 current = xbt_dictelm_new(key, key_len, data, free_ctn, NULL);
175 if (previous == NULL) {
176 dict->table[hash_code] = current;
179 previous->next = current;
184 /* there is already an element with the same key: we overwrite it */
185 if (current->content != NULL && current->free_f != NULL) {
186 current->free_f(current->content);
188 current->content = data;
189 current->free_f = free_ctn;
194 * \brief Add data to the dict (null-terminated key)
196 * \param dict the dict
197 * \param key the key to set the new data
198 * \param data the data to add in the dict
199 * \param free_ctn function to call with (\a key as argument) when
200 * \a key is removed from the dictionnary
202 * set the \a data in the structure under the \a key, which is a
203 * null terminated string.
205 void xbt_dict_set(xbt_dict_t dict,
208 void_f_pvoid_t *free_ctn) {
212 xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn);
216 * \brief Retrieve data from the dict (arbitrary key)
218 * \param dict the dealer of data
219 * \param key the key to find data
220 * \param key_len the size of the \a key
221 * \return the data that we are looking for
223 * Search the given \a key. Throws not_found_error when not found.
225 void *xbt_dict_get_ext(xbt_dict_t dict,
230 unsigned int hash_code = xbt_dict_hash(key,key_len) % dict->table_size;
231 xbt_dictelm_t current;
233 current = dict->table[hash_code];
234 while (current != NULL &&
235 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
236 current = current->next;
239 if (current == NULL) {
240 THROW2(not_found_error, 0, "key %.*s not found", key_len, key);
243 return current->content;
247 * \brief Retrieve data from the dict (null-terminated key)
249 * \param dict the dealer of data
250 * \param key the key to find data
251 * \return the data that we are looking for
253 * Search the given \a key. Throws not_found_error when not found.
254 * Check xbt_dict_get_or_null() for a version returning NULL without exception when
257 void *xbt_dict_get(xbt_dict_t dict,
261 unsigned int hash_code = xbt_dict_hash(key) % dict->table_size;
262 xbt_dictelm_t current;
264 current = dict->table[hash_code];
265 while (current != NULL && (strcmp(key, current->key))) {
266 current = current->next;
269 if (current == NULL) {
270 THROW1(not_found_error, 0, "key %s not found", key);
273 return current->content;
277 * \brief like xbt_dict_get(), but returning NULL when not found
279 void *xbt_dict_get_or_null(xbt_dict_t dict,
284 result = xbt_dict_get(dict, key);
286 if (e.category != not_found_error)
296 * \brief Remove data from the dict (arbitrary key)
298 * \param dict the trash can
299 * \param key the key of the data to be removed
300 * \param key_len the size of the \a key
302 * Remove the entry associated with the given \a key (throws not_found)
304 void xbt_dict_remove_ext(xbt_dict_t dict,
309 unsigned int hash_code = xbt_dict_hash(key,key_len) % dict->table_size;
310 xbt_dictelm_t current, previous = NULL;
312 current = dict->table[hash_code];
313 while (current != NULL &&
314 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
315 previous = current; /* save the previous node */
316 current = current->next;
319 if (current == NULL) {
320 THROW2(not_found_error, 0, "key %.*s not found", key_len, key);
323 if (previous != NULL) {
324 xbt_assert0(previous->next == current, "previous-next != current");
325 previous->next = current->next;
328 dict->table[hash_code] = current->next;
331 xbt_dictelm_free(current);
336 * \brief Remove data from the dict (null-terminated key)
338 * \param dict the dict
339 * \param key the key of the data to be removed
341 * Remove the entry associated with the given \a key
343 void xbt_dict_remove(xbt_dict_t dict,
347 xbt_dict_remove_ext(dict, key, strlen(key));
351 * \brief Remove all data from the dict
352 * \param dict the dict
354 void xbt_dict_reset(xbt_dict_t dict) {
358 xbt_dictelm_t current, previous = NULL;
359 for (i = 0; i < dict->table_size; i++) {
360 current = dict->table[i];
361 while (current != NULL) {
363 current = current->next;
364 xbt_dictelm_free(previous);
366 dict->table[i] = NULL;
373 * \brief Return the number of elements in the dict.
374 * \param dict a dictionary
376 int xbt_dict_length(xbt_dict_t dict) {
383 * Add an already mallocated element to a dictionary.
385 void xbt_dict_add_element(xbt_dict_t dict, xbt_dictelm_t element) {
388 int hashcode = xbt_dict_hash(element->key,element->key_len) % dict->table_size;
389 element->next = dict->table[hashcode];
390 dict->table[hashcode] = element;
394 * \brief Outputs the content of the structure (debuging purpose)
396 * \param dict the exibitionist
397 * \param output a function to dump each data in the tree
399 * Ouputs the content of the structure. (for debuging purpose). \a ouput is a
400 * function to output the data. If NULL, data won't be displayed.
403 void xbt_dict_dump(xbt_dict_t dict,
404 void_f_pvoid_t *output) {
406 xbt_dictelm_t element;
407 printf("Dict %p:\n", dict);
409 for (i = 0; i < dict->table_size; i++) {
410 element = dict->table[i];
411 while (element != NULL) {
412 printf("%s -> ", element->key);
413 if (output != NULL) {
414 output(element->content);
417 element = element->next;
424 * Destroy the dict mallocators.
425 * This is an internal XBT function called by xbt_exit().
427 void xbt_dict_exit(void) {
428 if (dict_mallocator != NULL) {
429 xbt_mallocator_free(dict_mallocator);
430 xbt_mallocator_free(dict_elm_mallocator);
434 static void* dict_mallocator_new_f(void) {
435 return xbt_new(s_xbt_dict_t, 1);
438 static void dict_mallocator_free_f(void* dict) {
442 static void dict_mallocator_reset_f(void* dict) {
443 /* nothing to do because all fields are
444 * initialized in xbt_dict_new
451 #include "portable.h"
453 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
454 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
456 XBT_TEST_SUITE("dict","Dict data container");
458 static void print_str(void *str) {
459 printf("%s",(char*)PRINTF_STR(str));
462 static void debuged_add_ext(xbt_dict_t head,const char*key,const char*data_to_fill) {
463 char *data=xbt_strdup(data_to_fill);
465 xbt_test_log2("Add %s under %s",PRINTF_STR(data_to_fill),PRINTF_STR(key));
467 xbt_dict_set(head,key,data,&free);
468 if (XBT_LOG_ISENABLED(xbt_dict,xbt_log_priority_debug)) {
469 xbt_dict_dump(head,(void (*)(void*))&printf);
473 static void debuged_add(xbt_dict_t head,const char*key) {
474 debuged_add_ext(head,key,key);
477 static void fill(xbt_dict_t *head) {
478 xbt_test_add0("Fill in the dictionnary");
480 *head = xbt_dict_new();
481 debuged_add(*head,"12");
482 debuged_add(*head,"12a");
483 debuged_add(*head,"12b");
484 debuged_add(*head,"123");
485 debuged_add(*head,"123456");
486 /* Child becomes child of what to add */
487 debuged_add(*head,"1234");
488 /* Need of common ancestor */
489 debuged_add(*head,"123457");
493 static void search_ext(xbt_dict_t head,const char*key, const char *data) {
496 xbt_test_add1("Search %s",key);
497 found=xbt_dict_get(head,key);
498 xbt_test_log1("Found %s",(char *)found);
500 xbt_test_assert1(found,"data do not match expectations: found NULL while searching for %s",data);
502 xbt_test_assert2(!strcmp((char*)data,found),"data do not match expectations: found %s while searching for %s", (char*)found, data);
505 static void search(xbt_dict_t head,const char*key) {
506 search_ext(head,key,key);
509 static void debuged_remove(xbt_dict_t head,const char*key) {
511 xbt_test_add1("Remove '%s'",PRINTF_STR(key));
512 xbt_dict_remove(head,key);
513 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
517 static void traverse(xbt_dict_t head) {
518 xbt_dict_cursor_t cursor=NULL;
522 xbt_dict_foreach(head,cursor,key,data) {
523 xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data));
524 xbt_test_assert2(!data || !strcmp(key,data),
525 "Key(%s) != value(%s). Abording\n",key,data);
529 static void search_not_found(xbt_dict_t head, const char *data) {
533 xbt_test_add1("Search %s (expected not to be found)",data);
536 data = xbt_dict_get(head, data);
537 THROW1(unknown_error,0,"Found something which shouldn't be there (%s)",data);
539 if (e.category != not_found_error)
540 xbt_test_exception(e);
544 xbt_test_assert0(ok,"Exception not raised");
547 static void count(xbt_dict_t dict, int length) {
548 xbt_test_add1("Count elements (expecting %d)", length);
549 xbt_test_assert2(xbt_dict_length(dict) == length, "Length(%d) != %d.", xbt_dict_length(dict), length);
553 xbt_dict_t head=NULL;
557 XBT_TEST_UNIT("basic",test_dict_basic,"Basic usage: change, retrieve, traverse"){
558 xbt_test_add0("Traversal the empty dictionnary");
561 xbt_test_add0("Traverse the full dictionnary");
565 debuged_add_ext(head,"toto","tutu");
566 search_ext(head,"toto","tutu");
567 debuged_remove(head,"toto");
572 xbt_test_add0("Free the dictionnary (twice)");
573 xbt_dict_free(&head);
574 xbt_dict_free(&head);
579 xbt_test_add0("Change 123 to 'Changed 123'");
580 xbt_dict_set(head,"123",strdup("Changed 123"),&free);
583 xbt_test_add0("Change 123 back to '123'");
584 xbt_dict_set(head,"123",strdup("123"),&free);
587 xbt_test_add0("Change 12a to 'Dummy 12a'");
588 xbt_dict_set(head,"12a",strdup("Dummy 12a"),&free);
591 xbt_test_add0("Change 12a to '12a'");
592 xbt_dict_set(head,"12a",strdup("12a"),&free);
595 xbt_test_add0("Traverse the resulting dictionnary");
599 xbt_test_add0("Search 123");
600 data = xbt_dict_get(head,"123");
601 xbt_test_assert(data);
602 xbt_test_assert(!strcmp("123",data));
604 search_not_found(head,"Can't be found");
605 search_not_found(head,"123 Can't be found");
606 search_not_found(head,"12345678 NOT");
611 search(head,"123456");
613 search(head,"123457");
615 xbt_test_add0("Traverse the resulting dictionnary");
618 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
620 xbt_test_add0("Free the dictionnary twice");
621 xbt_dict_free(&head);
622 xbt_dict_free(&head);
624 xbt_test_add0("Traverse the resulting dictionnary");
628 XBT_TEST_UNIT("remove",test_dict_remove,"Removing some values"){
631 xbt_test_add0("Remove non existing data");
633 debuged_remove(head,"Does not exist");
635 if (e.category != not_found_error)
636 xbt_test_exception(e);
641 xbt_dict_free(&head);
643 xbt_test_add0("Remove each data manually (traversing the resulting dictionnary each time)");
645 debuged_remove(head,"12a"); traverse(head);
647 debuged_remove(head,"12b"); traverse(head);
649 debuged_remove(head,"12"); traverse(head);
651 debuged_remove(head,"123456"); traverse(head);
654 debuged_remove(head,"12346");
656 if (e.category != not_found_error)
657 xbt_test_exception(e);
661 debuged_remove(head,"1234"); traverse(head);
662 debuged_remove(head,"123457"); traverse(head);
663 debuged_remove(head,"123"); traverse(head);
665 debuged_remove(head,"12346");
667 if (e.category != not_found_error)
668 xbt_test_exception(e);
672 xbt_test_add0("Remove all values");
673 xbt_dict_free(&head);
675 xbt_dict_reset(head);
679 xbt_test_add0("Free the dictionnary twice");
680 xbt_dict_free(&head);
681 xbt_dict_free(&head);
684 XBT_TEST_UNIT("nulldata",test_dict_nulldata,"NULL data management"){
687 xbt_test_add0("Store NULL under 'null'");
688 xbt_dict_set(head,"null",NULL,NULL);
689 search_ext(head,"null",NULL);
691 xbt_test_add0("Check whether I see it while traversing...");
693 xbt_dict_cursor_t cursor=NULL;
697 xbt_dict_foreach(head,cursor,key,data) {
698 xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data));
699 if (!strcmp(key,"null"))
702 xbt_test_assert0(found,"the key 'null', associated to NULL is not found");
704 xbt_dict_free(&head);
708 #define SIZEOFKEY 1024
709 static int countelems(xbt_dict_t head) {
710 xbt_dict_cursor_t cursor;
715 xbt_dict_foreach(head,cursor,key,data) {
721 XBT_TEST_UNIT("crash",test_dict_crash,"Crash test"){
722 xbt_dict_t head=NULL;
727 srand((unsigned int)time(NULL));
729 xbt_test_add0("CRASH test");
730 xbt_test_log0("Fill the struct, count its elems and frees the structure (x10)");
731 xbt_test_log1("using 1000 elements with %d chars long randomized keys.",SIZEOFKEY);
735 // if (i%10) printf("."); else printf("%d",i/10); fflush(stdout);
737 for (j=0;j<1000;j++) {
738 key=xbt_malloc(SIZEOFKEY);
740 for (k=0;k<SIZEOFKEY-1;k++)
741 key[k]=rand() % ('z' - 'a') + 'a';
743 /* printf("[%d %s]\n",j,key); */
744 xbt_dict_set(head,key,key,&free);
746 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
747 nb = countelems(head);
748 xbt_test_assert1(nb == 1000,"found %d elements instead of 1000",nb);
750 xbt_dict_free(&head);
751 xbt_dict_free(&head);
756 xbt_test_add1("Fill %d elements, with keys being the number of element",NB_ELM);
757 for (j=0;j<NB_ELM;j++) {
758 // if (!(j%1000)) { printf("."); fflush(stdout); }
760 key = xbt_malloc(10);
763 xbt_dict_set(head,key,key,&free);
766 xbt_test_add0("Count the elements (retrieving the key and data for each)");
767 i = countelems(head);
768 xbt_test_log1("There is %d elements",i);
770 xbt_test_add1("Search my %d elements 20 times",NB_ELM);
773 // if (i%10) printf("."); else printf("%d",i/10); fflush(stdout);
774 for (j=0;j<NB_ELM;j++) {
777 data = xbt_dict_get(head,key);
778 xbt_test_assert2(!strcmp(key,(char*)data),
779 "key=%s != data=%s\n",key,(char*)data);
784 xbt_test_add1("Remove my %d elements",NB_ELM);
786 for (j=0;j<NB_ELM;j++) {
787 //if (!(j%10000)) printf("."); fflush(stdout);
790 xbt_dict_remove(head,key);
795 xbt_test_add0("Free the structure (twice)");
796 xbt_dict_free(&head);
797 xbt_dict_free(&head);
800 static void str_free(void *s) {
805 XBT_TEST_UNIT("multicrash",test_dict_multicrash,"Multi-dict crash test"){
808 #define NB_ELM 100 /*00*/
811 #define NB_TEST 20 /*20*/
814 xbt_dict_t mdict = NULL;
816 xbt_dynar_t keys = xbt_dynar_new(sizeof(char*),str_free);
821 xbt_test_add0("Generic multicache CRASH test");
822 xbt_test_log4(" Fill the struct and frees it %d times, using %d elements, "
823 "depth of multicache=%d, key size=%d",
824 NB_TEST,NB_ELM,DEPTH,KEY_SIZE);
826 for (l=0 ; l<DEPTH ; l++) {
827 key=xbt_malloc(KEY_SIZE);
828 xbt_dynar_push(keys,&key);
831 for (i=0;i<NB_TEST;i++) {
832 mdict = xbt_dict_new();
833 VERB1("mdict=%p",mdict);
835 printf("Test %d\n",i);
836 /* else if (i%10) printf("."); else printf("%d",i/10);*/
838 for (j=0;j<NB_ELM;j++) {
839 if (verbose>0) printf (" Add {");
841 for (l=0 ; l<DEPTH ; l++) {
842 key=*(char**)xbt_dynar_get_ptr(keys,l);
844 for (k=0;k<KEY_SIZE-1;k++)
845 key[k]=rand() % ('z' - 'a') + 'a';
849 if (verbose>0) printf("%p=%s %s ",key, key,(l<DEPTH-1?";":"}"));
851 if (verbose>0) printf("in multitree %p.\n",mdict);
853 xbt_multidict_set(mdict,keys,xbt_strdup(key),free);
855 data = xbt_multidict_get(mdict,keys);
857 xbt_test_assert2(data && !strcmp((char*)data,key),
858 "Retrieved value (%s) does not match the entrered one (%s)\n",
861 xbt_dict_free(&mdict);
864 xbt_dynar_free(&keys);
867 xbt_dict_dump(mdict,&xbt_dict_print);*/
869 xbt_dict_free(&mdict);
870 xbt_dynar_free(&keys);
873 #endif /* SIMGRID_TEST */