summaryrefslogtreecommitdiff
path: root/array.c
blob: d8765c140d5e03f46f6dd56047ae5bd45536df15 (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
#include "array.h"
#include "crash.h"
#include <string.h>

#define CRASH_IF_OOB(array, idx) {\
    if (idx >= array->length)\
        crash("Array access out of bounds: %ld >= %ld\n", idx, array->length);\
}

void* array_at(const array_t* array, size_t idx) {
    CRASH_IF_OOB(array, idx);
    return (char*)array->__data + idx*array->elemsz;
}

char* str_at(const str_t* str, size_t idx) {
    CRASH_IF_OOB(str, idx);
    return str->__data + idx;
}

str_t str_slice(const str_t* str, size_t start, size_t length) {
    CRASH_IF_OOB(str, start + length - 1);
    str_t slice = {.length = length, .__data = str->__data + start};
    return slice;
}

void str_c_str(
    char* dst,
    size_t dst_size,
    const str_t* src
) {
    if (src->length >= dst_size)
        crash(
            "String is too long to hold in C string buffer: %ld >= %ld\n",
            src->length,
            dst_size);

    memmove(dst, src->__data, src->length);
    dst[src->length] = 0;
}