Repository navigation
Expand file tree
/
Copy pathcontainers.h
More file actions
95 lines (78 loc) · 2.97 KB
/
Copy pathcontainers.h
File metadata and controls
95 lines (78 loc) · 2.97 KB
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
#pragma once
#include <memory.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
typedef struct vector {
void *data;
size_t size;
size_t capacity;
} vector;
static void vector_grow(vector *vec, size_t type_size) {
size_t new_capacity = vec->capacity ? vec->capacity * 2 : 1;
vec->data = realloc(vec->data, new_capacity * type_size);
vec->capacity = new_capacity;
}
#define vector_at(type, vec, index) ((type *)((vec)->data))[index]
#define vector_last(type, vec) ((type *)((vec)->data))[((vec)->size) - 1]
#define vector_push(type, vec, value) \
do { \
if ((vec)->size >= (vec)->capacity) { \
vector_grow((vec), sizeof(type)); \
} \
vector_at(type, vec, (vec)->size++) = value; \
} while (0)
#define vector_remove(type, vec, index) \
do { \
memmove(&vector_at(type, (vec), (index)), \
&vector_at(type, (vec), (index) + 1), \
sizeof(type) * ((vec)->size - (index)-1)); \
(vec)->size--; \
} while (0)
typedef struct string {
char *data;
size_t length;
} string;
#define string_literal(str) ((string){.data = str, .length = sizeof(str) - 1})
#define invalid_length ((size_t)-1)
#define invalid_str ((string){.data = NULL, .length = invalid_length})
static inline bool string_equal(string a, string b) {
if (a.length != b.length)
return false;
return memcmp(a.data, b.data, a.length) == 0;
}
static inline bool string_is_valid(string str) {
return str.data != NULL && str.length != invalid_length;
}
typedef struct source_entry {
string source;
size_t i;
struct source_entry *next;
} source_entry;
static inline void advance(source_entry **entry) {
(*entry)->i++;
if ((*entry)->i >= (*entry)->source.length) {
*entry = (*entry)->next;
}
}
static inline bool inplace_advance(source_entry *_entry) {
source_entry *entry = _entry;
advance(&_entry);
if (_entry != NULL)
return false;
*entry = *_entry;
return true;
}
typedef struct span {
void *data;
size_t size;
} span;
typedef struct owned_span {
void *data;
size_t size;
} owned_span;
#define make_owned_span(ty, size) \
((owned_span){.data = malloc((size) * sizeof(ty)), .size = (size)})
// could be worth realloc'ing down to the final size
#define owned_span_from_vector(vec) \
((owned_span){.data = (vec).data, .size = (vec).size})