data_structures
hashset_utils.c
Go to the documentation of this file.
1 /* ************************************************************************** */
3 /* */
4 /* ::: :::::::: */
5 /* hashset_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:56:27 by unite ### ########.fr */
11 /* */
12 /* ************************************************************************** */
13 
14 #include "hashset_utils.h"
15 
16 void hashset_rehash(t_hashset *hs, void **old_vals, size_t old_capacity)
17 {
18  size_t i;
19  size_t ind;
20 
21  i = 0;
22  while (i < old_capacity)
23  {
24  if (old_vals[i] != NULL)
25  {
26  hashset_put(hs, old_vals[i]);
27  hs->type->del(old_vals[i]);
28  }
29  i++;
30  }
31  free(old_vals);
32 }
33 
34 void hashset_grow(t_hashset *hs)
35 {
36  void **old_vals;
37  size_t old_capacity;
38 
39  old_vals = hs->vals;
40  old_capacity = hs->capacity;
41  hs->vals = ds_xcalloc(sizeof(void *), hs->capacity * 2);
42  hs->capacity = hs->capacity * 2;
43  hashset_rehash(hs, old_vals, old_capacity);
44  free(old_vals);
45 }
46 
47 void hashset_shrink(t_hashset *hs)
48 {
49  void **old_vals;
50  size_t old_capacity;
51 
52  old_vals = hs->vals;
53  old_capacity = hs->capacity;
54  hs->vals = ds_xcalloc(sizeof(void *), hs->size * 2);
55  hs->capacity = hs->size * 2;
56  hashset_rehash(hs, old_vals, old_capacity);
57  free(old_vals);
58 }
s_hashset::capacity
size_t capacity
The current capacity of the hashset.
Definition: hashset.h:47
hashset_put
void hashset_put(t_hashset *hs, const void *val)
Adds a copy of the specified element to the hashset.
Definition: hashset_put.c:17
hashset_utils.h
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_hashset::vals
void ** vals
The data.
Definition: hashset.h:45
s_hashset::size
size_t size
The number of elements in the hashset.
Definition: hashset.h:46
s_type::del
void(* del)(void *)
A function pointer used to free the memory taken by the data type.
Definition: types.h:51
s_hashset
A dynamically resizing linear-probing hashset.
Definition: hashset.h:43
s_hashset::type
const t_type * type
The type of elements in the hashset.
Definition: hashset.h:48