aboutsummaryrefslogtreecommitdiff
path: root/src/list.cc
blob: 4518d8916efc2ded638bb6d4b90396549f63e9ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <list.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void
List::init(size_t element_size)
{
  this->element_size = element_size;
  current = 0;
  max = START_SIZE;
  elements = (uint8_t *) calloc(max, element_size);
}

void
List::add(void *element)
{
  if (current == max) {
    max += INCREMENT_BY;
    elements = (uint8_t *) realloc(elements, element_size * max);
    if (elements == NULL) {
      /* TODO: Handle error */
      printf("Failed to reallocate array\n");
      return;
    }
  }

  void *new_element = elements + element_size * current;
  new_element = memcpy(new_element, element, element_size);

  if (new_element == NULL)
    printf("Failed to add a new element\n");

  current++;
}

void *
List::get(size_t i)
{
  return elements + (i * element_size);
}

void
List::clean(void)
{
  free(elements);
}