~schnouki/pustule

ref: 2e90522e70214bb6d1bb88aef6f7d8c06152a99f pustule/dyn_array.c -rw-r--r-- 2.0 KiB
2e90522e — Thomas Jost Expose log functions in Lua 10 months ago
                                                                                
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
/**
 * pustule
 * Copyright 2014-2020 Thomas Jost <schnouki@schnouki.net>
 *
 * This file is part of pustule.
 *
 * pustule is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * pustule is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * pustule. If not, see <http://www.gnu.org/licenses/>.
 */

#define _GNU_SOURCE
#include <stdbool.h>
#include <stdlib.h>

#include "log.h"
#include "pustule.h"

#define DEFAULT_SIZE 4
#define DEFAULT_SIZE_INCR 4


void array_init(array_t* arr) {
    intptr_t* ptr = malloc(sizeof(intptr_t) * DEFAULT_SIZE);
    if (!ptr) {
        log_fatal("Could not allocate memory");
        exit(1);
    }

    arr->capacity = DEFAULT_SIZE;
    arr->size = 0;
    arr->array = ptr;
}


void array_push(array_t* arr, intptr_t value) {
    if (arr->size >= arr->capacity) {
        intptr_t* ptr = realloc(arr->array, sizeof(intptr_t) * (arr->capacity + DEFAULT_SIZE_INCR));
        if (!ptr) {
            log_fatal("Could not reallocate memory");
            exit(1);
        }
        arr->array = ptr;
        arr->capacity += DEFAULT_SIZE_INCR;
    }

    arr->array[arr->size++] = value;
}

bool array_find(array_t* arr, intptr_t value, size_t* idx) {
    for (size_t i = 0; i < arr->size; i++) {
        if (arr->array[i] == value) {
            if (idx)
                *idx = i;
            return true;
        }
    }
    return false;
}

void array_remove(array_t* arr, intptr_t value) {
    size_t idx;
    bool found = array_find(arr, value, &idx);
    if (!found)
        return;

    for (size_t i = idx; i < arr->size - 1; i++) {
        arr->array[i] = arr->array[i+1];
    }
    arr->size -= 1;
}