#ifndef CORE_HPP #define CORE_HPP #include #include #include #include #if ENVIRONMENT_WINDOWS #include "Windows.h" #endif #if ENVIRONMENT_LINUX #include #include #endif // ### Misc macros ### #if SLOWMODE #define Assert(expression) if (!(expression)) {*(volatile int *)0 = 0;} #else #define Assert(expression) #endif // ### Types ### typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; typedef uint8_t byte; typedef float real32; typedef double real64; // ### Sizes and Numbers ### #define Bytes(n) (n) #define Kilobytes(n) (n << 10) #define Megabytes(n) (n << 20) #define Gigabytes(n) (((uint64)n) << 30) #define Terabytes(n) (((uint64)n) << 40) #define Thousand(n) ((n)*1000) #define Million(n) ((n)*1000000) #define Billion(n) ((n)*1000000000LL) #define ArrayCount(arr) (sizeof(arr) / sizeof((arr)[0])) // ### Arenas ### struct Arena { void *memory; size_t capacity; size_t head; }; void *pushSize(Arena *arena, size_t bytes) { if (arena->capacity - arena->head >= bytes) { void *ptr = (char *)arena->memory + arena->head; arena->head += bytes; return ptr; } return 0; } #define PushArray(arena, type, size) (type *)pushSize(arena, sizeof(type) * (size)) #define PushStruct(arena, type) (type *)pushSize(arena, sizeof(type)) Arena *arenaAlloc(size_t capacity) { #if ENVIRONMENT_WINDOWS Arena *result = (Arena *)VirtualAlloc(NULL, sizeof(Arena) + capacity, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); #endif #if ENVIRONMENT_LINUX Arena *result = (Arena *)mmap(0, capacity, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); #endif result->memory = result + sizeof(Arena); result->capacity = capacity; result->head = 0; return result; } void arenaFree(Arena *arena) { #if ENVIRONMENT_WINDOWS VirtualFree(arena, NULL, MEM_RELEASE); #endif #if ENVIRONMENT_LINUX // TODO(dledda): implement this for Linux #endif } // ### Lists ### template struct list { T* data; size_t capacity; size_t length; }; #define PushList(arena, type, size) (list{ PushArray(arena, type, size), size, 0 }) #define PushFullList(arena, type, size) (list{ PushArray(arena, type, size), size, size }) #define EachIn(list, it) size_t it = 0; it < list.length; it++ #define EachInReversed(list, it) size_t it = list.length - 1; it >= 0 && it < list.length; it-- // TODO(dledda): test assignment in for loop? #define EachInArray(arr, it) size_t it = 0; it < ArrayCount(arr); ++it template T *appendList(list *list, T element) { if (list->length < list->capacity) { list->data[list->length] = element; list->length++; return &(list->data[list->length - 1]); } else { return 0; } } template void zeroListFull(list *list) { memset(list->data, 0, list->capacity * sizeof(T)); } template void zeroList(list *list) { list->length = 0; memset(list->data, 0, list->capacity * sizeof(T)); } // ### Strings ### #define strlit(lit) (string{(char *)(lit), sizeof(lit) - 1}) struct string { char *str; size_t length; }; #define PushString(arena, length) (string{ (char *)pushSize(arena, length), (length) }) const char *cstring(Arena *arena, list buf) { char *arr = PushArray(arena, char, buf.length + 1); memmove(arr, buf.data, buf.length); arr[buf.length] = '\0'; return arr; } const char *cstring(Arena *arena, string str) { char *arr = PushArray(arena, char, str.length + 1); memmove(arr, str.str, str.length); arr[str.length] = '\0'; return arr; } bool strEql(string s1, string s2) { if (s1.length != s2.length) { return false; } for (size_t i = 0; i < s1.length; i++) { if (s1.str[i] != s2.str[i]) { return false; } } return true; } size_t calcStringLen(const char *str) { size_t size = 0; if (str == NULL) { return size; } while (str[size] != '\0') { size++; } return size; } string strFromCString(Arena *arena, const char *str) { string result = PushString(arena, calcStringLen(str)); memcpy(result.str, str, result.length); return result; } string strReverse(Arena *arena, string str) { string reversed = PushString(arena, str.length); for ( size_t mainIndex = str.length - 1, reversedIndex = 0; mainIndex < str.length; mainIndex--, reversedIndex++ ) { reversed.str[reversedIndex] = str.str[mainIndex]; } return reversed; } template list listSlice(list l, size_t start, size_t stop = 0) { if (stop == 0) { stop = l.length; } // TODO(dledda): maybe assert instead if (stop > l.length || start > stop) { return {0}; } return { l.data + start, stop - start, stop - start, }; } string strSlice(string str, size_t start, size_t stop = 0) { if (stop == 0) { stop = str.length; } // TODO(dledda): maybe assert instead if (stop > str.length || start > stop) { return {0}; } return { str.str + start, stop - start, }; } string strSlice(char *data, size_t start, size_t stop) { return { data + start, stop - start, }; } bool stringContains(string str, char c) { for (size_t i = 0; i < str.length; i++) { if (str.str[i] == c) { return true; } } return false; } const char NUMERIC_CHARS[] = "0123456789"; inline bool isNumeric(char c) { return stringContains(strlit(NUMERIC_CHARS), c); } list strSplit(Arena *arena, string splitStr, string inputStr) { list result = {0}; if (inputStr.length > 0) { size_t splitCount = 0; size_t c = 0; size_t start = 0; void *beginning = (char *)arena->memory + arena->head; while (c < inputStr.length - splitStr.length) { if (strEql(strSlice(inputStr, c, splitStr.length), splitStr)) { string *splitString = PushStruct(arena, string); splitString->str = inputStr.str + start; splitString->length = c - start; splitCount++; start = c + 1; } c++; } string *splitString = PushStruct(arena, string); splitString->str = inputStr.str + start; splitString->length = inputStr.length - start; splitCount++; result.data = (string *)beginning, result.capacity = splitCount, result.length = splitCount; } return result; } int8 parsePositiveInt(string str, size_t *lengthPointer) { size_t numEnd = 0; char currChar = str.str[numEnd]; while (numEnd < str.length && isNumeric(currChar)) { currChar = str.str[++numEnd]; *lengthPointer += 1; } *lengthPointer -= 1; if (numEnd > 0) { uint8 result = 0; for (size_t i = 0; i < numEnd; i++) { result *= 10; result += str.str[i] - '0'; } return result; } else { return -1; } } real32 parsePositiveReal32(Arena *arena, string str, size_t *lengthPointer) { real32 result = NAN; string wholePartStr = string{0}; string fractionalPartStr = string{0}; bool split = false; size_t c = 0; while (c < str.length) { if (str.str[c] == '.') { wholePartStr.str = str.str; wholePartStr.length = c; fractionalPartStr.str = str.str + c + 1; fractionalPartStr.length = str.length - c - 1; split = true; break; } c++; } if (split) { int wholePart = parsePositiveInt(wholePartStr, lengthPointer); *lengthPointer += 1; int fractionalPart = parsePositiveInt(fractionalPartStr, lengthPointer); if (wholePart >= 0 && fractionalPart >= 0) { real32 fractionalPartMultiplier = 1.0f / powf(10.0f, (real32)fractionalPartStr.length); result = (real32)wholePart + (real32)fractionalPart * (real32)fractionalPartMultiplier; } } else if (c > 0) { result = (real32)parsePositiveInt(str, lengthPointer); } return result; } // ### File IO ### string readEntireFile(Arena *arena, string filename) { #if ENVIRONMENT_WINDOWS string result = {0}; HANDLE fileHandle = CreateFileA(cstring(arena, filename), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if (fileHandle != INVALID_HANDLE_VALUE) { LARGE_INTEGER fileSize; if (GetFileSizeEx(fileHandle, &fileSize)) { string readfile = PushString(arena, (size_t)fileSize.QuadPart); if (readfile.str) { DWORD bytesRead; if (ReadFile(fileHandle, readfile.str, (DWORD)fileSize.QuadPart, &bytesRead, NULL) && (fileSize.QuadPart == bytesRead)) { result = readfile; } } } CloseHandle(fileHandle); } return result; #endif #if ENVIRONMENT_LINUX FILE *input = fopen((char *)file.str, "r"); struct stat st; stat((char *)file.str, &st); size_t fsize = st.st_size; string readBuffer = PushString(arena, filesize); readBuffer.length = filesize; fread(readBuffer.str, sizeof(byte), filesize, input); fclose(input); return readBuffer; #endif } bool writeEntireFile(Arena *arena, string filename, const byte *contents, size_t contentsLength) { #if ENVIRONMENT_WINDOWS bool result = false; HANDLE fileHandle = CreateFileA(cstring(arena, filename), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, NULL, NULL); if (fileHandle != INVALID_HANDLE_VALUE) { DWORD bytesWritten; if (WriteFile(fileHandle, contents, (DWORD)contentsLength, &bytesWritten, NULL)) { // file written successfully result = bytesWritten == contentsLength; } CloseHandle(fileHandle); } return result; #endif #if ENVIRONMENT_LINUX Assert(false); #endif } bool fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength) { #if ENVIRONMENT_WINDOWS bool result = false; HANDLE fileHandle = CreateFileA(cstring(arena, filename), FILE_APPEND_DATA | FILE_GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (fileHandle != INVALID_HANDLE_VALUE) { DWORD bytesWritten; DWORD position = SetFilePointer(fileHandle, 0, NULL, FILE_END); if (WriteFile(fileHandle, contents, (DWORD)contentsLength, &bytesWritten, NULL)) { // file written successfully result = bytesWritten == contentsLength; } CloseHandle(fileHandle); } return result; #endif #if ENVIRONMENT_LINUX Assert(false); #endif } // ### Misc ### int cmpint(const void *a, const void *b) { int *x = (int *)a; int *y = (int *)b; return (*x > *y) - (*x < *y); } list getArgs(Arena *arena, int argc, char **argv) { list args = PushList(arena, string, (size_t)argc); for (int i = 1; i < argc; i++) { appendList(&args, strFromCString(arena, argv[i])); } return args; } uint64 getSystemUnixTime() { time_t now; time(&now); return now; } string formatTimeHms(Arena *arena, time_t time) { static const string format = strlit("HH-MM-SS"); string buf = PushString(arena, format.length); tm timestamp; gmtime_s(×tamp, &time); strftime(buf.str, buf.length + 1, "%T", ×tamp); return buf; } string formatTimeHms(Arena *arena, tm *time) { static const string format = strlit("HH-MM-SS"); string buf = PushString(arena, format.length); strftime(buf.str, buf.length + 1, "%T", time); return buf; } string formatTimeYmd(Arena *arena, time_t time) { static const string format = strlit("YYYY-mm-dd"); string buf = PushString(arena, format.length); tm timestamp; gmtime_s(×tamp, &time); strftime(buf.str, buf.length + 1, "%Y-%m-%d", ×tamp); return buf; } string formatTimeYmd(Arena *arena, tm *time) { static const string format = strlit("YYYY-mm-dd"); string buf = PushString(arena, format.length); strftime(buf.str, buf.length + 1, "%Y-%m-%d", time); return buf; } // ### Logging ### void print(Arena *arena, list l) { for (size_t i = 0; i < l.length; i++) { if (i != 0) { printf(", "); } else { printf("{ "); } printf("%i", l.data[i]); } printf(" } length: %zu, capacity: %zu\n", l.capacity, l.length); } void print(Arena *arena, list l) { for (size_t i = 0; i < l.length; i++) { if (i != 0) { printf(", "); } else { printf("{ "); } printf("\"%s\"", cstring(arena, l.data[i])); } printf(" } length: %zu, capacity: %zu\n", l.capacity, l.length); } #endif