Logo AND Algorithmique Numérique Distribuée

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