aboutsummaryrefslogtreecommitdiff
path: root/std.h
blob: bd385ea8bf459aa795e24352216e61943a9273ac (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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/* See copyright information at the end of the file */

/*! @file std.h
 * @brief Mario Forzanini's "standard" library
 */

#ifndef __STD_H__
#define __STD_H__

#include <stdbool.h>
#include <stdio.h>

#ifndef STD_MALLOC
#include <stdlib.h>
/*! malloc(3) compatible function to use to allocate memory. */
#define STD_MALLOC(size) (malloc(size))
#define STD_FREE(size) (free(size))
#endif /* STD_MALLOC */

#ifndef STD_FREE
#error "You should define STD_FREE if you provide a custom definition of STD_MALLOC"
#endif /* STD_FREE */

#ifndef STD_ERROR
#include <stdio.h>
#include <stdlib.h>
/*! Function to use to report errors, by default will call exit(3). */
#define STD_ERROR(...)                                                       \
	do {                                                                 \
		fprintf(stderr, __VA_ARGS__);                                \
		exit(EXIT_FAILURE);                                          \
	} while (0)
#endif /* STD_ERROR */

#ifndef STD_ASSERT
#include <assert.h>
/*! assert(3) compatible function. */
#define STD_ASSERT(...) assert(__VA_ARGS__)
#endif /* STD_ASSERT */

#define STD_UNREACHABLE() STD_ASSERT(0 && "Unreachable")

#define KB (1024)
#define MB (1024 * 1024)
#define LEN(x) (sizeof(x) / sizeof(x[0]))
#define UNUSED(x) ((void)x)
#define STRLEN(str) (LEN(str) - 1)

#if defined(__SSE__) || defined(__SSE2__) || defined(__SSE3__)               \
        || defined(STD_THREAD)
#include <immintrin.h>
#endif /* __SSE__ */

#define STD_TODO(str) STD_ASSERT(0 && "TODO: " str)

#define global_var static
#define internal static
#define local_persist static

typedef struct MemPool MemPool;
typedef struct Region Region;
typedef struct String String;
typedef struct StrView StrView;

/*! Pool allocator */
struct MemPool {
	Region *r;
	size_t len;        /*!< Number of allocated elements */
	size_t capacity;   /*!< Total number of elements in the pool */
	size_t chunk_size; /*!< Size of a single element */
	void *buf;         /*!< The buffer in which allocations are stored */
};

/*! Arena allocator */
struct Region {
	void *buf;          /*!< The buffer in which allocations are stored */
	size_t bcap, bsize; /*!< capacity and occupied size, in bytes */
	Region *next;       /*!< Singly-linked list of regions */
};

/*! Owned string */
struct String {
	char *buf;  /*!< Data buffer containing the string */
	size_t len; /*!< Length of string */
	size_t cap; /*!< Capacity of the buffer */
};

/*! Immutable slice into a string */
struct StrView {
	const char *str; /*!< Pointer to the beginning of the string */
	size_t len;      /*!< Length of the slice */
};

#define String_Fmt "%.*s"
#define String_Arg(s) (int)s.len, (s).buf

/*! Use this in format strings to print StrViews */
#define StrView_Fmt "%.*s"
/*! Use this in format arguments to print StrView_Fmt.
 * e.g.
 * @code
 * StrView to_print = STRVIEW_STATIC("blabla");
 * printf(StrView_Fmt, StrView_Arg(to_print));
 * @endcode
 */
#define StrView_Arg(s) (int)(s).len, (s).str
#define STRVIEW_STATIC(str)                                                  \
	{                                                                    \
		str, sizeof(str) / sizeof(char) - 1                          \
	}
#define STRVIEW_LITERAL(s)                                                 \
	(StrView) { .len = sizeof(s) / sizeof(char) - 1, .str = (s) }
#define STRVIEW_FROM_STRING(string) *(StrView *)&(string)

/*! Copy a file.
 *
 * @param src Name of the file to copy.
 * @param dst File to copy to.
 * @return errno(3)
 */
int cp(const char src[static restrict 1], const char dst[static restrict 1]);
void *ecalloc(size_t nmemb, size_t size);
void *emalloc(size_t size);

/*! Allocate a string.
 *
 * @param r Region to use
 * @param len Length of the backing buffer
 * @return a zero-initialized, owned string.
 */
String string_alloc(Region *r, size_t len);
String string_concat(Region *r, String a, String b);
/*! Copy a string.
 *
 * @param r Region to use
 * @param src String to be copied
 * @return An exact copy of src into a newly allocated string.
 */
String string_copy(Region *r, String src);
/*! Copy NULL-terminated string into an owned String.
 *
 * @param r Region to use
 * @param str NULL-terminated string to copy
 * @param len strlen(str)
 * @return An exact copy of str into a newly allocated string.
 */
String string_from_cstr(Region *r, const char *str, size_t len);
/*! Copy StrView into an owned String.
 *
 * @param r Region to use
 * @param str StrView that has to be copied
 * @return An exact copy of str into a newly allocated String.
 */
String string_from_strview(Region *r, const StrView str);
void string_downcase(String str);
/*! Read the whole contents of a stream into a String.
 *
 * @param r Region on which to allocate the string.
 * @param stream File stream to read from.
 * @param contents pointer to the string to fill.
 * @return false on error, setting errno(3).
 *
 * @warning This does not work for non seekable files.
 */
bool string_read(
        Region *r, FILE stream[static 1], String contents[static 1]);

/* StrView functions */
StrView strview_from_string(const String str);
StrView strview_from_cstr(char *cstr);
bool strview_is_null(StrView);
StrView make_strview(size_t, const char *);
/*! Acts like strcmp(3) on s1 and s2. */
int strview_cmp(StrView s1, StrView s2);
bool strview_contains(const StrView s, const char *charbag, const size_t len);
/*! Checks whether str ends with end. */
bool strview_ends_with(StrView end, StrView str);
/*! Return next line in StrView.
 *
 * Cannot be used to count the number of lines in a file as it will
 * skip empty lines.
 *
 * @see strview_next_tok
 * @param str StrView to tokenize.
 * @todo handle CRLF
 */
StrView strview_next_line(StrView str[static 1]);
/*! Return next word in StrView.
 *
 * @see strview_next_tok
 * @param str StrView to tokenize.
 */
StrView strview_next_word(StrView str[static 1]);
/*! Tokenize str based on delim, and return the next token.
 *
 * Multiple delimiters are skipped and produce only two tokens, e.g.:
 *
 * @code
 * StrView str = STRVIEW_STATIC("a  b    c");
 * StrView tok1 = strview_next_tok(&str, ' ');
 * StrView tok2 = strview_next_tok(&str, ' ');
 * StrView tok3 = strview_next_tok(&str, ' ');
 * @endcode
 *
 * tok1 == (StrView){.count = 1, .str = "a"};
 * tok2 == (StrView){.count = 1, .str = "b"};
 * tok3 == (StrView){.count = 1, .str = "c"};
 *
 * @param str The string to modify.
 * @param delim The delimiter to look for when tokenizing.
 * @return The next token found until delim, or a StrView where .str = NULL.
 * Note that after the execution str will point to the character after the
 * delimiter.
 */
StrView strview_next_tok(StrView str[static 1], char delim);
/*! Read the whole contents of a stream into a StrView.
 *
 * @param r Region on which to allocate the string.
 * @param stream File stream to read from.
 * @param contents pointer to the string to fill.
 * @return false on error, setting errno(3).
 *
 * @warning This does not work for non seekable files.
 */
bool strview_read(
        Region *r, FILE stream[static 1], StrView contents[static 1]);
/*! Read the whole file into a StrView.
 *
 * @see strview_read
 */
bool strview_read_file(
        Region *r, const char filename[static 1], StrView contents[static 1]);
/*! Check whether str starts with start. */
bool strview_starts_with(StrView start, StrView str);
/*! Strip the first n characters off of a StrView.
 *
 * @param str pointer to StrView to modify.
 * @param n Number of characters to consume.
 * @return The first n characters of str, or less if str is not long
 * enough.
 */
StrView strview_take(StrView str[static 1], size_t n);
/*! Remove whitespace from StrView.
 *
 * @param str Input StrView to be modified.
 */
void strview_trim(StrView str[static 1]);
/*! Remove leading or trailing characters from StrView.
 *
 * @param str Input StrView to be modified.
 * @param charbag String of characters to be removed
 * @param len Length of charbag
 */
void strview_trim_chars(
        StrView s[static 1], const char *charbag, const size_t len);
/*! Behaves like strcat(3) for StrViews.
 *
 * @param r Region in which to allocate the result
 * @param x First string to concatenate.
 * @param y Second string to concatenate.
 * @return Concatenation of x and y, allocated on r.
 */
StrView strview_strcat(Region *r, StrView x, StrView y);
/*! Convert StrView to int.
 *
 * @warning First converts to long, it may truncate the result.
 * @param[in] str StrView to convert.
 * @param[out] i Pointer to the result.
 * @return true if no error occurred, false otherwise (check errno(3)).
 */
bool strview_strtoi(StrView str, int i[static 1]);
/*! Convert StrView to unsigned long.
 *
 * @param[in] str StrView to convert.
 * @param[out] ul Pointer to the result.
 * @return true if no error occurred, false otherwise (check errno(3)).
 */
bool strview_strtoul(StrView str, unsigned long ul[static 1]);
/*! Convert StrView to long.
 *
 * @param[in] str StrView to convert.
 * @param[out] l Pointer to the result.
 * @return true if no error occurred, false otherwise (check errno(3)).
 */
bool strview_strtol(StrView str, long l[static 1]);
/*! Convert StrView to double.
 *
 * @param[in] str StrView to convert.
 * @param[out] d Pointer to the result.
 * @return true if no error occurred, false otherwise (check errno(3)).
 */
bool strview_strtod(StrView str, double d[static 1]);

/* Region functions */
/*! Allocate linear allocator in a heap buffer.
 * @param bcap Capacity in bytes.
 * @return Heap allocated, zero-initialized, empty Region.
 */
Region *region_alloc(size_t bcap);
/*! Allocate memory in region r.
 *
 * Note that if the requested size is bigger that the region's
 * capacity, a new node in the linked list of regions is allocated
 * using region_alloc.
 * @see region_alloc
 * @see Region
 *
 * @warning Allocates memory aligned to sizeof(void *).
 * @param r Region to allocate on.
 * @param bsize Size of needed space in bytes.
 * @return Pointer to the allocated buffer.
 */
void *region_malloc(void *r, size_t bsize);
/*! Reset a region to it's initial state.
 *
 * @warning Does not zero the memory, in this sense the region will
 * not be exactly in its initial state.
 * @param r Region to reset.
 */
void region_reset(Region *r);
/*! Free heap allocated region.
 * @see region_alloc
 */
void region_free(Region *r);

/* Pool functions */
/*! Allocate pool allocator in a heap buffer.
 * @param count Number of elements in the pool.
 * @param chunk_size Size of each element in the pool;
 * @return Heap allocated, zero-initialized, empty Region.
 */
MemPool pool_alloc(Region *r, size_t count, size_t chunk_size);
/*! Free all of the elements in the pool allocator. */
void pool_free_all(MemPool *pool);
/*! Allocate an element from the pool allocator. */
void *pool_malloc(MemPool *pool);
/*! Free heap allocated memory pool.
 * @see pool_alloc
 */
void pool_free(MemPool *pool);
void pool_reset(MemPool *pool);
#endif /* __STD_H__ */

/*
 * Copyright ©️ 2023 Mario Forzanini <mf@marioforzanini.com>
 *
 * This file is part of my bachelor thesis.
 *
 * This file 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.
 *
 * This file 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 this file. If not, see <https://www.gnu.org/licenses/>.
 *
 */