Sfoglia il codice sorgente

first commit

master
Ledda 2 settimane fa
commit
1131d1787c
8 ha cambiato i file con 2695 aggiunte e 0 eliminazioni
  1. +3
    -0
      .clangd
  2. +5
    -0
      .gitignore
  3. +15
    -0
      app.cpp
  4. +3
    -0
      build
  5. +27
    -0
      build.bat
  6. +494
    -0
      core.cpp
  7. +227
    -0
      core.h
  8. +1921
    -0
      vendor/stb_sprintf.h

+ 3
- 0
.clangd Vedi File

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

+ 5
- 0
.gitignore Vedi File

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

+ 15
- 0
app.cpp Vedi File

@@ -0,0 +1,15 @@
#include <math.h>
#include "core.cpp"

int main(int argc, char **argv) {
int statusCode = 0;
initialiseCore();
Arena *arena = arenaAlloc(Megabytes(64));
list<string> args = getArgs(arena, argc, argv);

{
log("teststr: %S :teststrend", strlit("teststring hahaha"));
};

return statusCode;
}

+ 3
- 0
build Vedi File

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

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

+ 27
- 0
build.bat Vedi File

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

+ 494
- 0
core.cpp Vedi File

@@ -0,0 +1,494 @@
#define STB_SPRINTF_IMPLEMENTATION
#include "core.h"

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) {
#if OS_WINDOWS
Arena *result = (Arena *)VirtualAlloc(NULL, sizeof(Arena) + capacity, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
#elif OS_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 OS_WINDOWS
VirtualFree(arena, NULL, MEM_RELEASE);
#elif OS_LINUX
// TODO(dledda): implement this for Linux
Assert(false);
#endif
}

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

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));
}

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(dledda): 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(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.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 *)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 OS_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;
#elif OS_LINUX
Assert(false);
#endif
}

bool fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
#if OS_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;
#elif OS_LINUX
Assert(false);
#endif
}

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 = strlit("HH-MM-SS");
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 = strlit("HH-MM-SS");
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 = strlit("YYYY-mm-dd");
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 = strlit("YYYY-mm-dd");
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(dledda): implementation
Assert(false);
#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);
}


+ 227
- 0
core.h Vedi File

@@ -0,0 +1,227 @@
#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(dledda): try not to depend on this one

#if OS_WINDOWS
#include "Windows.h"
#elif OS_LINUX
#include <sys/mman.h>
#include <sys/stat.h>
#else
#error Development environment not supported.
#endif

// ### 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 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) })

// 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(dledda): 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.length; it++
#define EachInReversed(list, it) size_t it = list.length - 1; it >= 0 && it < list.length; it--
#define EachInArray(arr, it) size_t it = 0; it < ArrayCount(arr); ++it

// ### Misc ###
int intCompare(const void *a, const void *b);

#endif

+ 1921
- 0
vendor/stb_sprintf.h
File diff soppresso perché troppo grande
Vedi File


Caricamento…
Annulla
Salva