summaryrefslogtreecommitdiff
path: root/pit/include/lcq/pit/utils.h
blob: d45758ffdaa02ea0617f5cbe660e1387b86258e1 (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
#ifndef LCOLONQ_PIT_UTILS_H
#define LCOLONQ_PIT_UTILS_H

#include <stdarg.h>
#include <lcq/pit/types.h>

/* macro helpers */
#define PIT_CONCAT(a, b) a ## b
#define PIT_STRSTR(x) #x
#define PIT_STR(x) PIT_STRSTR(x)

/* implementations of needed libc functions */
/* ctype */
static inline bool pit_libc_ctype_isdigit(int a) { return a >= '0' && a <= '9'; }
static inline bool pit_libc_ctype_islower(int a) { return a >= 'a' && a <= 'z'; }
static inline bool pit_libc_ctype_isupper(int a) { return a >= 'A' && a <= 'Z'; }
static inline bool pit_libc_ctype_isalpha(int a) { return pit_libc_ctype_islower(a) || pit_libc_ctype_isupper(a); }
static inline bool pit_libc_ctype_isprint(int a) { return a >= 0x20 && a <= 0x7f; }
static inline bool pit_libc_ctype_isspace(int a) { return a == ' ' || a == '\r' || a == '\n' || a == '\t'; }

/* string */
static inline size_t pit_libc_string_strlen(char *s) {
    size_t idx = 0;
    while (s[idx] != 0) ++idx;
    return idx;
}
static inline u64 pit_string_hash(char *x) {
    if (x == NULL) return 0;
    u64 ret = 0;
    while (*x != 0) {
        u64 new = (ret << 6) + (ret << 16) - ret;
        ret = (u64) *x++ + (u64) new;
    }
    return ret;
}
static inline bool pit_string_equal(char *x, char *y) {
    if (x == NULL && y == NULL) return true;
    if (x == NULL || y == NULL) return false;
    while (*x != 0 && *y != 0) if (*x++ != *y++) return false;
    return *x == *y;
}
static inline u8 *pit_libc_string_memcpy(u8 *dest, u8 *src, size_t n) {
    size_t i = 0;
    for (; i < n; ++i) dest[i] = src[i];
    return dest;
}

/* printf */
typedef struct {
    char specifier;
    i64 (*callback)(va_list ap, char *buf, size_t len, void *data);
} pit_printf_handler;
int pit_vsnprintf_helper(char *buf, size_t len, char *format, va_list ap, pit_printf_handler *handlers, i64 handlers_len, void *data);
int pit_libc_string_vsnprintf(char *str, size_t size, char *format, va_list ap);
int pit_libc_string_snprintf(char *buf, size_t len, char *format, ...);

/* assorted utilities and debugging tools */
#define pit_mul(result, a, b) *result = (i64) (a) * (i64) (b)
static inline i64 pit_mod(i64 x, i64 m) { return (m + (x % m)) % m; }

#endif