Debian Codegraph @

crt/aws-c-common/include/aws/common/hash_table.h

raw symbols SCIP
1 #ifndef AWS_COMMON_HASH_TABLE_H
2 #define AWS_COMMON_HASH_TABLE_H
3
4 /**
5 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 * SPDX-License-Identifier: Apache-2.0.
7 */
8
9 #include <aws/common/common.h>
10
11 #include <stddef.h>
12
13 AWS_PUSH_SANE_WARNING_LEVEL
14
15 enum {
16 AWS_COMMON_HASH_TABLE_ITER_CONTINUE = (1 << 0),
17 AWS_COMMON_HASH_TABLE_ITER_DELETE = (1 << 1),
18 AWS_COMMON_HASH_TABLE_ITER_ERROR = (1 << 2),
19 };
20
21 /**
22 * Hash table data structure. This module provides an automatically resizing
23 * hash table implementation for general purpose use. The hash table stores a
24 * mapping between void * keys and values; it is expected that in most cases,
25 * these will point to a structure elsewhere in the heap, instead of inlining a
26 * key or value into the hash table element itself.
27 *
28 * Currently, this hash table implements a variant of robin hood hashing, but
29 * we do not guarantee that this won't change in the future.
30 *
31 * Associated with each hash function are four callbacks:
32 *
33 * hash_fn - A hash function from the keys to a uint64_t. It is critical that
34 * the hash function for a key does not change while the key is in the hash
35 * table; violating this results in undefined behavior. Collisions are
36 * tolerated, though naturally with reduced performance.
37 *
38 * equals_fn - An equality comparison function. This function must be
39 * reflexive and consistent with hash_fn.
40 *
41 * destroy_key_fn, destroy_value_fn - Optional callbacks invoked when the
42 * table is cleared or cleaned up and at the caller's option when an element
43 * is removed from the table. Either or both may be set to NULL, which
44 * has the same effect as a no-op destroy function.
45 *
46 * This datastructure can be safely moved between threads, subject to the
47 * requirements of the underlying allocator. It is also safe to invoke
48 * non-mutating operations on the hash table from multiple threads. A suitable
49 * memory barrier must be used when transitioning from single-threaded mutating
50 * usage to multithreaded usage.
51 */
52 struct hash_table_state; /* Opaque pointer */
53 struct aws_hash_table {
54 struct hash_table_state *p_impl;
55 };
56
57 /**
58 * Represents an element in the hash table. Various operations on the hash
59 * table may provide pointers to elements stored within the hash table;
60 * generally, calling code may alter value, but must not alter key (or any
61 * information used to compute key's hash code).
62 *
63 * Pointers to elements within the hash are invalidated whenever an operation
64 * which may change the number of elements in the hash is invoked (i.e. put,
65 * delete, clear, and clean_up), regardless of whether the number of elements
66 * actually changes.
67 */
68 struct aws_hash_element {
69 const void *key;
70 void *value;
71 };
72
73 enum aws_hash_iter_status {
74 AWS_HASH_ITER_STATUS_DONE,
75 AWS_HASH_ITER_STATUS_DELETE_CALLED,
76 AWS_HASH_ITER_STATUS_READY_FOR_USE,
77 };
78
79 struct aws_hash_iter {
80 const struct aws_hash_table *map;
81 struct aws_hash_element element;
82 size_t slot;
83 size_t limit;
84 enum aws_hash_iter_status status;
85 /*
86 * Reserving extra fields for binary compatibility with future expansion of
87 * iterator in case hash table implementation changes.
88 */
89 int unused_0;
90 void *unused_1;
91 void *unused_2;
92 };
93
94 /**
95 * Prototype for a key hashing function pointer.
96 */
97 typedef uint64_t(aws_hash_fn)(const void *key);
98
99 /**
100 * Prototype for a hash table equality check function pointer.
101 *
102 * This type is usually used for a function that compares two hash table
103 * keys, but note that the same type is used for a function that compares
104 * two hash table values in aws_hash_table_eq.
105 *
106 * Equality functions used in a hash table must be be reflexive (a == a),
107 * symmetric (a == b => b == a), transitive (a == b, b == c => a == c)
108 * and consistent (result does not change with time).
109 */
110 typedef bool(aws_hash_callback_eq_fn)(const void *a, const void *b);
111
112 /**
113 * Prototype for a hash table key or value destructor function pointer.
114 *
115 * This function is used to destroy elements in the hash table when the
116 * table is cleared or cleaned up.
117 *
118 * Note that functions which remove individual elements from the hash
119 * table provide options of whether or not to invoke the destructors
120 * on the key and value of a removed element.
121 */
122 typedef void(aws_hash_callback_destroy_fn)(void *key_or_value);
123
124 AWS_EXTERN_C_BEGIN
125
126 /**
127 * Initializes a hash map with initial capacity for 'size' elements
128 * without resizing. Uses hash_fn to compute the hash of each element.
129 * equals_fn to compute equality of two keys. Whenever an element is
130 * removed without being returned, destroy_key_fn is run on the pointer
131 * to the key and destroy_value_fn is run on the pointer to the value.
132 * Either or both may be NULL if a callback is not desired in this case.
133 */
134 AWS_COMMON_API
135 int aws_hash_table_init(
136 struct aws_hash_table *map,
137 struct aws_allocator *alloc,
138 size_t size,
139 aws_hash_fn *hash_fn,
140 aws_hash_callback_eq_fn *equals_fn,
141 aws_hash_callback_destroy_fn *destroy_key_fn,
142 aws_hash_callback_destroy_fn *destroy_value_fn);
143
144 /**
145 * Deletes every element from map and frees all associated memory.
146 * destroy_fn will be called for each element. aws_hash_table_init
147 * must be called before reusing the hash table.
148 *
149 * This method is idempotent.
150 */
151 AWS_COMMON_API
152 void aws_hash_table_clean_up(struct aws_hash_table *map);
153
154 /**
155 * Safely swaps two hash tables. Note that we swap the entirety of the hash
156 * table, including which allocator is associated.
157 *
158 * Neither hash table is required to be initialized; if one or both is
159 * uninitialized, then the uninitialized state is also swapped.
160 */
161 AWS_COMMON_API
162 void aws_hash_table_swap(struct aws_hash_table *AWS_RESTRICT a, struct aws_hash_table *AWS_RESTRICT b);
163
164 /**
165 * Moves the hash table in 'from' to 'to'. After this move, 'from' will
166 * be identical to the state of the original 'to' hash table, and 'to'
167 * will be in the same state as if it had been passed to aws_hash_table_clean_up
168 * (that is, it will have no memory allocated, and it will be safe to
169 * either discard it or call aws_hash_table_clean_up again).
170 *
171 * Note that 'to' will not be cleaned up. You should make sure that 'to'
172 * is either uninitialized or cleaned up before moving a hashtable into
173 * it.
174 */
175 AWS_COMMON_API
176 void aws_hash_table_move(struct aws_hash_table *AWS_RESTRICT to, struct aws_hash_table *AWS_RESTRICT from);
177
178 /**
179 * Returns the current number of entries in the table.
180 */
181 AWS_COMMON_API
182 size_t aws_hash_table_get_entry_count(const struct aws_hash_table *map);
183
184 /**
185 * Returns an iterator to be used for iterating through a hash table.
186 * Iterator will already point to the first element of the table it finds,
187 * which can be accessed as iter.element.
188 *
189 * This function cannot fail, but if there are no elements in the table,
190 * the returned iterator will return true for aws_hash_iter_done(&iter).
191 */
192 AWS_COMMON_API
193 struct aws_hash_iter aws_hash_iter_begin(const struct aws_hash_table *map);
194
195 /**
196 * Returns true if iterator is done iterating through table, false otherwise.
197 * If this is true, the iterator will not include an element of the table.
198 */
199 AWS_COMMON_API
200 bool aws_hash_iter_done(const struct aws_hash_iter *iter);
201
202 /**
203 * Updates iterator so that it points to next element of hash table.
204 *
205 * This and the two previous functions are designed to be used together with
206 * the following idiom:
207 *
208 * for (struct aws_hash_iter iter = aws_hash_iter_begin(&map);
209 * !aws_hash_iter_done(&iter); aws_hash_iter_next(&iter)) {
210 * const key_type key = *(const key_type *)iter.element.key;
211 * value_type value = *(value_type *)iter.element.value;
212 * // etc.
213 * }
214 *
215 * Note that calling this on an iter which is "done" is idempotent:
216 * i.e. it will return another iter which is "done".
217 */
218 AWS_COMMON_API
219 void aws_hash_iter_next(struct aws_hash_iter *iter);
220
221 /**
222 * Deletes the element currently pointed-to by the hash iterator.
223 * After calling this method, the element member of the iterator
224 * should not be accessed until the next call to aws_hash_iter_next.
225 *
226 * @param destroy_contents If true, the destructors for the key and value
227 * will be called.
228 */
229 AWS_COMMON_API
230 void aws_hash_iter_delete(struct aws_hash_iter *iter, bool destroy_contents);
231
232 /**
233 * Attempts to locate an element at key. If the element is found, a
234 * pointer to the value is placed in *p_elem; if it is not found,
235 * *pElem is set to NULL. Either way, AWS_OP_SUCCESS is returned.
236 *
237 * This method does not change the state of the hash table. Therefore, it
238 * is safe to call _find from multiple threads on the same hash table,
239 * provided no mutating operations happen in parallel.
240 *
241 * Calling code may update the value in the hash table by modifying **pElem
242 * after a successful find. However, this pointer is not guaranteed to
243 * remain usable after a subsequent call to _put, _delete, _clear, or
244 * _clean_up.
245 */
246
247 AWS_COMMON_API
248 int aws_hash_table_find(const struct aws_hash_table *map, const void *key, struct aws_hash_element **p_elem);
249
250 /**
251 * Attempts to locate an element at key. If no such element was found,
252 * creates a new element, with value initialized to NULL. In either case, a
253 * pointer to the element is placed in *p_elem.
254 *
255 * If was_created is non-NULL, *was_created is set to 0 if an existing
256 * element was found, or 1 is a new element was created.
257 *
258 * Returns AWS_OP_SUCCESS if an item was found or created.
259 * Raises AWS_ERROR_OOM if hash table expansion was required and memory
260 * allocation failed.
261 */
262 AWS_COMMON_API
263 int aws_hash_table_create(
264 struct aws_hash_table *map,
265 const void *key,
266 struct aws_hash_element **p_elem,
267 int *was_created);
268
269 /**
270 * Inserts a new element at key, with the given value. If another element
271 * exists at that key, the old element will be overwritten; both old key and
272 * value objects will be destroyed.
273 *
274 * If was_created is non-NULL, *was_created is set to 0 if an existing
275 * element was found, or 1 is a new element was created.
276 *
277 * Returns AWS_OP_SUCCESS if an item was found or created.
278 * Raises AWS_ERROR_OOM if hash table expansion was required and memory
279 * allocation failed.
280 */
281 AWS_COMMON_API
282 int aws_hash_table_put(struct aws_hash_table *map, const void *key, void *value, int *was_created);
283
284 /**
285 * Removes element at key. Always returns AWS_OP_SUCCESS.
286 *
287 * If pValue is non-NULL, the existing value (if any) is moved into
288 * (*value) before removing from the table, and destroy_fn is _not_
289 * invoked. If pValue is NULL, then (if the element existed) destroy_fn
290 * will be invoked on the element being removed.
291 *
292 * If was_present is non-NULL, it is set to 0 if the element was
293 * not present, or 1 if it was present (and is now removed).
294 */
295 AWS_COMMON_API
296 int aws_hash_table_remove(
297 struct aws_hash_table *map,
298 const void *key,
299 struct aws_hash_element *p_value,
300 int *was_present);
301
302 /**
303 * Removes element already known (typically by find()).
304 *
305 * p_value should point to a valid element returned by create() or find().
306 *
307 * NOTE: DO NOT call this method from inside of a aws_hash_table_foreach callback, return
308 * AWS_COMMON_HASH_TABLE_ITER_DELETE instead.
309 */
310 AWS_COMMON_API
311 int aws_hash_table_remove_element(struct aws_hash_table *map, struct aws_hash_element *p_value);
312
313 /**
314 * Iterates through every element in the map and invokes the callback on
315 * that item. Iteration is performed in an arbitrary, implementation-defined
316 * order, and is not guaranteed to be consistent across invocations.
317 *
318 * The callback may change the value associated with the key by overwriting
319 * the value pointed-to by value. In this case, the on_element_removed
320 * callback will not be invoked, unless the callback invokes
321 * AWS_COMMON_HASH_TABLE_ITER_DELETE (in which case the on_element_removed
322 * is given the updated value).
323 *
324 * The callback must return a bitmask of zero or more of the following values
325 * ORed together:
326 *
327 * # AWS_COMMON_HASH_TABLE_ITER_CONTINUE - Continues iteration to the next
328 * element (if not set, iteration stops)
329 * # AWS_COMMON_HASH_TABLE_ITER_DELETE - Deletes the current value and
330 * continues iteration. destroy_fn will NOT be invoked.
331 * # AWS_COMMON_HASH_TABLE_ITER_ERROR - Stop iteration with error.
332 * No action will be taken for the current value and the value before this.
333 * No rolling back. The deleted value before will NOT be back.
334 * aws_hash_table_foreach returns AWS_OP_ERR after stropping the iteration.
335 *
336 * Invoking any method which may change the contents of the hashtable
337 * during iteration results in undefined behavior. However, you may safely
338 * invoke non-mutating operations during an iteration.
339 *
340 * This operation is mutating only if AWS_COMMON_HASH_TABLE_ITER_DELETE
341 * is returned at some point during iteration. Otherwise, it is non-mutating
342 * and is safe to invoke in parallel with other non-mutating operations.
343 */
344
345 AWS_COMMON_API
346 int aws_hash_table_foreach(
347 struct aws_hash_table *map,
348 int (*callback)(void *context, struct aws_hash_element *p_element),
349 void *context);
350
351 /**
352 * Compares two hash tables for equality. Both hash tables must have equivalent
353 * key comparators; values will be compared using the comparator passed into this
354 * function. The key hash function does not need to be equivalent between the
355 * two hash tables.
356 */
357 AWS_COMMON_API
358 bool aws_hash_table_eq(
359 const struct aws_hash_table *a,
360 const struct aws_hash_table *b,
361 aws_hash_callback_eq_fn *value_eq);
362
363 /**
364 * Removes every element from the hash map. destroy_fn will be called for
365 * each element.
366 */
367 AWS_COMMON_API
368 void aws_hash_table_clear(struct aws_hash_table *map);
369
370 /**
371 * Convenience hash function for NULL-terminated C-strings
372 */
373 AWS_COMMON_API
374 uint64_t aws_hash_c_string(const void *item);
375
376 /**
377 * Convenience hash function for struct aws_strings.
378 * Hash is same as used on the string bytes by aws_hash_c_string.
379 */
380 AWS_COMMON_API
381 uint64_t aws_hash_string(const void *item);
382
383 /**
384 * Convenience hash function for struct aws_byte_cursor.
385 * Hash is same as used on the string bytes by aws_hash_c_string.
386 */
387 AWS_COMMON_API
388 uint64_t aws_hash_byte_cursor_ptr(const void *item);
389
390 /**
391 * Convenience hash function which hashes the pointer value directly,
392 * without dereferencing. This can be used in cases where pointer identity
393 * is desired, or where a uintptr_t is encoded into a const void *.
394 */
395 AWS_COMMON_API
396 uint64_t aws_hash_ptr(const void *item);
397
398 AWS_COMMON_API
399 uint64_t aws_hash_combine(uint64_t item1, uint64_t item2);
400
401 /**
402 * Convenience eq callback for NULL-terminated C-strings
403 */
404 AWS_COMMON_API
405 bool aws_hash_callback_c_str_eq(const void *a, const void *b);
406
407 /**
408 * Convenience eq callback for AWS strings
409 */
410 AWS_COMMON_API
411 bool aws_hash_callback_string_eq(const void *a, const void *b);
412
413 /**
414 * Convenience destroy callback for AWS strings
415 */
416 AWS_COMMON_API
417 void aws_hash_callback_string_destroy(void *a);
418
419 /**
420 * Equality function which compares pointer equality.
421 */
422 AWS_COMMON_API
423 bool aws_ptr_eq(const void *a, const void *b);
424
425 /**
426 * Best-effort check of hash_table_state data-structure invariants
427 */
428 AWS_COMMON_API
429 bool aws_hash_table_is_valid(const struct aws_hash_table *map);
430
431 /**
432 * Given a pointer to a hash_iter, checks that it is well-formed, with all data-structure invariants.
433 */
434 AWS_COMMON_API
435 bool aws_hash_iter_is_valid(const struct aws_hash_iter *iter);
436
437 /**
438 * Helper function to hash keys that are uint64_t values.
439 *
440 * The function is not a strong hash function in any sense; it merely reflects
441 * the uint64 value back. Do not use this function as a hash if you need
442 * the properties of a strong hash function.
443 */
444 AWS_COMMON_API uint64_t aws_hash_uint64_t_by_identity(const void *item);
445
446 /**
447 * Helper function to compare hash keys that are uint64_t values.
448 */
449 AWS_COMMON_API bool aws_hash_compare_uint64_t_eq(const void *a, const void *b);
450
451 AWS_EXTERN_C_END
452 AWS_POP_SANE_WARNING_LEVEL
453
454 #endif /* AWS_COMMON_HASH_TABLE_H */