|
- #include <unistd.h> // TODO(djledda): get outta here
- #include <math.h>
- #include <string.h>
- #define STB_SPRINTF_IMPLEMENTATION
- #include "core.h"
- #include "os.cpp"
-
- 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;
- }
-
- Arena *arenaAlloc(size_t capacity) {
- Arena *result = (Arena *)os_alloc(sizeof(Arena) + capacity);
- result->memory = result + sizeof(Arena);
- result->capacity = capacity;
- result->head = 0;
- return result;
- }
-
- void arenaFree(Arena *arena) {
- os_free(arena, arena->capacity);
- }
-
- void arenaFreeFrom(Arena *arena, size_t position) {
- arena->head = position;
- }
-
- Arena *scratchArenas[2];
-
- void initialiseCore() {
- for (EachInArray(scratchArenas, i)) {
- scratchArenas[i] = arenaAlloc(Megabytes(64));
- }
- }
-
- Scratch scratchStart(Arena **conflicts, size_t conflictCount) {
- Scratch scratch = {0};
- for (size_t i = 0; i < ArrayCount(scratchArenas); i += 1) {
- bool conflicted = false;
- for (Arena **conflict = conflicts; conflict < conflicts + conflictCount; conflict += 1) {
- if (*conflict == scratchArenas[i]) {
- conflicted = true;
- break;
- }
- }
- if (conflicted == false) {
- scratch.arena = scratchArenas[i];
- scratch.start = scratch.arena->head;
- break;
- }
- }
- return scratch;
- }
-
- #define DeferLoop(begin_stmnt, end_stmnt) for(int __defer_i = ((begin_stmnt), 0); __defer_i < 1; (++__defer_i, (end_stmnt)))
- #define WithScratch(scratchName) Scratch scratchName; DeferLoop(scratchName = scratchStart(0, 0), scratchEnd(scratchName))
-
- void scratchEnd(Scratch scratch) {
- arenaFreeFrom(scratch.arena, scratch.start);
- }
-
- template <typename T>
- T *appendList(list<T> *list, T element) {
- if (list->head < list->length) {
- list->data[list->head] = element;
- list->head++;
- return &(list->data[list->head - 1]);
- } else {
- return 0;
- }
- }
-
- template <typename T>
- void zeroListFull(list<T> *list) {
- memset(list->data, 0, list->head * sizeof(T));
- }
-
- template <typename T>
- void zeroList(list<T> *list) {
- list->head = 0;
- memset(list->data, 0, list->head * sizeof(T));
- }
-
- inline string operator""_s(const char *cstrLiteral, unsigned long length) {
- return {
- (char *)cstrLiteral,
- length,
- };
- }
-
- const char *cstring(Arena *arena, list<char> 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;
- }
-
- string strPrintfv(Arena *arena, const char *fmt, va_list args) {
- string result = {0};
- va_list argsCopy;
- va_copy(argsCopy, args);
- uint64 bufSize = stb_vsnprintf(0, 0, fmt, args) + 1;
- result.str = PushArray(arena, char, bufSize);
- result.length = bufSize - 1;
- stb_vsnprintf((char *)result.str, (int)bufSize, fmt, argsCopy);
- return result;
- }
-
- string strPrintf(Arena *arena, const char *fmt, ...) {
- string result = {0};
- va_list args;
- va_start(args, fmt);
- result = strPrintfv(arena, fmt, args);
- va_end(args);
- return result;
- }
-
- template <typename T>
- list<T> listSlice(list<T> l, size_t start, size_t stop) {
- if (stop == 0) {
- stop = l.head;
- }
- // TODO(djledda): maybe assert instead
- if (stop > l.head || start > stop) {
- return {0};
- }
- return {
- l.data + start,
- stop - start,
- stop - start,
- };
- }
-
- string strSlice(string str, size_t start, size_t stop) {
- if (stop == 0) {
- stop = str.length;
- }
- // TODO(djledda): 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;
- }
-
- string NUMERIC_CHARS = "0123456789"_s;
- inline bool isNumeric(char c) {
- return stringContains(NUMERIC_CHARS, c);
- }
-
- list<string> strSplit(Arena *arena, string splitStr, string inputStr) {
- list<string> 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, 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.head = 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(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;
- }
-
- string readEntireFile(Arena *arena, string filename) {
- #if OS_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;
- #elif OS_LINUX
- FILE *input = fopen((char *)filename.str, "r");
- struct stat st;
- stat((char *)filename.str, &st);
- size_t fsize = st.st_size;
- string readBuffer = PushString(arena, fsize);
- fread(readBuffer.str, sizeof(byte), readBuffer.length, input);
- fclose(input);
- return readBuffer;
- #endif
- }
-
- bool writeEntireFile(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
- bool result = false;
- #if OS_WINDOWS
- 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);
- }
- #elif OS_LINUX
- Assert(false);
- #endif
- return result;
- }
-
- bool fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
- bool result = false;
- #if OS_WINDOWS
- 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);
- }
- #elif OS_LINUX
- Assert(false);
- #endif
- return result;
- }
-
- list<string> getArgs(Arena *arena, int argc, char **argv) {
- list<string> args = PushList(arena, string, (size_t)argc);
- for (int i = 1; i < argc; i++) {
- appendList(&args, strFromCString(arena, argv[i]));
- }
- return args;
- }
-
- UnixTimestamp getSystemUnixTime() {
- time_t now;
- time(&now);
- return (UnixTimestamp)now;
- }
-
- Timestamp timestampFromUnixTime(UnixTimestamp *unixTimestamp) {
- tm *timestamp = gmtime((time_t *)&time);
- return *timestamp;
- }
-
- string formatTimeHms(Arena *arena, UnixTimestamp time) {
- local_persist const string format = "HH-MM-SS"_s;
- string buf = PushString(arena, format.length);
- tm *timestamp = gmtime((time_t *)&time);
- strftime(buf.str, buf.length + 1, "%T", timestamp);
- return buf;
- }
-
- string formatTimeHms(Arena *arena, Timestamp *time) {
- local_persist const string format = "HH-MM-SS"_s;
- string buf = PushString(arena, format.length);
- strftime(buf.str, buf.length + 1, "%T", (tm *)time);
- return buf;
- }
-
- string formatTimeYmd(Arena *arena, UnixTimestamp time) {
- local_persist const string format = "YYYY-mm-dd"_s;
- string buf = PushString(arena, format.length);
- tm *timestamp = gmtime((time_t *)&time);
- strftime(buf.str, buf.length + 1, "%Y-%m-%d", timestamp);
- return buf;
- }
-
- string formatTimeYmd(Arena *arena, Timestamp *time) {
- local_persist const string format = "YYYY-mm-dd"_s;
- string buf = PushString(arena, format.length);
- strftime(buf.str, buf.length + 1, "%Y-%m-%d", (tm *)time);
- return buf;
- }
-
- function void __core_log(LogTarget target, const char *fmt, va_list argList) {
- Scratch scratch = scratchStart(0, 0);
- string result = strPrintfv(scratch.arena, fmt, argList);
- #if OS_WINDOWS
- DWORD done;
- HANDLE stdHandle;
- switch (target) {
- case LogTarget_stdin:
- stdHandle = GetStdHandle(STD_INPUT_HANDLE);
- break;
- case LogTarget_stdout:
- stdHandle = GetStdHandle(STD_ERROR_HANDLE);
- break;
- case LogTarget_stderr:
- stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
- break;
- default:
- stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
- break;
- }
- WriteFile(stdHandle, result.str, (DWORD)result.length, &done, 0);
- #elif OS_LINUX
- // TODO(djledda): finish implementation without cstdlib
- switch (target) {
- case LogTarget_stdin:
- write(0, (const void *)result.str, result.length);
- break;
- case LogTarget_stderr:
- fflush(stderr);
- write(2, (const void *)result.str, result.length);
- break;
- case LogTarget_stdout:
- default:
- fflush(stdout);
- write(1, (const void *)result.str, result.length);
- break;
- }
- #endif
- scratchEnd(scratch);
- }
-
- void logErr(const char *fmt, ...) {
- va_list argList;
- va_start(argList, fmt);
- __core_log(LogTarget_stdout, fmt, argList);
- va_end(argList);
- }
-
- function void logStdout(const char *fmt, ...) {
- va_list argList;
- va_start(argList, fmt);
- __core_log(LogTarget_stdout, fmt, argList);
- va_end(argList);
- }
-
- void log(const char *fmt, ...) {
- va_list argList;
- va_start(argList, fmt);
- __core_log(LogTarget_stdout, fmt, argList);
- va_end(argList);
- }
-
- void log(list<int> l, LogTarget target) {
- void (*logFn)(const char *fmt, ...) = target == LogTarget_stdout ? &logStdout : &logErr;
- logFn("{ ");
- for (size_t i = 0; i < l.length; i++) {
- if (i != 0) {
- logFn(", ");
- }
- logFn("%i", l.data[i]);
- }
- logFn(" } length: %zu, head: %zu\n", l.length, l.head);
- }
-
- void log(list<string> l, LogTarget target) {
- void (*logFn)(const char *fmt, ...) = target == LogTarget_stdout ? &logStdout : &logErr;
- logFn("{ ");
- for (size_t i = 0; i < l.length; i++) {
- if (i != 0) {
- logFn(", ");
- }
- logFn("\"%S\"", l.data[i]);
- }
- logFn(" } length: %zu, head: %zu\n", l.length, l.head);
- }
-
- int intCompare(const void *a, const void *b) {
- int *x = (int *)a;
- int *y = (int *)b;
- return (*x > *y) - (*x < *y);
- }
|