data_structures
hashmap_utils.c
Go to the documentation of this file.
1 /* ************************************************************************** */
3 /* */
4 /* ::: :::::::: */
5 /* hashmap_utils.c :+: :+: :+: */
6 /* +:+ +:+ +:+ */
7 /* By: unite <marvin@42.fr> +#+ +:+ +#+ */
8 /* +#+#+#+#+#+ +#+ */
9 /* Created: 2020/07/21 19:19:37 by unite #+# #+# */
10 /* Updated: 2020/09/07 21:53:05 by unite ### ########.fr */
11 /* */
12 /* ************************************************************************** */
13 
14 #include "hashmap_utils.h"
15 
16 static void hashmap_rehash(t_hashmap *hm, void **old_keys, void **old_vals,
17  size_t old_capacity)
18 {
19  size_t i;
20  size_t ind;
21 
22  i = 0;
23  while (i < old_capacity)
24  {
25  if (old_keys[i] != NULL)
26  {
27  hashmap_put(hm, old_keys[i], old_vals[i]);
28  hm->key_type->del(old_keys[i]);
29  hm->val_type->del(old_vals[i]);
30  }
31  i++;
32  }
33  free(old_keys);
34  free(old_vals);
35 }
36 
37 void hashmap_grow(t_hashmap *hm)
38 {
39  void **old_keys;
40  void **old_vals;
41  size_t old_capacity;
42 
43  old_keys = hm->keys;
44  old_vals = hm->vals;
45  old_capacity = hm->capacity;
46  hm->keys = ds_xcalloc(sizeof(void *), hm->capacity * 2);
47  hm->vals = ds_xcalloc(sizeof(void *), hm->capacity * 2);
48  hm->capacity *= 2;
49  hashmap_rehash(hm, old_keys, old_vals, old_capacity);
50  free(old_keys);
51  free(old_vals);
52 }
53 
54 void hashmap_shrink(t_hashmap *hm)
55 {
56  void **old_keys;
57  void **old_vals;
58  size_t old_capacity;
59 
60  old_keys = hm->keys;
61  old_vals = hm->vals;
62  old_capacity = hm->capacity;
63  hm->keys = ds_xcalloc(sizeof(void *), hm->size * 2);
64  hm->vals = ds_xcalloc(sizeof(void *), hm->size * 2);
65  hm->capacity = hm->size * 2;
66  hashmap_rehash(hm, old_keys, old_vals, old_capacity);
67  free(old_keys);
68  free(old_vals);
69 }
hashmap_utils.h
s_hashmap::key_type
const t_type * key_type
The type of keys in the hashmap.
Definition: hashmap.h:54
hashmap_put
void hashmap_put(t_hashmap *hm, const void *key, const void *val)
Adds a key-value pair to the symbol table.
Definition: hashmap_put.c:17
s_hashmap::size
size_t size
The number of elements in the hashmap.
Definition: hashmap.h:52
ds_xcalloc
void * ds_xcalloc(size_t count, size_t size)
Replicates behaviour of calloc from libc, but fails on memory allocation errors.
Definition: ds_xcalloc.c:22
s_hashmap::keys
void ** keys
The keys.
Definition: hashmap.h:50
s_hashmap
A symbol table of generic key-value pairs, implemented as a dynamically resizing linear-probing hashm...
Definition: hashmap.h:48
s_type::del
void(* del)(void *)
A function pointer used to free the memory taken by the data type.
Definition: types.h:51
s_hashmap::val_type
const t_type * val_type
The type of values in the hashmap.
Definition: hashmap.h:55
s_hashmap::capacity
size_t capacity
The current capacity of the hashmap.
Definition: hashmap.h:53
s_hashmap::vals
void ** vals
The values.
Definition: hashmap.h:51