Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fix https://framagit.org/simgrid/simgrid/issues/28
[simgrid.git] / src / xbt / dict.cpp
1 /* dict - a generic dictionary, variation over hash table                   */
2
3 /* Copyright (c) 2004-2019. The SimGrid Team. All rights reserved.          */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include "xbt/dict.h"
9 #include "dict_private.h"
10 #include "simgrid/Exception.hpp"
11 #include "src/xbt_modinter.h"
12 #include "xbt/ex.h"
13 #include "xbt/log.h"
14 #include "xbt/mallocator.h"
15 #include "xbt/str.h"
16 #include "xbt/string.hpp"
17
18 #include <cstdio>
19 #include <cstring>
20
21 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict, xbt, "Dictionaries provide the same functionalities as hash tables");
22
23 constexpr int MAX_FILL_PERCENT = 80;
24
25 /**
26  * @brief Constructor
27  * @param free_ctn function to call with (@a data as argument) when @a data is removed from the dictionary
28  * @return pointer to the destination
29  * @see xbt_dict_free()
30  *
31  * Creates and initialize a new dictionary with a default hashtable size.
32  * The dictionary is homogeneous: each element share the same free function.
33  */
34 xbt_dict_t xbt_dict_new_homogeneous(void_f_pvoid_t free_ctn)
35 {
36   if (dict_elm_mallocator == nullptr)
37     xbt_dict_preinit();
38
39   xbt_dict_t dict;
40
41   dict = xbt_new(s_xbt_dict_t, 1);
42   dict->free_f = free_ctn;
43   dict->table_size = 127;
44   dict->table = xbt_new0(xbt_dictelm_t, dict->table_size + 1);
45   dict->count = 0;
46   dict->fill = 0;
47
48   return dict;
49 }
50
51 /**
52  * @brief Destructor
53  * @param dict the dictionary to be freed
54  *
55  * Frees a dictionary with all the data
56  */
57 void xbt_dict_free(xbt_dict_t * dict)
58 {
59   if (dict != nullptr && *dict != nullptr) {
60     int table_size       = (*dict)->table_size;
61     xbt_dictelm_t* table = (*dict)->table;
62     /* Warning: the size of the table is 'table_size+1'...
63      * This is because table_size is used as a binary mask in xbt_dict_rehash */
64     for (int i = 0; (*dict)->count && i <= table_size; i++) {
65       xbt_dictelm_t current = table[i];
66       xbt_dictelm_t previous;
67
68       while (current != nullptr) {
69         previous = current;
70         current = current->next;
71         xbt_dictelm_free(*dict, previous);
72         (*dict)->count--;
73       }
74     }
75     xbt_free(table);
76     xbt_free(*dict);
77     *dict = nullptr;
78   }
79 }
80
81 /** Returns the amount of elements in the dict */
82 unsigned int xbt_dict_size(xbt_dict_t dict)
83 {
84   return (dict != nullptr ? static_cast<unsigned int>(dict->count) : static_cast<unsigned int>(0));
85 }
86
87 /* Expend the size of the dict */
88 static void xbt_dict_rehash(xbt_dict_t dict)
89 {
90   const unsigned oldsize = dict->table_size + 1;
91   unsigned newsize = oldsize * 2;
92
93   xbt_dictelm_t *currcell = (xbt_dictelm_t *) xbt_realloc((char *) dict->table, newsize * sizeof(xbt_dictelm_t));
94   memset(&currcell[oldsize], 0, oldsize * sizeof(xbt_dictelm_t));       /* zero second half */
95   newsize--;
96   dict->table_size = newsize;
97   dict->table = currcell;
98   XBT_DEBUG("REHASH (%u->%u)", oldsize, newsize);
99
100   for (unsigned i = 0; i < oldsize; i++, currcell++) {
101     if (*currcell == nullptr) /* empty cell */
102       continue;
103
104     xbt_dictelm_t *twincell = currcell + oldsize;
105     xbt_dictelm_t *pprev = currcell;
106     xbt_dictelm_t bucklet = *currcell;
107     for (; bucklet != nullptr; bucklet = *pprev) {
108       /* Since we use "& size" instead of "%size" and since the size was doubled, each bucklet of this cell must either:
109          - stay  in  cell i (ie, currcell)
110          - go to the cell i+oldsize (ie, twincell) */
111       if ((bucklet->hash_code & newsize) != i) {        /* Move to b */
112         *pprev = bucklet->next;
113         bucklet->next = *twincell;
114         if (*twincell == nullptr)
115           dict->fill++;
116         *twincell = bucklet;
117       } else {
118         pprev = &bucklet->next;
119       }
120     }
121
122     if (*currcell == nullptr) /* everything moved */
123       dict->fill--;
124   }
125 }
126
127 /**
128  * @brief Add data to the dict (arbitrary key)
129  * @param dict the container
130  * @param key the key to set the new data
131  * @param key_len the size of the @a key
132  * @param data the data to add in the dict
133  * @param free_ctn unused parameter (kept for compatibility)
134  *
135  * Set the @a data in the structure under the @a key, which can be any kind of data, as long as its length is provided
136  * in @a key_len.
137  */
138 void xbt_dict_set_ext(xbt_dict_t dict, const char* key, int key_len, void* data,
139                       XBT_ATTRIB_UNUSED void_f_pvoid_t free_ctn)
140 {
141   unsigned int hash_code = xbt_str_hash_ext(key, key_len);
142
143   xbt_dictelm_t current;
144   xbt_dictelm_t previous = nullptr;
145
146   XBT_CDEBUG(xbt_dict, "ADD %.*s hash = %u, size = %d, & = %u", key_len, key, hash_code,
147              dict->table_size, hash_code & dict->table_size);
148   current = dict->table[hash_code & dict->table_size];
149   while (current != nullptr && (hash_code != current->hash_code || key_len != current->key_len
150           || memcmp(key, current->key, key_len))) {
151     previous = current;
152     current = current->next;
153   }
154
155   if (current == nullptr) {
156     /* this key doesn't exist yet */
157     current = xbt_dictelm_new(key, key_len, hash_code, data);
158     dict->count++;
159     if (previous == nullptr) {
160       dict->table[hash_code & dict->table_size] = current;
161       dict->fill++;
162       if ((dict->fill * 100) / (dict->table_size + 1) > MAX_FILL_PERCENT)
163         xbt_dict_rehash(dict);
164     } else {
165       previous->next = current;
166     }
167   } else {
168     XBT_CDEBUG(xbt_dict, "Replace %.*s by %.*s under key %.*s",
169                key_len, (char *) current->content, key_len, (char *) data, key_len, (char *) key);
170     /* there is already an element with the same key: overwrite it */
171     xbt_dictelm_set_data(dict, current, data);
172   }
173 }
174
175 /**
176  * @brief Add data to the dict (null-terminated key)
177  *
178  * @param dict the dict
179  * @param key the key to set the new data
180  * @param data the data to add in the dict
181  * @param free_ctn unused parameter (kept for compatibility)
182  *
183  * set the @a data in the structure under the @a key, which is anull terminated string.
184  */
185 void xbt_dict_set(xbt_dict_t dict, const char *key, void *data, void_f_pvoid_t free_ctn)
186 {
187   xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn);
188 }
189
190 /**
191  * @brief Retrieve data from the dict (arbitrary key)
192  *
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
197  *
198  * Search the given @a key. Throws std::out_of_range when not found.
199  */
200 void *xbt_dict_get_ext(xbt_dict_t dict, const char *key, int key_len)
201 {
202   unsigned int hash_code = xbt_str_hash_ext(key, key_len);
203   xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
204
205   while (current != nullptr && (hash_code != current->hash_code || key_len != current->key_len
206           || memcmp(key, current->key, key_len))) {
207     current = current->next;
208   }
209
210   if (current == nullptr)
211     throw std::out_of_range(simgrid::xbt::string_printf("key %.*s not found", key_len, key));
212
213   return current->content;
214 }
215
216 /** @brief like xbt_dict_get_ext(), but returning nullptr when not found */
217 void *xbt_dict_get_or_null_ext(xbt_dict_t dict, const char *key, int key_len)
218 {
219   unsigned int hash_code = xbt_str_hash_ext(key, key_len);
220   xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
221
222   while (current != nullptr && (hash_code != current->hash_code || key_len != current->key_len
223           || memcmp(key, current->key, key_len))) {
224     current = current->next;
225   }
226
227   if (current == nullptr)
228     return nullptr;
229
230   return current->content;
231 }
232
233 /**
234  * @brief retrieve the key associated to that object. Warning, that's a linear search
235  *
236  * Returns nullptr if the object cannot be found
237  */
238 char *xbt_dict_get_key(xbt_dict_t dict, const void *data)
239 {
240   for (int i = 0; i <= dict->table_size; i++) {
241     xbt_dictelm_t current = dict->table[i];
242     while (current != nullptr) {
243       if (current->content == data)
244         return current->key;
245       current = current->next;
246     }
247   }
248   return nullptr;
249 }
250
251 /**
252  * @brief Retrieve data from the dict (null-terminated key)
253  *
254  * @param dict the dealer of data
255  * @param key the key to find data
256  * @return the data that we are looking for
257  *
258  * Search the given @a key. Throws std::out_of_range when not found.
259  * Check xbt_dict_get_or_null() for a version returning nullptr without exception when not found.
260  */
261 void *xbt_dict_get(xbt_dict_t dict, const char *key)
262 {
263   return xbt_dict_get_elm(dict, key)->content;
264 }
265
266 /**
267  * @brief Retrieve element from the dict (null-terminated key)
268  *
269  * @param dict the dealer of data
270  * @param key the key to find data
271  * @return the s_xbt_dictelm_t that we are looking for
272  *
273  * Search the given @a key. Throws std::out_of_range when not found.
274  * Check xbt_dict_get_or_null() for a version returning nullptr without exception when not found.
275  */
276 xbt_dictelm_t xbt_dict_get_elm(xbt_dict_t dict, const char *key)
277 {
278   xbt_dictelm_t current = xbt_dict_get_elm_or_null(dict, key);
279
280   if (current == nullptr)
281     throw std::out_of_range(simgrid::xbt::string_printf("key %s not found", key));
282
283   return current;
284 }
285
286 /**
287  * @brief like xbt_dict_get(), but returning nullptr when not found
288  */
289 void *xbt_dict_get_or_null(xbt_dict_t dict, const char *key)
290 {
291   xbt_dictelm_t current = xbt_dict_get_elm_or_null(dict, key);
292
293   if (current == nullptr)
294     return nullptr;
295
296   return current->content;
297 }
298
299 /**
300  * @brief like xbt_dict_get_elm(), but returning nullptr when not found
301  */
302 xbt_dictelm_t xbt_dict_get_elm_or_null(xbt_dict_t dict, const char *key)
303 {
304   unsigned int hash_code = xbt_str_hash(key);
305   xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
306
307   while (current != nullptr && (hash_code != current->hash_code || strcmp(key, current->key)))
308     current = current->next;
309   return current;
310 }
311
312 /**
313  * @brief Remove data from the dict (arbitrary key)
314  *
315  * @param dict the trash can
316  * @param key the key of the data to be removed
317  * @param key_len the size of the @a key
318  *
319  * Remove the entry associated with the given @a key (throws std::out_of_range)
320  */
321 void xbt_dict_remove_ext(xbt_dict_t dict, const char *key, int key_len)
322 {
323   unsigned int hash_code = xbt_str_hash_ext(key, key_len);
324   xbt_dictelm_t previous = nullptr;
325   xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
326
327   while (current != nullptr && (hash_code != current->hash_code || key_len != current->key_len
328           || strncmp(key, current->key, key_len))) {
329     previous = current;         /* save the previous node */
330     current = current->next;
331   }
332
333   if (current == nullptr)
334     throw std::out_of_range(simgrid::xbt::string_printf("key %.*s not found", key_len, key));
335   else {
336     if (previous != nullptr) {
337       previous->next = current->next;
338     } else {
339       dict->table[hash_code & dict->table_size] = current->next;
340     }
341   }
342
343   if (not dict->table[hash_code & dict->table_size])
344     dict->fill--;
345
346   xbt_dictelm_free(dict, current);
347   dict->count--;
348 }
349
350 /**
351  * @brief Remove data from the dict (null-terminated key)
352  *
353  * @param dict the dict
354  * @param key the key of the data to be removed
355  *
356  * Remove the entry associated with the given @a key
357  */
358 void xbt_dict_remove(xbt_dict_t dict, const char *key)
359 {
360   xbt_dict_remove_ext(dict, key, strlen(key));
361 }
362
363 /** @brief Remove all data from the dict */
364 void xbt_dict_reset(xbt_dict_t dict)
365 {
366   if (dict->count == 0)
367     return;
368
369   for (int i = 0; i <= dict->table_size; i++) {
370     xbt_dictelm_t previous = nullptr;
371     xbt_dictelm_t current = dict->table[i];
372     while (current != nullptr) {
373       previous = current;
374       current = current->next;
375       xbt_dictelm_free(dict, previous);
376     }
377     dict->table[i] = nullptr;
378   }
379
380   dict->count = 0;
381   dict->fill = 0;
382 }
383
384 /**
385  * @brief Return the number of elements in the dict.
386  * @param dict a dictionary
387  */
388 int xbt_dict_length(xbt_dict_t dict)
389 {
390   return dict->count;
391 }
392
393 /**
394  * @brief test if the dict is empty or not
395  */
396 int xbt_dict_is_empty(xbt_dict_t dict)
397 {
398   return not dict || (xbt_dict_length(dict) == 0);
399 }
400
401 /**
402  * Create the dict mallocators.
403  * This is an internal XBT function called during the lib initialization.
404  * It can be used several times to recreate the mallocator, for example when you switch to MC mode
405  */
406 void xbt_dict_preinit()
407 {
408   if (dict_elm_mallocator == nullptr)
409     dict_elm_mallocator = xbt_mallocator_new(256, dict_elm_mallocator_new_f, dict_elm_mallocator_free_f,
410       dict_elm_mallocator_reset_f);
411 }
412
413 /**
414  * Destroy the dict mallocators.
415  * This is an internal XBT function during the lib initialization
416  */
417 void xbt_dict_postexit()
418 {
419   if (dict_elm_mallocator != nullptr) {
420     xbt_mallocator_free(dict_elm_mallocator);
421     dict_elm_mallocator = nullptr;
422   }
423 }