aboutsummaryrefslogtreecommitdiff
path: root/src/ivec.c
blob: 9c0dd95db891fbabbbe9995bda6f43ec9f5def3a (plain) (blame)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "ivec.h"
#include <stdio.h>
#include <stdlib.h>

void iv_free(ivec *v) {
  free(v->_data);
  v->_data = NULL;
  v->_cap = 0;
  v->len = 0;
}

static void _iv_ensure_init(ivec *v) {
  if (v->_data)
    return;

  v->_cap = 16;
  v->len = 0;

  v->_data = malloc(v->_cap * sizeof(long long));
  if (!v->_data) {
    perror("_v_ensure_init.malloc");
    abort();
  }
}

static void _iv_ensure_capacity(ivec *v) {
  _iv_ensure_init(v);

  if (v->len >= v->_cap) {
    v->_cap = (v->_cap == 0) ? 16 : v->_cap * 2;

    long long *tmp = realloc(v->_data, v->_cap * sizeof(long long));
    if (!tmp) {
      perror("_v_ensure_capacity.realloc");
      abort();
    }

    v->_data = tmp;
  }
}

size_t iv_push(ivec *v, long long data) {
  _iv_ensure_capacity(v);

  v->_data[v->len++] = data;
  return v->len - 1;
}

// getter
long long iv_get(ivec *v, size_t idx) {
  _iv_ensure_init(v);

  if (idx < v->len) {
    return v->_data[idx];
  }

  return 0;
}

// O(n) shift delete
long long iv_rem_shift(ivec *v, size_t idx) {
  _iv_ensure_init(v);

  if (idx >= v->len)
    return 0;

  int old = v->_data[idx];

  for (size_t j = idx; j + 1 < v->len; j++) {
    v->_data[j] = v->_data[j + 1];
  }

  v->len--;
  return old;
}

// O(1) swap delete
long long iv_rem(ivec *v, size_t idx) {
  _iv_ensure_init(v);

  if (idx >= v->len)
    return 0;

  int old = v->_data[idx];
  v->_data[idx] = v->_data[--v->len];
  return old;
}

// search
long long iv_has(ivec *v, long long x,
                 int (*comp)(const long long, const long long)) {
  _iv_ensure_init(v);

  if (!comp)
    return 0;

  for (size_t i = 0; i < v->len; i++) {
    if (comp(v->_data[i], x) == 0) {
      return v->_data[i];
    }
  }

  return 0;
}

void iv_shrink(ivec *v) {
  _iv_ensure_init(v);

  size_t new_cap = v->len ? v->len : 1;

  long long *tmp = realloc(v->_data, new_cap * sizeof(int)); // FIX
  if (!tmp) {
    perror("v_shrink.realloc");
    abort();
  }

  v->_cap = new_cap;
  v->_data = tmp;
}