@@ -1,3 +1,3 @@ | |||
CompileFlags: | |||
Add: | |||
- -DENVIRONMENT_WINDOWS | |||
- -DOS_LINUX |
@@ -1,9 +1,10 @@ | |||
#include <math.h> | |||
#include <memory.h> | |||
#include <time.h> | |||
#include "core.hpp" | |||
#include "./djstdlib/core.cpp" | |||
const string LOG_FILE_LOCATION = strlit(".\\log.gtl"); | |||
const string DB_FILE_LOCATION = strlit(".\\db.gtd"); | |||
const string LOG_FILE_LOCATION = "./log.gtl"_s; | |||
const string DB_FILE_LOCATION = "./db.gtd"_s; | |||
struct GymLogDbHeader { | |||
uint32 nextId; | |||
@@ -24,14 +25,16 @@ struct GymLogDbParsed { | |||
list<GymLogDbParsedEntry> entries; | |||
}; | |||
struct WeightRepsInfo { | |||
uint8 reps; | |||
real32 weight; | |||
}; | |||
struct GymLogEntry { | |||
uint64 timestamp; | |||
uint32 exerciseId; | |||
union { | |||
struct WeightReps { | |||
uint8 reps; | |||
real32 weight; | |||
} weightRepsInfo; | |||
WeightRepsInfo weightRepsInfo; | |||
}; | |||
}; | |||
@@ -62,7 +65,7 @@ int gymTrackerWorkForExercise(Arena *arena, uint32 exerciseId) { | |||
string logfile = readEntireFile(arena, LOG_FILE_LOCATION); | |||
if (logfile.length % sizeof(GymLogEntry) != 0) { | |||
puts("Log file corrupted."); | |||
log("Log file corrupted.\n"); | |||
statusCode = 1; | |||
} else { | |||
size_t entryCount = logfile.length / sizeof(GymLogEntry); | |||
@@ -70,21 +73,19 @@ int gymTrackerWorkForExercise(Arena *arena, uint32 exerciseId) { | |||
int currentYear = 0; | |||
list<GymLogEntry> logEntries = { (GymLogEntry *)logfile.str, entryCount, entryCount }; | |||
tm todayTs = {0}; | |||
time_t todayUnix = getSystemUnixTime(); | |||
gmtime_s(&todayTs, (time_t *)&todayUnix); | |||
UnixTimestamp todayUnix = getSystemUnixTime(); | |||
Timestamp todayTs = timestampFromUnixTime(&todayUnix); | |||
real32 work = 0; | |||
for (EachIn(logEntries, i)) { | |||
GymLogEntry logEntry = logEntries.data[i]; | |||
tm logTs = {0}; | |||
gmtime_s(&logTs, (time_t *)&logEntry.timestamp); | |||
Timestamp logTs = timestampFromUnixTime(&logEntry.timestamp); | |||
if (logTs.tm_yday == todayTs.tm_yday && todayTs.tm_year == logTs.tm_year) { | |||
work += logEntry.weightRepsInfo.weight * logEntry.weightRepsInfo.reps; | |||
} | |||
} | |||
printf("Total work for this exercise today:\n%.2f J * m/ex\n", work); | |||
log("Total work for this exercise today:\n%.2f J * m/ex\n", work); | |||
} | |||
return statusCode; | |||
@@ -100,11 +101,11 @@ int gymTrackerStatus(Arena *arena, list<string> args) { | |||
puts("Log file corrupted."); | |||
statusCode = 1; | |||
} else { | |||
tm stopTs = {0}; | |||
if (args.length > 0 && strEql(args.data[0], strlit("--today"))) { | |||
time_t todayUnix = getSystemUnixTime(); | |||
gmtime_s(&stopTs, (time_t *)&todayUnix); | |||
} else if (args.length > 1 && strEql(args.data[0], strlit("--days")) || strEql(args.data[0], strlit("-d"))) { | |||
Timestamp stopTs = {0}; | |||
if (args.length > 0 && strEql(args.data[0], "--today"_s)) { | |||
UnixTimestamp nowUnix = getSystemUnixTime(); | |||
stopTs = timestampFromUnixTime(&nowUnix); | |||
} else if (args.length > 1 && strEql(args.data[0], "--days"_s) || strEql(args.data[0], "-d"_s)) { | |||
size_t l; | |||
int numDays = parsePositiveInt(args.data[1], &l); | |||
if (numDays == -1) { | |||
@@ -112,8 +113,8 @@ int gymTrackerStatus(Arena *arena, list<string> args) { | |||
statusCode = 1; | |||
} else { | |||
uint64 todayUnix = getSystemUnixTime(); | |||
time_t stopUnix = (time_t)(todayUnix - numDays * 24 * 60 * 60); | |||
gmtime_s(&stopTs, (time_t *)&stopUnix); | |||
UnixTimestamp stopUnix = todayUnix - numDays * 24 * 60 * 60; | |||
stopTs = timestampFromUnixTime(&stopUnix); | |||
} | |||
} | |||
@@ -130,9 +131,9 @@ int gymTrackerStatus(Arena *arena, list<string> args) { | |||
int dayCount = 0; | |||
tm timestamp = {0}; | |||
Timestamp timestamp = {0}; | |||
if (logEntries.length > 0) { | |||
gmtime_s(×tamp, (time_t *)&logEntries.data[logEntries.length - 1].timestamp); | |||
timestamp = timestampFromUnixTime(&logEntries.data[logEntries.length - 1].timestamp); | |||
} | |||
for (EachInReversed(logEntries, i)) { | |||
@@ -142,9 +143,9 @@ int gymTrackerStatus(Arena *arena, list<string> args) { | |||
break; | |||
} | |||
if (dayCount > 0) { | |||
puts(""); | |||
log("\n"); | |||
} | |||
printf("--- %s ---\n", cstring(arena, formatTimeYmd(arena, ×tamp))); | |||
log("--- %S ---\n", formatTimeYmd(arena, ×tamp)); | |||
currentDay = timestamp.tm_yday; | |||
currentYear = timestamp.tm_year; | |||
dayCount++; | |||
@@ -152,11 +153,11 @@ int gymTrackerStatus(Arena *arena, list<string> args) { | |||
workPerExerciseByDay.data[entry.exerciseId] += entry.weightRepsInfo.reps * entry.weightRepsInfo.weight; | |||
char *format; | |||
const char *format; | |||
if (entry.weightRepsInfo.weight == (int32)entry.weightRepsInfo.weight) { | |||
format = "%s: %s, %.0fkg X %i\n"; | |||
format = "%S: %S, %.0fkg X %i\n"; | |||
} else { | |||
format = "%s: %s, %.2fkg X %i\n"; | |||
format = "%S: %S, %.2fkg X %i\n"; | |||
} | |||
string *exerciseName = &(nameByExercise.data[entry.exerciseId]); | |||
@@ -169,22 +170,22 @@ int gymTrackerStatus(Arena *arena, list<string> args) { | |||
} | |||
} | |||
printf(format, | |||
cstring(arena, formatTimeHms(arena, ×tamp)), | |||
exerciseName->str ? cstring(arena, *exerciseName) : "unknown-exercise", | |||
log(format, | |||
formatTimeHms(arena, ×tamp), | |||
exerciseName->str ? *exerciseName : "unknown-exercise"_s, | |||
entry.weightRepsInfo.weight, | |||
entry.weightRepsInfo.reps); | |||
if (i > 0) { | |||
gmtime_s(×tamp, (time_t *)&logEntries.data[i - 1].timestamp); | |||
timestamp = timestampFromUnixTime(&logEntries.data[i - 1].timestamp); | |||
} | |||
if (i == 0 || timestamp.tm_yday != currentDay || timestamp.tm_year != currentYear) { | |||
puts(""); | |||
puts("Work summary:"); | |||
log("\n"); | |||
log("Work summary:\n"); | |||
for (size_t j = 0; j < workPerExerciseByDay.length; j++) { | |||
if (workPerExerciseByDay.data[j] != 0.0f) { | |||
printf("%s: %.2f J * m/ex\n", cstring(arena, nameByExercise.data[j]), workPerExerciseByDay.data[j]); | |||
log("%S: %.2f J * m/ex\n", nameByExercise.data[j], workPerExerciseByDay.data[j]); | |||
} | |||
} | |||
zeroListFull(&workPerExerciseByDay); | |||
@@ -201,7 +202,7 @@ int gymTrackerDo(Arena *arena, list<string> args) { | |||
int statusCode = 0; | |||
string newExerciseName = {0}; | |||
if (args.length < 3 || args.data[0].length == 0) { | |||
printf("Invalid exercise name and/or number of arguments."); | |||
log("Invalid exercise name and/or number of arguments.\n"); | |||
statusCode = 1; | |||
} else { | |||
newExerciseName = args.data[0]; | |||
@@ -226,10 +227,10 @@ int gymTrackerDo(Arena *arena, list<string> args) { | |||
if (statusCode == 0) { | |||
uint32 exerciseId = existingEntry->id; | |||
size_t parsedCount = 0; | |||
real32 kg = parsePositiveReal32(arena, args.data[1], &parsedCount); | |||
real32 kg = parsePositiveReal32(args.data[1], &parsedCount); | |||
uint8 reps = parsePositiveInt(args.data[2], &parsedCount); | |||
if (parsedCount == 0 || kg == NAN || reps == 0 || kg == 0) { | |||
printf("Invalid reps or weight input."); | |||
log("Invalid reps or weight input.\n"); | |||
statusCode = 1; | |||
} else { | |||
GymLogEntry entry = { | |||
@@ -251,7 +252,7 @@ int gymTrackerAddExercise(Arena *arena, list<string> args) { | |||
int statusCode = 0; | |||
string newExerciseName = args.data[0]; | |||
if (newExerciseName.length == 0) { | |||
printf("No exercise name provided."); | |||
log("No exercise name provided.\n"); | |||
statusCode = 1; | |||
} | |||
@@ -280,7 +281,7 @@ int gymTrackerAddExercise(Arena *arena, list<string> args) { | |||
string entryName = {(char *)((byte *)database.str + head), currentEntry->nameLength }; | |||
if (strEql(entryName, newExerciseName)) { | |||
invalid = true; | |||
printf("Exercise \"%s\" already registered (entry #%i)\n", cstring(arena, entryName), currentEntry->id); | |||
log("Exercise \"%S\" already registered (entry #%i)\n", entryName, currentEntry->id); | |||
break; | |||
} | |||
head += currentEntry->nameLength; | |||
@@ -313,25 +314,25 @@ int gymTrackerAddExercise(Arena *arena, list<string> args) { | |||
} | |||
int main(int argc, char **argv) { | |||
initialiseCore(); | |||
Arena *arena = arenaAlloc(Megabytes(64)); | |||
list<string> args = getArgs(arena, argc, argv); | |||
int statusCode = 0; | |||
if (args.length < 1) { | |||
puts("At least one arg is required."); | |||
log("At least one arg is required.\n"); | |||
statusCode = 1; | |||
} | |||
if (statusCode == 0) { | |||
if (strEql(args.data[0], strlit("status"))) { | |||
if (strEql(args.data[0], "status"_s)) { | |||
statusCode = gymTrackerStatus(arena, listSlice(args, 1)); | |||
} else if (strEql(args.data[0], strlit("do"))) { | |||
} else if (strEql(args.data[0], "do"_s)) { | |||
statusCode = gymTrackerDo(arena, listSlice(args, 1)); | |||
} else if (strEql(args.data[0], strlit("add"))) { | |||
} else if (strEql(args.data[0], "add"_s)) { | |||
statusCode = gymTrackerAddExercise(arena, listSlice(args, 1)); | |||
} else { | |||
printf("Unknown command \"%s\"", cstring(arena, args.data[0])); | |||
log("Unknown command \"%S\"\n", args.data[0]); | |||
statusCode = 1; | |||
} | |||
} | |||
@@ -1,3 +1,3 @@ | |||
#!/bin/bash | |||
gcc -g -g3 ./app.cpp -o ./target/app | |||
g++ -g -g3 -DOS_LINUX ./app.cpp -o ./target/app |
@@ -0,0 +1,3 @@ | |||
CompileFlags: | |||
Add: | |||
- -DOS_LINUX |
@@ -0,0 +1,14 @@ | |||
#include <stdio.h> | |||
#include "core.cpp" | |||
#include "core.h" | |||
int main(int argc, char **argv) { | |||
int statusCode = 0; | |||
initialiseCore(); | |||
Arena *arena = arenaAlloc(Megabytes(64)); | |||
list<string> args = getArgs(arena, argc, argv); | |||
prinft("%S", strSplit(arena, "-"_s, "hallo-world"_s)); | |||
return statusCode; | |||
} |
@@ -0,0 +1,3 @@ | |||
#!/bin/bash | |||
g++ -g -g3 -lm -DOS_LINUX=1 -DENABLE_ASSERT=1 ./app.cpp -o ./target/app |
@@ -0,0 +1,27 @@ | |||
@echo off | |||
if NOT EXIST .\target mkdir .\target | |||
set commonLinkerFlags=-opt:ref | |||
set commonCompilerFlags=^ | |||
-MT %= Make sure the C runtime library is statically linked =%^ | |||
-Gm- %= Turns off incremental building =%^ | |||
-nologo %= No one cares you made the compiler Microsoft =%^ | |||
-Oi %= Always use intrinsics =%^ | |||
-EHa- %= Disable exception handling =%^ | |||
-GR- %= Never use runtime type info from C++ =%^ | |||
-WX -W4 -wd4201 -wd4100 -wd4189 -wd4505 %= Compiler warnings, -WX warnings as errors, -W4 warning level 4, -wdXXXX disable warning XXXX =%^ | |||
-DAPP_DEBUG=0 -DENABLE_ASSERT=1 -DOS_WINDOWS=1 %= Custom #defines =%^ | |||
-D_CRT_SECURE_NO_WARNINGS=1^ | |||
-FC %= Full path of source code file in diagnostics =%^ | |||
-Zi %= Generate debugger info =% | |||
pushd .\target | |||
cl %commonCompilerFlags% -Fe:.\app.exe ..\app.cpp /link -incremental:no %commonLinkerFlags% | |||
popd | |||
exit /b | |||
:error | |||
echo Failed with error #%errorlevel%. | |||
exit /b %errorlevel% |
@@ -1,61 +1,10 @@ | |||
#ifndef CORE_HPP | |||
#define CORE_HPP | |||
#include <time.h> | |||
#include <math.h> | |||
#include <stdint.h> | |||
#include <stdio.h> | |||
#if ENVIRONMENT_WINDOWS | |||
#include "Windows.h" | |||
#endif | |||
#if ENVIRONMENT_LINUX | |||
#include <sys/mman.h> | |||
#include <sys/stat.h> | |||
#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; | |||
}; | |||
#include <string.h> | |||
#include <unistd.h> | |||
#include "core.h" | |||
#include "os.cpp" | |||
#define STB_SPRINTF_IMPLEMENTATION | |||
#include "vendor/stb_sprintf.h" | |||
void *pushSize(Arena *arena, size_t bytes) { | |||
if (arena->capacity - arena->head >= bytes) { | |||
@@ -66,17 +15,8 @@ void *pushSize(Arena *arena, size_t bytes) { | |||
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 | |||
Arena *result = (Arena *)os_alloc(sizeof(Arena) + capacity); | |||
result->memory = result + sizeof(Arena); | |||
result->capacity = capacity; | |||
result->head = 0; | |||
@@ -84,36 +24,57 @@ Arena *arenaAlloc(size_t capacity) { | |||
} | |||
void arenaFree(Arena *arena) { | |||
#if ENVIRONMENT_WINDOWS | |||
VirtualFree(arena, NULL, MEM_RELEASE); | |||
#endif | |||
os_free(arena, arena->capacity); | |||
} | |||
#if ENVIRONMENT_LINUX | |||
// TODO(dledda): implement this for Linux | |||
#endif | |||
void arenaFreeFrom(Arena *arena, size_t position) { | |||
arena->head = position; | |||
} | |||
// ### Lists ### | |||
template <typename T> | |||
struct list { | |||
T* data; | |||
size_t capacity; | |||
size_t length; | |||
}; | |||
#define PushList(arena, type, size) (list<type>{ PushArray(arena, type, size), size, 0 }) | |||
#define PushFullList(arena, type, size) (list<type>{ 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 | |||
void arenaPopTo(Arena *arena, void *position) { | |||
arena->head = (byte *)position - (byte *)arena->memory; | |||
} | |||
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->length < list->capacity) { | |||
list->data[list->length] = element; | |||
list->length++; | |||
return &(list->data[list->length - 1]); | |||
if (list->head < list->length) { | |||
list->data[list->head] = element; | |||
list->head++; | |||
return &(list->data[list->head - 1]); | |||
} else { | |||
return 0; | |||
} | |||
@@ -121,24 +82,21 @@ T *appendList(list<T> *list, T element) { | |||
template <typename T> | |||
void zeroListFull(list<T> *list) { | |||
memset(list->data, 0, list->capacity * sizeof(T)); | |||
memset(list->data, 0, list->head * sizeof(T)); | |||
} | |||
template <typename T> | |||
void zeroList(list<T> *list) { | |||
list->length = 0; | |||
memset(list->data, 0, list->capacity * sizeof(T)); | |||
list->head = 0; | |||
memset(list->data, 0, list->head * 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) }) | |||
inline string operator""_s(const char *cstrLiteral, size_t length) { | |||
return { | |||
(char *)cstrLiteral, | |||
length, | |||
}; | |||
} | |||
const char *cstring(Arena *arena, list<char> buf) { | |||
char *arr = PushArray(arena, char, buf.length + 1); | |||
@@ -195,13 +153,33 @@ string strReverse(Arena *arena, string str) { | |||
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 = 0) { | |||
list<T> listSlice(list<T> l, size_t start, size_t stop) { | |||
if (stop == 0) { | |||
stop = l.length; | |||
stop = l.head; | |||
} | |||
// TODO(dledda): maybe assert instead | |||
if (stop > l.length || start > stop) { | |||
// TODO(djledda): maybe assert instead | |||
if (stop > l.head || start > stop) { | |||
return {0}; | |||
} | |||
return { | |||
@@ -211,11 +189,11 @@ list<T> listSlice(list<T> l, size_t start, size_t stop = 0) { | |||
}; | |||
} | |||
string strSlice(string str, size_t start, size_t stop = 0) { | |||
string strSlice(string str, size_t start, size_t stop) { | |||
if (stop == 0) { | |||
stop = str.length; | |||
} | |||
// TODO(dledda): maybe assert instead | |||
// TODO(djledda): maybe assert instead | |||
if (stop > str.length || start > stop) { | |||
return {0}; | |||
} | |||
@@ -241,9 +219,9 @@ bool stringContains(string str, char c) { | |||
return false; | |||
} | |||
const char NUMERIC_CHARS[] = "0123456789"; | |||
string NUMERIC_CHARS = "0123456789"_s; | |||
inline bool isNumeric(char c) { | |||
return stringContains(strlit(NUMERIC_CHARS), c); | |||
return stringContains(NUMERIC_CHARS, c); | |||
} | |||
list<string> strSplit(Arena *arena, string splitStr, string inputStr) { | |||
@@ -254,7 +232,7 @@ list<string> strSplit(Arena *arena, string splitStr, string inputStr) { | |||
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)) { | |||
if (strEql(strSlice(inputStr, c, c + splitStr.length), splitStr)) { | |||
string *splitString = PushStruct(arena, string); | |||
splitString->str = inputStr.str + start; | |||
splitString->length = c - start; | |||
@@ -269,7 +247,7 @@ list<string> strSplit(Arena *arena, string splitStr, string inputStr) { | |||
splitString->length = inputStr.length - start; | |||
splitCount++; | |||
result.data = (string *)beginning, | |||
result.capacity = splitCount, | |||
result.head = splitCount, | |||
result.length = splitCount; | |||
} | |||
return result; | |||
@@ -295,7 +273,7 @@ int8 parsePositiveInt(string str, size_t *lengthPointer) { | |||
} | |||
} | |||
real32 parsePositiveReal32(Arena *arena, string str, size_t *lengthPointer) { | |||
real32 parsePositiveReal32(string str, size_t *lengthPointer) { | |||
real32 result = NAN; | |||
string wholePartStr = string{0}; | |||
@@ -319,6 +297,7 @@ real32 parsePositiveReal32(Arena *arena, string str, size_t *lengthPointer) { | |||
*lengthPointer += 1; | |||
int fractionalPart = parsePositiveInt(fractionalPartStr, lengthPointer); | |||
if (wholePart >= 0 && fractionalPart >= 0) { | |||
// TODO(dledda): implement powf with intrinsics? or just custom | |||
real32 fractionalPartMultiplier = 1.0f / powf(10.0f, (real32)fractionalPartStr.length); | |||
result = (real32)wholePart + (real32)fractionalPart * (real32)fractionalPartMultiplier; | |||
} | |||
@@ -328,9 +307,8 @@ real32 parsePositiveReal32(Arena *arena, string str, size_t *lengthPointer) { | |||
return result; | |||
} | |||
// ### File IO ### | |||
string readEntireFile(Arena *arena, string filename) { | |||
#if ENVIRONMENT_WINDOWS | |||
#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) { | |||
@@ -347,24 +325,26 @@ string readEntireFile(Arena *arena, string filename) { | |||
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); | |||
#elif OS_LINUX | |||
FILE *input = fopen((char *)filename.str, "r"); | |||
string readBuffer; | |||
if (input) { | |||
struct stat st; | |||
stat((char *)filename.str, &st); | |||
size_t fsize = st.st_size; | |||
readBuffer = PushString(arena, fsize); | |||
fread(readBuffer.str, sizeof(byte), readBuffer.length, input); | |||
fclose(input); | |||
} else { | |||
readBuffer = PushString(arena, 0); | |||
} | |||
return readBuffer; | |||
#endif | |||
} | |||
bool writeEntireFile(Arena *arena, string filename, const byte *contents, size_t contentsLength) { | |||
#if ENVIRONMENT_WINDOWS | |||
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; | |||
@@ -374,17 +354,20 @@ bool writeEntireFile(Arena *arena, string filename, const byte *contents, size_t | |||
} | |||
CloseHandle(fileHandle); | |||
} | |||
return result; | |||
#endif | |||
#if ENVIRONMENT_LINUX | |||
Assert(false); | |||
#elif OS_LINUX | |||
FILE *output = fopen((char *)filename.str, "w"); | |||
if (output) { | |||
fwrite(contents, contentsLength, contentsLength, output); | |||
fclose(output); | |||
result = true; | |||
} | |||
#endif | |||
return result; | |||
} | |||
bool fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength) { | |||
#if ENVIRONMENT_WINDOWS | |||
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; | |||
@@ -395,19 +378,15 @@ bool fileAppend(Arena *arena, string filename, const byte *contents, size_t cont | |||
} | |||
CloseHandle(fileHandle); | |||
} | |||
return result; | |||
#endif | |||
#if ENVIRONMENT_LINUX | |||
Assert(false); | |||
#elif OS_LINUX | |||
FILE *output = fopen((char *)filename.str, "a"); | |||
if (output) { | |||
fwrite(contents, contentsLength, contentsLength, output); | |||
fclose(output); | |||
result = true; | |||
} | |||
#endif | |||
} | |||
// ### Misc ### | |||
int cmpint(const void *a, const void *b) { | |||
int *x = (int *)a; | |||
int *y = (int *)b; | |||
return (*x > *y) - (*x < *y); | |||
return result; | |||
} | |||
list<string> getArgs(Arena *arena, int argc, char **argv) { | |||
@@ -418,67 +397,136 @@ list<string> getArgs(Arena *arena, int argc, char **argv) { | |||
return args; | |||
} | |||
uint64 getSystemUnixTime() { | |||
UnixTimestamp getSystemUnixTime() { | |||
time_t now; | |||
time(&now); | |||
return now; | |||
return (UnixTimestamp)now; | |||
} | |||
string formatTimeHms(Arena *arena, time_t time) { | |||
static const string format = strlit("HH-MM-SS"); | |||
Timestamp timestampFromUnixTime(UnixTimestamp *unixTimestamp) { | |||
tm *timestamp = gmtime((time_t *)unixTimestamp); | |||
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_s(×tamp, &time); | |||
strftime(buf.str, buf.length + 1, "%T", ×tamp); | |||
tm *timestamp = gmtime((time_t *)&time); | |||
strftime(buf.str, buf.length + 1, "%T", timestamp); | |||
return buf; | |||
} | |||
string formatTimeHms(Arena *arena, tm *time) { | |||
static const string format = strlit("HH-MM-SS"); | |||
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", time); | |||
strftime(buf.str, buf.length + 1, "%T", (tm *)time); | |||
return buf; | |||
} | |||
string formatTimeYmd(Arena *arena, time_t time) { | |||
static const string format = strlit("YYYY-mm-dd"); | |||
string formatTimeYmd(Arena *arena, UnixTimestamp time) { | |||
local_persist const string format = "YYYY-mm-dd"_s; | |||
string buf = PushString(arena, format.length); | |||
tm timestamp; | |||
gmtime_s(×tamp, &time); | |||
strftime(buf.str, buf.length + 1, "%Y-%m-%d", ×tamp); | |||
tm *timestamp = gmtime((time_t *)&time); | |||
strftime(buf.str, buf.length + 1, "%Y-%m-%d", timestamp); | |||
return buf; | |||
} | |||
string formatTimeYmd(Arena *arena, tm *time) { | |||
static const string format = strlit("YYYY-mm-dd"); | |||
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", time); | |||
strftime(buf.str, buf.length + 1, "%Y-%m-%d", (tm *)time); | |||
return buf; | |||
} | |||
// ### Logging ### | |||
void print(Arena *arena, list<int> l) { | |||
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) { | |||
printf(", "); | |||
} else { | |||
printf("{ "); | |||
logFn(", "); | |||
} | |||
printf("%i", l.data[i]); | |||
logFn("%i", l.data[i]); | |||
} | |||
printf(" } length: %zu, capacity: %zu\n", l.capacity, l.length); | |||
logFn(" } length: %zu, head: %zu\n", l.length, l.head); | |||
} | |||
void print(Arena *arena, list<string> l) { | |||
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) { | |||
printf(", "); | |||
} else { | |||
printf("{ "); | |||
} | |||
printf("\"%s\"", cstring(arena, l.data[i])); | |||
logFn(", "); | |||
} | |||
logFn("\"%S\"", l.data[i]); | |||
} | |||
printf(" } length: %zu, capacity: %zu\n", l.capacity, l.length); | |||
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); | |||
} | |||
#endif |
@@ -0,0 +1,220 @@ | |||
#ifndef CORE_H | |||
#define CORE_H | |||
// cstdlib includes | |||
#include <math.h> | |||
#include <stdint.h> // necessary for int type sizes | |||
#include <stdio.h> | |||
#include <time.h> // TODO(djledda): try not to depend on this one | |||
// ### Misc macros ### | |||
#if ENABLE_ASSERT | |||
#define Assert(expression) if (!(expression)) {*(volatile int *)0 = 0;} | |||
#else | |||
#define Assert(expression) | |||
#endif | |||
#define function static | |||
#define global static | |||
#define local_persist static | |||
// ### 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; | |||
}; | |||
struct Scratch { | |||
Arena *arena; | |||
size_t start; | |||
}; | |||
void *pushSize(Arena *arena, size_t bytes); | |||
Arena *arenaAlloc(size_t capacity); | |||
void arenaFree(Arena *arena); | |||
void arenaFreeFrom(Arena *arena, size_t pos); | |||
void arenaPopTo(Arena *arena, void *pos); | |||
void initialiseCore(); | |||
Scratch scratchStart(Arena **conflicts, size_t conflictCount); | |||
void scratchEnd(Scratch scratch); | |||
#define PushArray(arena, type, size) (type *)pushSize(arena, sizeof(type) * (size)) | |||
#define PushStruct(arena, type) (type *)pushSize(arena, sizeof(type)) | |||
// ### Vectors ### | |||
template <typename T> | |||
union Vector2 { | |||
struct { | |||
T x; | |||
T y; | |||
}; | |||
T vec[2]; | |||
}; | |||
template <typename T> | |||
inline function Vector2<T> vec2(T x, T y) { | |||
Vector2<T> result = {0}; | |||
result.x = x; | |||
result.y = y; | |||
return result; | |||
} | |||
template <typename T> | |||
union Vector3 { | |||
struct { | |||
T x; | |||
T y; | |||
T z; | |||
}; | |||
T vec[3]; | |||
}; | |||
template <typename T> | |||
inline function Vector3<T> vec3(T x, T y, T z) { | |||
Vector3<T> result = {0}; | |||
result.x = x; | |||
result.y = y; | |||
result.z = z; | |||
return result; | |||
} | |||
template <typename T> | |||
union Vector4 { | |||
struct { | |||
T x; | |||
T y; | |||
T z; | |||
T w; | |||
}; | |||
T vec[4]; | |||
}; | |||
template <typename T> | |||
inline function Vector4<T> vec4(T x, T y, T z, T w) { | |||
Vector4<T> result = {0}; | |||
result.x = x; | |||
result.y = y; | |||
result.z = z; | |||
result.w = w; | |||
return result; | |||
} | |||
// ### Lists ### | |||
template <typename T> | |||
struct list { | |||
T* data; | |||
size_t length; | |||
size_t head; | |||
}; | |||
#define PushList(arena, type, size) (list<type>{ PushArray(arena, type, size), size, 0 }) | |||
#define PushFullList(arena, type, size) (list<type>{ PushArray(arena, type, size), size, size }) | |||
template <typename T> T *appendList(list<T> *list, T element); | |||
template <typename T> void zeroList(list<T> *list); | |||
template <typename T> void zeroListFull(list<T> *list); | |||
template <typename T> list<T> listSlice(list<T> l, size_t start, size_t stop = 0); | |||
// ### Strings ### | |||
struct string { | |||
char *str; | |||
size_t length; | |||
}; | |||
#define STB_SPRINTF_DECORATE(name) stb_##name // define this before including if you want to change the names | |||
#include "vendor/stb_sprintf.h" | |||
#define strlit(lit) (string{(char *)(lit), sizeof(lit) - 1}) | |||
#define PushString(arena, length) (string{ (char *)pushSize(arena, length), (length) }) | |||
string operator""_s(const char *cstrLiteral, size_t length); | |||
// C Strings | |||
const char *cstring(Arena *arena, list<char> buf); | |||
const char *cstring(Arena *arena, string str); | |||
size_t calcStringLen(const char *str); | |||
string strFromCString(Arena *arena, const char *str); | |||
bool strEql(string s1, string s2); | |||
bool stringContains(string str, char c); | |||
string strReverse(Arena *arena, string str); | |||
string strSlice(string str, size_t start, size_t stop = 0); | |||
string strSlice(char *data, size_t start, size_t stop = 0); | |||
list<string> strSplit(Arena *arena, string splitStr, string inputStr); | |||
string strPrintfv(Arena *arena, const char *fmt, va_list args); | |||
string strPrintf(Arena *arena, const char *fmt, ...); | |||
int8 parsePositiveInt(string str, size_t *lengthPointer); | |||
real32 parsePositiveReal32(Arena *arena, string str, size_t *lengthPointer); | |||
inline function bool isNumeric(char c); | |||
// ### File IO ### | |||
string readEntireFile(Arena *arena, string filename); | |||
bool writeEntireFile(Arena *arena, string filename, const byte *contents, size_t contentsLength); | |||
bool fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength); | |||
// ### Cmdline ### | |||
list<string> getArgs(Arena *arena, int argc, char **argv); | |||
// ### Time ### | |||
typedef uint64 UnixTimestamp; | |||
typedef tm Timestamp; | |||
UnixTimestamp getSystemUnixTime(); | |||
Timestamp timestampFromUnixTime(UnixTimestamp *unixTimestamp); | |||
string formatTimeHms(Arena *arena, UnixTimestamp time); | |||
string formatTimeHms(Arena *arena, Timestamp *time); | |||
string formatTimeYmd(Arena *arena, UnixTimestamp time); | |||
string formatTimeYmd(Arena *arena, Timestamp *time); | |||
// ### Linked Lists ### | |||
// TODO(djledda): implement basic linked lists (based on arenas?) | |||
// ### Logging ### | |||
enum LogTarget { | |||
LogTarget_stdout, | |||
LogTarget_stdin, | |||
LogTarget_stderr, | |||
LogTarget_count, | |||
}; | |||
void log(list<int> l, LogTarget target = LogTarget_stdout); | |||
void log(list<string> l, LogTarget target = LogTarget_stdout); | |||
void log(const char *fmt, ...); | |||
void logError(const char *fmt, ...); | |||
// ### Loops ### | |||
#define EachIn(list, it) size_t it = 0; it < (list).head; it++ | |||
#define EachInReversed(list, it) size_t it = (list).head - 1; it >= 0 && it < (list).head; it-- | |||
#define EachInArray(arr, it) size_t it = 0; it < ArrayCount(arr); ++it | |||
// ### Misc ### | |||
int intCompare(const void *a, const void *b); | |||
#endif |
@@ -0,0 +1,12 @@ | |||
#ifndef OS_CPP | |||
#define OS_CPP | |||
#if OS_WINDOWS | |||
#include "os_win32.cpp" | |||
#elif OS_LINUX | |||
#include "os_linux.cpp" | |||
#else | |||
#error Development environment not supported. | |||
#endif | |||
#endif |
@@ -0,0 +1,12 @@ | |||
#ifndef OS_H | |||
#define OS_H | |||
#include "core.h" | |||
// ### Memory ### | |||
void *os_alloc(size_t capacity); | |||
void os_reserve(void *ptr); | |||
void os_decommit(void *ptr); | |||
void os_free(void *ptr, size_t freeSize); | |||
#endif |
@@ -0,0 +1,24 @@ | |||
#ifndef OS_IMPL_LINUX_CPP | |||
#define OS_IMPL_LINUX_CPP | |||
#include "os.h" | |||
#include <sys/mman.h> | |||
#include <sys/stat.h> | |||
void *os_alloc(size_t capacity) { | |||
return mmap(0, capacity, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); | |||
} | |||
void os_commit(void *ptr) { | |||
} | |||
void os_decommit(void *ptr) { | |||
} | |||
void os_free(void *ptr, size_t size) { | |||
int err = munmap(ptr, size); | |||
Assert(err != -1); | |||
} | |||
#endif |
@@ -0,0 +1,21 @@ | |||
#ifndef OS_IMPL_WIN32_CPP | |||
#define OS_IMPL_WIN32_CPP | |||
#include "os.h" | |||
#include "Windows.h" | |||
void *os_alloc(size_t commitSize) { | |||
return VirtualAlloc(NULL, commitSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); | |||
} | |||
void os_reserve(void *ptr) { | |||
} | |||
void os_decommit(void *ptr) { | |||
} | |||
void os_free(void *ptr, size_t size) { | |||
VirtualFree(ptr, NULL, MEM_RELEASE); | |||
} | |||
#endif |