aboutsummaryrefslogtreecommitdiff
path: root/src/stdlib/util.h
blob: 8341fee544ef3ddef433ff3d12ec447556e8a55d (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
// Built-in utility functions

#pragma once

#include <assert.h>
#include <err.h>
#include <stdbool.h>
#include <string.h>

#define streq(a, b) (((a) == NULL && (b) == NULL) || (((a) == NULL) == ((b) == NULL) && strcmp(a, b) == 0))
#define starts_with(line, prefix) (strncmp(line, prefix, strlen(prefix)) == 0)
#define ends_with(line, suffix)                                                                                        \
    (strlen(line) >= strlen(suffix) && strcmp(line + strlen(line) - strlen(suffix), suffix) == 0)
#define check_initialized(var, init_var, name)                                                                         \
    *({                                                                                                                \
        if (!init_var) fail_text(Text("The variable " name " is being accessed before it has been initialized!"));     \
        &var;                                                                                                          \
    })

#define WHEN(type, subj, var, body)                                                                                    \
    {                                                                                                                  \
        type var = subj;                                                                                               \
        switch (var.$tag)                                                                                              \
            body                                                                                                       \
    }

#ifndef public
#define public __attribute__((visibility("default")))
#endif

#ifndef PUREFUNC
#define PUREFUNC __attribute__((pure))
#endif

#ifndef CONSTFUNC
#define CONSTFUNC __attribute__((const))
#endif

#ifndef INLINE
#define INLINE inline __attribute__((always_inline))
#endif

#ifndef likely
#define likely(x) (__builtin_expect(!!(x), 1))
#endif

#ifndef unlikely
#define unlikely(x) (__builtin_expect(!!(x), 0))
#endif

// GCC lets you define macro-like functions which are always inlined and never
// compiled using this combination of flags. See: https://gcc.gnu.org/onlinedocs/gcc/Inline.html
#ifndef MACROLIKE
#ifdef __TINYC__
#define MACROLIKE static inline __attribute__((gnu_inline, always_inline))
#else
#define MACROLIKE extern inline __attribute__((gnu_inline, always_inline))
#endif
#endif

#ifndef GC_MALLOC
extern void *GC_malloc(size_t);
#define GC_MALLOC GC_malloc
#define heap(x) (__typeof(x) *)memcpy(GC_malloc(sizeof(x)), (__typeof(x)[1]){x}, sizeof(x))
#define stack(x) (__typeof(x) *)((__typeof(x)[1]){x})
#endif