caos-with-snake/snake/misc_utils.h

92 lines
2.1 KiB
C

#pragma once
#include "../syscall.h"
#include <stdbool.h>
#include <stdint.h>
void _Noreturn panic(const char *message) {
syscall(SYS_switch_to_text, 0); // ???
syscall(SYS_puts, (uintptr_t)message);
syscall(SYS_exit, 1);
__builtin_unreachable();
}
#define check(expr) \
if (!(expr)) { \
panic("Assertion failed at " __FILE__ ": " #expr "\n"); \
}
typedef struct {
int x, y;
} ivec2;
void *memcpy(void *dst, const void *src, uint32_t size) {
uint8_t *d = (uint8_t *)dst;
const uint8_t *s = (const uint8_t *)src;
for (uint32_t i = 0; i < size; i++) {
d[i] = s[i];
}
return dst;
}
void *memset(void *dst, int value, uint32_t size) {
uint8_t *d = (uint8_t *)dst;
uint8_t byte = (uint8_t)value;
for (uint32_t i = 0; i < size; i++) {
d[i] = byte;
}
return dst;
}
#define STRING_BUILDER_CAPACITY 150
typedef struct {
char buf[STRING_BUILDER_CAPACITY];
int len;
} StringBuilder;
void StringBuilder_putc(StringBuilder *self, char ch) {
if (self->len + 1 > STRING_BUILDER_CAPACITY) {
panic("string builder\n");
}
self->buf[self->len++] = ch;
}
void StringBuilder_append_cstr(StringBuilder *self, const char *str) {
for (const char *p = str; *p; p++) {
StringBuilder_putc(self, *p);
}
}
void StringBuilder_append_u32(StringBuilder *self, uint32_t x) {
char b[11];
int len = 0;
if (x == 0) {
b[len++] = '0';
} else {
while (x > 0) {
b[len++] = (char)('0' + (x % 10));
x /= 10;
}
int i = 0, j = len - 1;
while (i < j) {
char tmp = b[i];
b[i] = b[j];
b[j] = tmp;
i++;
j--;
}
}
b[len] = 0;
StringBuilder_append_cstr(self, b);
}
const char *StringBuilder_get_cstr(StringBuilder *self) {
StringBuilder_putc(self, 0);
return self->buf;
}
uint32_t time_ms(void) { return (uint32_t)syscall(SYS_time_ms, 0); }