Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Let the xbt_log module register its finalizer itself
[simgrid.git] / src / xbt / dict.cpp
1 /* dict - a generic dictionary, variation over hash table                   */
2
3 /* Copyright (c) 2004-2023. 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 "xbt/ex.h"
12 #include "xbt/log.h"
13 #include "xbt/mallocator.h"
14 #include "xbt/str.h"
15 #include "xbt/string.hpp"
16
17 #include <algorithm>
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 /** Handle the dict mallocators init/fini cycle. */
26 static void xbt_dict_postexit()
27 {
28   if (dict_elm_mallocator != nullptr) {
29     xbt_mallocator_free(dict_elm_mallocator);
30     dict_elm_mallocator = nullptr;
31   }
32 }
33 static void xbt_dict_preinit()
34 {
35   if (dict_elm_mallocator == nullptr) {
36     dict_elm_mallocator =
37         xbt_mallocator_new(256, dict_elm_mallocator_new_f, dict_elm_mallocator_free_f, dict_elm_mallocator_reset_f);
38     atexit(xbt_dict_postexit);
39   }
40 }
41
42 /**
43  * @brief Constructor
44  * @param free_ctn function to call with (@a data as argument) when @a data is removed from the dictionary
45  * @return pointer to the destination
46  * @see xbt_dict_free()
47  *
48  * Creates and initialize a new dictionary with a default hashtable size.
49  * The dictionary is homogeneous: each element share the same free function.
50  */
51 xbt_dict_t xbt_dict_new_homogeneous(void_f_pvoid_t free_ctn)
52 {
53   xbt_dict_preinit(); // Make sure that the module is intialized
54
55   xbt_dict_t dict;
56
57   dict = xbt_new(s_xbt_dict_t, 1);
58   dict->free_f = free_ctn;
59   dict->table_size = 127;
60   dict->table = xbt_new0(xbt_dictelm_t, dict->table_size + 1);
61   dict->count = 0;
62   dict->fill = 0;
63
64   return dict;
65 }
66
67 /**
68  * @brief Destructor
69  * @param dict the dictionary to be freed
70  *
71  * Frees a dictionary with all the data
72  */
73 void xbt_dict_free(xbt_dict_t * dict)
74 {
75   if (dict != nullptr && *dict != nullptr) {
76     int table_size       = (*dict)->table_size;
77     xbt_dictelm_t* table = (*dict)->table;
78     /* Warning: the size of the table is 'table_size+1'...
79      * This is because table_size is used as a binary mask in xbt_dict_rehash */
80     for (int i = 0; (*dict)->count && i <= table_size; i++) {
81       xbt_dictelm_t current = table[i];
82       xbt_dictelm_t previous;
83
84       while (current != nullptr) {
85         previous = current;
86         current = current->next;
87         xbt_dictelm_free(*dict, previous);
88         (*dict)->count--;
89       }
90     }
91     xbt_free(table);
92     xbt_free(*dict);
93     *dict = nullptr;
94   }
95 }
96
97 /** Returns the amount of elements in the dict */
98 unsigned int xbt_dict_size(const_xbt_dict_t dict)
99 {
100   return (dict != nullptr ? static_cast<unsigned int>(dict->count) : static_cast<unsigned int>(0));
101 }
102
103 /* Expend the size of the dict */
104 static void xbt_dict_rehash(xbt_dict_t dict)
105 {
106   const unsigned oldsize = dict->table_size + 1;
107   unsigned newsize = oldsize * 2;
108
109   auto* newtable = static_cast<xbt_dictelm_t*>(xbt_realloc(dict->table, newsize * sizeof(xbt_dictelm_t)));
110   std::fill(newtable + oldsize, newtable + newsize, nullptr); /* zero second half */
111   newsize--;
112   dict->table_size = newsize;
113   dict->table      = newtable;
114   XBT_DEBUG("REHASH (%u->%u)", oldsize, newsize);
115
116   for (unsigned i = 0; i < oldsize; i++) {
117     xbt_dictelm_t* currcell = &newtable[i];
118     if (*currcell == nullptr) /* empty cell */
119       continue;
120
121     xbt_dictelm_t *twincell = currcell + oldsize;
122     xbt_dictelm_t *pprev = currcell;
123     xbt_dictelm_t bucklet = *currcell;
124     while (bucklet != nullptr) {
125       /* Since we use "& size" instead of "%size" and since the size was doubled, each bucklet of this cell must either:
126          - stay  in  cell i (ie, currcell)
127          - go to the cell i+oldsize (ie, twincell) */
128       if ((bucklet->hash_code & newsize) != i) {        /* Move to b */
129         *pprev = bucklet->next;
130         bucklet->next = *twincell;
131         if (*twincell == nullptr)
132           dict->fill++;
133         *twincell = bucklet;
134       } else {
135         pprev = &bucklet->next;
136       }
137       bucklet = *pprev;
138     }
139
140     if (*currcell == nullptr) /* everything moved */
141       dict->fill--;
142   }
143 }
144
145 /**
146  * @brief Add data to the dict (arbitrary key)
147  * @param dict the container
148  * @param key the key to set the new data
149  * @param key_len the size of the @a key
150  * @param data the data to add in the dict
151  *
152  * 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
153  * in @a key_len.
154  */
155 void xbt_dict_set_ext(xbt_dict_t dict, const char* key, int key_len, void* data)
156 {
157   unsigned int hash_code = xbt_str_hash_ext(key, key_len);
158
159   xbt_dictelm_t current;
160   xbt_dictelm_t previous = nullptr;
161
162   XBT_CDEBUG(xbt_dict, "ADD %.*s hash = %u, size = %d, & = %u", key_len, key, hash_code,
163              dict->table_size, hash_code & dict->table_size);
164   current = dict->table[hash_code & dict->table_size];
165   while (current != nullptr && (hash_code != current->hash_code || key_len != current->key_len
166           || memcmp(key, current->key, key_len))) {
167     previous = current;
168     current = current->next;
169   }
170
171   if (current == nullptr) {
172     /* this key doesn't exist yet */
173     current = xbt_dictelm_new(key, key_len, hash_code, data);
174     dict->count++;
175     if (previous == nullptr) {
176       dict->table[hash_code & dict->table_size] = current;
177       dict->fill++;
178       if ((dict->fill * 100) / (dict->table_size + 1) > MAX_FILL_PERCENT)
179         xbt_dict_rehash(dict);
180     } else {
181       previous->next = current;
182     }
183   } else {
184     XBT_CDEBUG(xbt_dict, "Replace %.*s by %.*s under key %.*s",
185                key_len, (char *) current->content, key_len, (char *) data, key_len, (char *) key);
186     /* there is already an element with the same key: overwrite it */
187     xbt_dictelm_set_data(dict, current, data);
188   }
189 }
190
191 /**
192  * @brief Add data to the dict (null-terminated key)
193  *
194  * @param dict the dict
195  * @param key the key to set the new data
196  * @param data the data to add in the dict
197  *
198  * set the @a data in the structure under the @a key, which is a null terminated string.
199  */
200 void xbt_dict_set(xbt_dict_t dict, const char* key, void* data)
201 {
202   xbt_dict_set_ext(dict, key, strlen(key), data);
203 }
204
205 /**
206  * @brief Retrieve data from the dict (arbitrary key)
207  *
208  * @param dict the dealer of data
209  * @param key the key to find data
210  * @param key_len the size of the @a key
211  * @return the data that we are looking for
212  *
213  * Search the given @a key. Returns nullptr when not found.
214  */
215 void* xbt_dict_get_or_null_ext(const_xbt_dict_t dict, const char* key, int key_len)
216 {
217   unsigned int hash_code = xbt_str_hash_ext(key, key_len);
218   const s_xbt_dictelm* current = dict->table[hash_code & dict->table_size];
219
220   while (current != nullptr && (hash_code != current->hash_code || key_len != current->key_len
221           || memcmp(key, current->key, key_len))) {
222     current = current->next;
223   }
224
225   if (current == nullptr)
226     return nullptr;
227
228   return current->content;
229 }
230
231 /**
232  * @brief Retrieve data from the dict (null-terminated key)
233  *
234  * @param dict the dealer of data
235  * @param key the key to find data
236  * @return the data that we are looking for
237  *
238  * Search the given @a key. Returns nullptr when not found.
239  */
240 void* xbt_dict_get_or_null(const_xbt_dict_t dict, const char* key)
241 {
242   const s_xbt_dictelm* current = xbt_dict_get_elm_or_null(dict, key);
243
244   if (current == nullptr)
245     return nullptr;
246
247   return current->content;
248 }
249
250 /**
251  * @brief Retrieve element from the dict (null-terminated key)
252  *
253  * @param dict the dealer of data
254  * @param key the key to find data
255  * @return the s_xbt_dictelm_t that we are looking for
256  *
257  * Search the given @a key. Returns nullptr when not found.
258  */
259 xbt_dictelm_t xbt_dict_get_elm_or_null(const_xbt_dict_t dict, const char* key)
260 {
261   unsigned int hash_code = xbt_str_hash(key);
262   xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
263
264   while (current != nullptr && (hash_code != current->hash_code || strcmp(key, current->key)))
265     current = current->next;
266   return current;
267 }
268
269 /**
270  * @brief Remove data from the dict (arbitrary key)
271  *
272  * @param dict the trash can
273  * @param key the key of the data to be removed
274  * @param key_len the size of the @a key
275  *
276  * Remove the entry associated with the given @a key (throws std::out_of_range)
277  */
278 void xbt_dict_remove_ext(xbt_dict_t dict, const char *key, int key_len)
279 {
280   unsigned int hash_code = xbt_str_hash_ext(key, key_len);
281   xbt_dictelm_t previous = nullptr;
282   xbt_dictelm_t current = dict->table[hash_code & dict->table_size];
283
284   while (current != nullptr && (hash_code != current->hash_code || key_len != current->key_len
285           || strncmp(key, current->key, key_len))) {
286     previous = current;         /* save the previous node */
287     current = current->next;
288   }
289
290   if (current == nullptr)
291     throw std::out_of_range(simgrid::xbt::string_printf("key %.*s not found", key_len, key));
292   else {
293     if (previous != nullptr) {
294       previous->next = current->next;
295     } else {
296       dict->table[hash_code & dict->table_size] = current->next;
297     }
298   }
299
300   if (not dict->table[hash_code & dict->table_size])
301     dict->fill--;
302
303   xbt_dictelm_free(dict, current);
304   dict->count--;
305 }
306
307 /**
308  * @brief Return the number of elements in the dict.
309  * @param dict a dictionary
310  */
311 int xbt_dict_length(const_xbt_dict_t dict)
312 {
313   return dict->count;
314 }
315
316 /**
317  * @brief test if the dict is empty or not
318  */
319 int xbt_dict_is_empty(const_xbt_dict_t dict)
320 {
321   return not dict || (xbt_dict_length(dict) == 0);
322 }