summaryrefslogtreecommitdiff
path: root/src/common.cc
diff options
context:
space:
mode:
authorFabrice <fabrice@schaub-dev.xyz>2026-03-02 11:59:47 +0100
committerFabrice <fabrice@schaub-dev.xyz>2026-03-02 11:59:47 +0100
commitb0d5c39d8acbd1429990e383ddd67226fc7bc0f9 (patch)
tree0f4ad595859fc4c26460da258dca63c80970f7bb /src/common.cc
parenta07e37de3f2b56b577da32b33d3dec45e0cd43b6 (diff)
working on source control
Diffstat (limited to 'src/common.cc')
-rw-r--r--src/common.cc75
1 files changed, 68 insertions, 7 deletions
diff --git a/src/common.cc b/src/common.cc
index ef790b2..141b079 100644
--- a/src/common.cc
+++ b/src/common.cc
@@ -1,8 +1,10 @@
#ifndef COMMON_CC
#define COMMON_CC
+#include <cstdarg>
#include <cstdint>
#include <cstdio>
+#include <cstdlib>
/* typedefs for common types */
@@ -19,9 +21,36 @@ typedef int64_t i64;
typedef uintptr_t usize;
typedef intptr_t isize;
+/* intrinsics */
+#define likely(cond) __builtin_expect(!!(cond), 1)
+#define unlikely(cond) __builtin_expect(!!(cond), 0)
+
+/* error handling sort of */
+[[noreturn]] void panic_impl(const char* file, i32 line, const char* fmt, ...) {
+ fprintf(stderr, "PANIC at %s:%d: ", file, line);
+
+ va_list args;
+ va_start(args, fmt);
+ vfprintf(stderr, fmt, args);
+ va_end(args);
+
+ fputc('\n', stderr);
+ fflush(stderr);
+ abort();
+}
+
+#define panic(fmt, ...) panic_impl(__FILE__, __LINE__, fmt, __VA_ARGS__)
+#define spanic(msg) panic("%s", msg)
+
+#undef assert
+#define assert(cond) \
+ do { \
+ if (unlikely(!(cond))) panic("assertion failed: %s", #cond); \
+ } while (0)
+
/* slice and string handling */
-template<typename T>
+template <typename T>
struct Slice {
T* ptr;
usize length;
@@ -30,21 +59,53 @@ struct Slice {
Slice(T* ptr, usize length) : ptr(ptr), length(length) {}
T* operator[](usize index) {
- return ptr + index;
+ assert(index < this->length);
+ return this->ptr + index;
}
- inline usize size() const {
- return this->length * sizeof(T);
+ const T* operator[](usize index) const {
+ assert(index < this->size());
+ return this->ptr + index;
}
+
+ inline usize size() const { return this->length * sizeof(T); }
};
-template<typename T>
+template <typename T>
bool slice_write(const Slice<T>* slice, FILE* stream) {
usize rc = fwrite(slice->ptr, sizeof(T), slice->length, stream);
- if(rc == 0 || slice->size() > rc) return false;
+ if (rc == 0 || slice->size() > rc) return false;
return true;
-}
+}
typedef Slice<const u8> String;
+/* linked list */
+
+struct Link {
+ Link* next;
+ Link* prev;
+
+ Link(Link* next, Link* prev) : next(next), prev(prev) {}
+};
+
+struct List {
+ Link head;
+ Link tail;
+};
+
+static inline void link_after(Link* prev, Link* nlink) {
+ assert(prev != nullptr);
+ assert(nlink != nullptr);
+
+ Link* next = prev->next;
+
+ nlink->prev = prev;
+ nlink->next = next;
+ prev->next = nlink;
+
+ if(next == nullptr) return;
+ next->prev = nlink;
+}
+
#endif