Explorar el Código

first commit

master
Ledda hace 2 semanas
commit
d7c3bb4868
Se han modificado 7 ficheros con 864 adiciones y 0 borrados
  1. +3
    -0
      .clangd
  2. +5
    -0
      .gitignore
  3. +340
    -0
      app.cpp
  4. +3
    -0
      build
  5. +26
    -0
      build.bat
  6. +484
    -0
      core.hpp
  7. +3
    -0
      run

+ 3
- 0
.clangd Ver fichero

@@ -0,0 +1,3 @@
CompileFlags:
Add:
- -DENVIRONMENT_WINDOWS

+ 5
- 0
.gitignore Ver fichero

@@ -0,0 +1,5 @@
/target
/.vscode
app
log.gtl
db.gtd

+ 340
- 0
app.cpp Ver fichero

@@ -0,0 +1,340 @@
#include <math.h>
#include <time.h>
#include "core.hpp"

const string LOG_FILE_LOCATION = strlit(".\\log.gtl");
const string DB_FILE_LOCATION = strlit(".\\db.gtd");

struct GymLogDbHeader {
uint32 nextId;
};

struct GymLogDbEntry {
uint32 id;
uint32 nameLength;
};

struct GymLogDbParsedEntry {
uint32 id;
string name;
};

struct GymLogDbParsed {
GymLogDbHeader header;
list<GymLogDbParsedEntry> entries;
};

struct GymLogEntry {
uint64 timestamp;
uint32 exerciseId;
union {
struct WeightReps {
uint8 reps;
real32 weight;
} weightRepsInfo;
};
};

GymLogDbParsed *parseDb(Arena *arena, string database) {
GymLogDbParsed *dbParsed = PushStruct(arena, GymLogDbParsed);

GymLogDbHeader *header = (GymLogDbHeader *)database.str;
dbParsed->header = *header;

size_t head = sizeof(GymLogDbHeader);
uint32 entriesLeft = header->nextId - 1;
dbParsed->entries = PushList(arena, GymLogDbParsedEntry, entriesLeft);

while (entriesLeft > 0 && head < database.length) {
GymLogDbEntry *currentEntry = (GymLogDbEntry *)((byte *)database.str + head);
GymLogDbParsedEntry parsedEntry = { currentEntry->id, PushString(arena, currentEntry->nameLength) };
head += sizeof(GymLogDbEntry);
memcpy(parsedEntry.name.str, database.str + head, currentEntry->nameLength);
appendList(&dbParsed->entries, parsedEntry);
head += currentEntry->nameLength;
}

return dbParsed;
}

int gymTrackerWorkForExercise(Arena *arena, uint32 exerciseId) {
int statusCode = 0;
string logfile = readEntireFile(arena, LOG_FILE_LOCATION);

if (logfile.length % sizeof(GymLogEntry) != 0) {
puts("Log file corrupted.");
statusCode = 1;
} else {
size_t entryCount = logfile.length / sizeof(GymLogEntry);
int currentDay = 0;
int currentYear = 0;
list<GymLogEntry> logEntries = { (GymLogEntry *)logfile.str, entryCount, entryCount };

tm todayTs = {0};
time_t todayUnix = getSystemUnixTime();
gmtime_s(&todayTs, (time_t *)&todayUnix);

real32 work = 0;
for (EachIn(logEntries, i)) {
GymLogEntry logEntry = logEntries.data[i];
tm logTs = {0};
gmtime_s(&logTs, (time_t *)&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);
}

return statusCode;
}

int gymTrackerStatus(Arena *arena, list<string> args) {
int statusCode = 0;
string file = readEntireFile(arena, LOG_FILE_LOCATION);

GymLogDbParsed *db = parseDb(arena, readEntireFile(arena, DB_FILE_LOCATION));

if (file.length % sizeof(GymLogEntry) != 0) {
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"))) {
size_t l;
int numDays = parsePositiveInt(args.data[1], &l);
if (numDays == -1) {
puts("Bad argument for --days parameter.");
statusCode = 1;
} else {
uint64 todayUnix = getSystemUnixTime();
time_t stopUnix = (time_t)(todayUnix - numDays * 24 * 60 * 60);
gmtime_s(&stopTs, (time_t *)&stopUnix);
}
}

if (statusCode == 0) {
size_t entryCount = file.length / sizeof(GymLogEntry);
int currentDay = -1;
int currentYear = -1;
list<GymLogEntry> logEntries = { (GymLogEntry *)file.str, entryCount, entryCount };

list<real32> workPerExerciseByDay = PushFullList(arena, real32, db->header.nextId);
list<string> nameByExercise = PushFullList(arena, string, db->header.nextId);
zeroListFull(&workPerExerciseByDay);
zeroListFull(&nameByExercise);

int dayCount = 0;

tm timestamp = {0};
if (logEntries.length > 0) {
gmtime_s(&timestamp, (time_t *)&logEntries.data[logEntries.length - 1].timestamp);
}

for (EachInReversed(logEntries, i)) {
GymLogEntry entry = logEntries.data[i];
if (timestamp.tm_yday != currentDay || timestamp.tm_year != currentYear) {
if (timestamp.tm_year < stopTs.tm_year || timestamp.tm_yday < stopTs.tm_yday) {
break;
}
if (dayCount > 0) {
puts("");
}
printf("--- %s ---\n", cstring(arena, formatTimeYmd(arena, &timestamp)));
currentDay = timestamp.tm_yday;
currentYear = timestamp.tm_year;
dayCount++;
}

workPerExerciseByDay.data[entry.exerciseId] += entry.weightRepsInfo.reps * entry.weightRepsInfo.weight;

char *format;
if (entry.weightRepsInfo.weight == (int32)entry.weightRepsInfo.weight) {
format = "%s: %s, %.0fkg X %i\n";
} else {
format = "%s: %s, %.2fkg X %i\n";
}

string *exerciseName = &(nameByExercise.data[entry.exerciseId]);
if (exerciseName->str == 0) {
for (EachIn(db->entries, j)) {
GymLogDbParsedEntry dbEntry = db->entries.data[j];
if (dbEntry.id == entry.exerciseId) {
*exerciseName = dbEntry.name;
}
}
}

printf(format,
cstring(arena, formatTimeHms(arena, &timestamp)),
exerciseName->str ? cstring(arena, *exerciseName) : "unknown-exercise",
entry.weightRepsInfo.weight,
entry.weightRepsInfo.reps);

if (i > 0) {
gmtime_s(&timestamp, (time_t *)&logEntries.data[i - 1].timestamp);
}

if (i == 0 || timestamp.tm_yday != currentDay || timestamp.tm_year != currentYear) {
puts("");
puts("Work summary:");
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]);
}
}
zeroListFull(&workPerExerciseByDay);
}
}
}
}

return statusCode;
}

// Syntax: do <exercise-name> weightKg reps
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.");
statusCode = 1;
} else {
newExerciseName = args.data[0];
}

GymLogDbParsedEntry *existingEntry = 0;

if (statusCode == 0) {
GymLogDbParsed *db = parseDb(arena, readEntireFile(arena, DB_FILE_LOCATION));
for (EachIn(db->entries, i)) {
GymLogDbParsedEntry entry = db->entries.data[i];
if (strEql(entry.name, newExerciseName)) {
existingEntry = &entry;
break;
}
}
if (!existingEntry) {
statusCode = 1;
}
}

if (statusCode == 0) {
uint32 exerciseId = existingEntry->id;
size_t parsedCount = 0;
real32 kg = parsePositiveReal32(arena, 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.");
statusCode = 1;
} else {
GymLogEntry entry = {
getSystemUnixTime(),
exerciseId,
reps,
kg,
};

fileAppend(arena, LOG_FILE_LOCATION, (byte *)&entry, sizeof(entry));
statusCode = gymTrackerWorkForExercise(arena, exerciseId);
}
}

return statusCode;
}

int gymTrackerAddExercise(Arena *arena, list<string> args) {
int statusCode = 0;
string newExerciseName = args.data[0];
if (newExerciseName.length == 0) {
printf("No exercise name provided.");
statusCode = 1;
}

if (statusCode != 1) {
string databaseLocation = DB_FILE_LOCATION;
string database = readEntireFile(arena, databaseLocation);

byte *buf = 0;
size_t newEntryStartIndex = 0;

if (database.length == 0) {
// Initialise DB
newEntryStartIndex = sizeof(GymLogDbHeader);
buf = PushArray(arena, byte, sizeof(GymLogDbHeader) + sizeof(GymLogDbEntry) + newExerciseName.length);
GymLogDbHeader *header = (GymLogDbHeader *)buf;
header->nextId = 1;
} else {
// Validate entry not already present
bool invalid = false;
GymLogDbHeader *header = (GymLogDbHeader *)database.str;
size_t head = sizeof(GymLogDbHeader);
uint32 entriesLeft = header->nextId - 1;
while (entriesLeft > 0 && head < database.length) {
GymLogDbEntry *currentEntry = (GymLogDbEntry *)((byte *)database.str + head);
head += sizeof(GymLogDbEntry);
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);
break;
}
head += currentEntry->nameLength;
}

if (!invalid) {
newEntryStartIndex = database.length;
buf = PushArray(arena, byte, database.length + sizeof(GymLogDbEntry) + newExerciseName.length);
memcpy(buf, database.str, database.length);
} else {
statusCode = 1;
}
}

if (statusCode != 1) {
// Add entry
GymLogDbHeader *header = (GymLogDbHeader *)buf;
GymLogDbEntry *entry = (GymLogDbEntry *)(buf + newEntryStartIndex);
entry->id = header->nextId;
entry->nameLength = (uint32)newExerciseName.length;
header->nextId++;
byte *newExerciseNameDb = buf + newEntryStartIndex + sizeof(GymLogDbEntry);
memcpy(newExerciseNameDb, newExerciseName.str, newExerciseName.length);
size_t bufSize = newEntryStartIndex + sizeof(GymLogDbEntry) + newExerciseName.length;
writeEntireFile(arena, databaseLocation, buf, bufSize);
}
}

return statusCode;
}

int main(int argc, char **argv) {
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.");
statusCode = 1;
}

if (statusCode == 0) {
if (strEql(args.data[0], strlit("status"))) {
statusCode = gymTrackerStatus(arena, listSlice(args, 1));
} else if (strEql(args.data[0], strlit("do"))) {
statusCode = gymTrackerDo(arena, listSlice(args, 1));
} else if (strEql(args.data[0], strlit("add"))) {
statusCode = gymTrackerAddExercise(arena, listSlice(args, 1));
} else {
printf("Unknown command \"%s\"", cstring(arena, args.data[0]));
statusCode = 1;
}
}

return statusCode;
}

+ 3
- 0
build Ver fichero

@@ -0,0 +1,3 @@
#!/bin/bash

gcc -g -g3 ./app.cpp -o ./target/app

+ 26
- 0
build.bat Ver fichero

@@ -0,0 +1,26 @@
@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 incremently 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 -DSLOWMODE=1 -DENVIRONMENT_WINDOWS=1 %= Custom #defines =%^
-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%

+ 484
- 0
core.hpp Ver fichero

@@ -0,0 +1,484 @@
#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;
};

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 <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

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]);
} else {
return 0;
}
}

template <typename T>
void zeroListFull(list<T> *list) {
memset(list->data, 0, list->capacity * sizeof(T));
}

template <typename T>
void zeroList(list<T> *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<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;
}

template <typename T>
list<T> listSlice(list<T> 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<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, 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<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;
}

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(&timestamp, &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 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(&timestamp, &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 buf = PushString(arena, format.length);
strftime(buf.str, buf.length + 1, "%Y-%m-%d", time);
return buf;
}

// ### Logging ###
void print(Arena *arena, list<int> 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<string> 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

+ 3
- 0
run Ver fichero

@@ -0,0 +1,3 @@
#!/bin/bash

./target/app "$@"

Cargando…
Cancelar
Guardar