Logo AND Algorithmique Numérique Distribuée

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