You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

485 regels
13 KiB

  1. #ifndef CORE_HPP
  2. #define CORE_HPP
  3. #include <time.h>
  4. #include <math.h>
  5. #include <stdint.h>
  6. #include <stdio.h>
  7. #if ENVIRONMENT_WINDOWS
  8. #include "Windows.h"
  9. #endif
  10. #if ENVIRONMENT_LINUX
  11. #include <sys/mman.h>
  12. #include <sys/stat.h>
  13. #endif
  14. // ### Misc macros ###
  15. #if SLOWMODE
  16. #define Assert(expression) if (!(expression)) {*(volatile int *)0 = 0;}
  17. #else
  18. #define Assert(expression)
  19. #endif
  20. // ### Types ###
  21. typedef int8_t int8;
  22. typedef int16_t int16;
  23. typedef int32_t int32;
  24. typedef int64_t int64;
  25. typedef uint8_t uint8;
  26. typedef uint16_t uint16;
  27. typedef uint32_t uint32;
  28. typedef uint64_t uint64;
  29. typedef uint8_t byte;
  30. typedef float real32;
  31. typedef double real64;
  32. // ### Sizes and Numbers ###
  33. #define Bytes(n) (n)
  34. #define Kilobytes(n) (n << 10)
  35. #define Megabytes(n) (n << 20)
  36. #define Gigabytes(n) (((uint64)n) << 30)
  37. #define Terabytes(n) (((uint64)n) << 40)
  38. #define Thousand(n) ((n)*1000)
  39. #define Million(n) ((n)*1000000)
  40. #define Billion(n) ((n)*1000000000LL)
  41. #define ArrayCount(arr) (sizeof(arr) / sizeof((arr)[0]))
  42. // ### Arenas ###
  43. struct Arena {
  44. void *memory;
  45. size_t capacity;
  46. size_t head;
  47. };
  48. void *pushSize(Arena *arena, size_t bytes) {
  49. if (arena->capacity - arena->head >= bytes) {
  50. void *ptr = (char *)arena->memory + arena->head;
  51. arena->head += bytes;
  52. return ptr;
  53. }
  54. return 0;
  55. }
  56. #define PushArray(arena, type, size) (type *)pushSize(arena, sizeof(type) * (size))
  57. #define PushStruct(arena, type) (type *)pushSize(arena, sizeof(type))
  58. Arena *arenaAlloc(size_t capacity) {
  59. #if ENVIRONMENT_WINDOWS
  60. Arena *result = (Arena *)VirtualAlloc(NULL, sizeof(Arena) + capacity, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  61. #endif
  62. #if ENVIRONMENT_LINUX
  63. Arena *result = (Arena *)mmap(0, capacity, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  64. #endif
  65. result->memory = result + sizeof(Arena);
  66. result->capacity = capacity;
  67. result->head = 0;
  68. return result;
  69. }
  70. void arenaFree(Arena *arena) {
  71. #if ENVIRONMENT_WINDOWS
  72. VirtualFree(arena, NULL, MEM_RELEASE);
  73. #endif
  74. #if ENVIRONMENT_LINUX
  75. // TODO(dledda): implement this for Linux
  76. #endif
  77. }
  78. // ### Lists ###
  79. template <typename T>
  80. struct list {
  81. T* data;
  82. size_t capacity;
  83. size_t length;
  84. };
  85. #define PushList(arena, type, size) (list<type>{ PushArray(arena, type, size), size, 0 })
  86. #define PushFullList(arena, type, size) (list<type>{ PushArray(arena, type, size), size, size })
  87. #define EachIn(list, it) size_t it = 0; it < list.length; it++
  88. #define EachInReversed(list, it) size_t it = list.length - 1; it >= 0 && it < list.length; it--
  89. // TODO(dledda): test assignment in for loop?
  90. #define EachInArray(arr, it) size_t it = 0; it < ArrayCount(arr); ++it
  91. template <typename T>
  92. T *appendList(list<T> *list, T element) {
  93. if (list->length < list->capacity) {
  94. list->data[list->length] = element;
  95. list->length++;
  96. return &(list->data[list->length - 1]);
  97. } else {
  98. return 0;
  99. }
  100. }
  101. template <typename T>
  102. void zeroListFull(list<T> *list) {
  103. memset(list->data, 0, list->capacity * sizeof(T));
  104. }
  105. template <typename T>
  106. void zeroList(list<T> *list) {
  107. list->length = 0;
  108. memset(list->data, 0, list->capacity * sizeof(T));
  109. }
  110. // ### Strings ###
  111. #define strlit(lit) (string{(char *)(lit), sizeof(lit) - 1})
  112. struct string {
  113. char *str;
  114. size_t length;
  115. };
  116. #define PushString(arena, length) (string{ (char *)pushSize(arena, length), (length) })
  117. const char *cstring(Arena *arena, list<char> buf) {
  118. char *arr = PushArray(arena, char, buf.length + 1);
  119. memmove(arr, buf.data, buf.length);
  120. arr[buf.length] = '\0';
  121. return arr;
  122. }
  123. const char *cstring(Arena *arena, string str) {
  124. char *arr = PushArray(arena, char, str.length + 1);
  125. memmove(arr, str.str, str.length);
  126. arr[str.length] = '\0';
  127. return arr;
  128. }
  129. bool strEql(string s1, string s2) {
  130. if (s1.length != s2.length) {
  131. return false;
  132. }
  133. for (size_t i = 0; i < s1.length; i++) {
  134. if (s1.str[i] != s2.str[i]) {
  135. return false;
  136. }
  137. }
  138. return true;
  139. }
  140. size_t calcStringLen(const char *str) {
  141. size_t size = 0;
  142. if (str == NULL) {
  143. return size;
  144. }
  145. while (str[size] != '\0') {
  146. size++;
  147. }
  148. return size;
  149. }
  150. string strFromCString(Arena *arena, const char *str) {
  151. string result = PushString(arena, calcStringLen(str));
  152. memcpy(result.str, str, result.length);
  153. return result;
  154. }
  155. string strReverse(Arena *arena, string str) {
  156. string reversed = PushString(arena, str.length);
  157. for (
  158. size_t mainIndex = str.length - 1, reversedIndex = 0;
  159. mainIndex < str.length;
  160. mainIndex--, reversedIndex++
  161. ) {
  162. reversed.str[reversedIndex] = str.str[mainIndex];
  163. }
  164. return reversed;
  165. }
  166. template <typename T>
  167. list<T> listSlice(list<T> l, size_t start, size_t stop = 0) {
  168. if (stop == 0) {
  169. stop = l.length;
  170. }
  171. // TODO(dledda): maybe assert instead
  172. if (stop > l.length || start > stop) {
  173. return {0};
  174. }
  175. return {
  176. l.data + start,
  177. stop - start,
  178. stop - start,
  179. };
  180. }
  181. string strSlice(string str, size_t start, size_t stop = 0) {
  182. if (stop == 0) {
  183. stop = str.length;
  184. }
  185. // TODO(dledda): maybe assert instead
  186. if (stop > str.length || start > stop) {
  187. return {0};
  188. }
  189. return {
  190. str.str + start,
  191. stop - start,
  192. };
  193. }
  194. string strSlice(char *data, size_t start, size_t stop) {
  195. return {
  196. data + start,
  197. stop - start,
  198. };
  199. }
  200. bool stringContains(string str, char c) {
  201. for (size_t i = 0; i < str.length; i++) {
  202. if (str.str[i] == c) {
  203. return true;
  204. }
  205. }
  206. return false;
  207. }
  208. const char NUMERIC_CHARS[] = "0123456789";
  209. inline bool isNumeric(char c) {
  210. return stringContains(strlit(NUMERIC_CHARS), c);
  211. }
  212. list<string> strSplit(Arena *arena, string splitStr, string inputStr) {
  213. list<string> result = {0};
  214. if (inputStr.length > 0) {
  215. size_t splitCount = 0;
  216. size_t c = 0;
  217. size_t start = 0;
  218. void *beginning = (char *)arena->memory + arena->head;
  219. while (c < inputStr.length - splitStr.length) {
  220. if (strEql(strSlice(inputStr, c, splitStr.length), splitStr)) {
  221. string *splitString = PushStruct(arena, string);
  222. splitString->str = inputStr.str + start;
  223. splitString->length = c - start;
  224. splitCount++;
  225. start = c + 1;
  226. }
  227. c++;
  228. }
  229. string *splitString = PushStruct(arena, string);
  230. splitString->str = inputStr.str + start;
  231. splitString->length = inputStr.length - start;
  232. splitCount++;
  233. result.data = (string *)beginning,
  234. result.capacity = splitCount,
  235. result.length = splitCount;
  236. }
  237. return result;
  238. }
  239. int8 parsePositiveInt(string str, size_t *lengthPointer) {
  240. size_t numEnd = 0;
  241. char currChar = str.str[numEnd];
  242. while (numEnd < str.length && isNumeric(currChar)) {
  243. currChar = str.str[++numEnd];
  244. *lengthPointer += 1;
  245. }
  246. *lengthPointer -= 1;
  247. if (numEnd > 0) {
  248. uint8 result = 0;
  249. for (size_t i = 0; i < numEnd; i++) {
  250. result *= 10;
  251. result += str.str[i] - '0';
  252. }
  253. return result;
  254. } else {
  255. return -1;
  256. }
  257. }
  258. real32 parsePositiveReal32(Arena *arena, string str, size_t *lengthPointer) {
  259. real32 result = NAN;
  260. string wholePartStr = string{0};
  261. string fractionalPartStr = string{0};
  262. bool split = false;
  263. size_t c = 0;
  264. while (c < str.length) {
  265. if (str.str[c] == '.') {
  266. wholePartStr.str = str.str;
  267. wholePartStr.length = c;
  268. fractionalPartStr.str = str.str + c + 1;
  269. fractionalPartStr.length = str.length - c - 1;
  270. split = true;
  271. break;
  272. }
  273. c++;
  274. }
  275. if (split) {
  276. int wholePart = parsePositiveInt(wholePartStr, lengthPointer);
  277. *lengthPointer += 1;
  278. int fractionalPart = parsePositiveInt(fractionalPartStr, lengthPointer);
  279. if (wholePart >= 0 && fractionalPart >= 0) {
  280. real32 fractionalPartMultiplier = 1.0f / powf(10.0f, (real32)fractionalPartStr.length);
  281. result = (real32)wholePart + (real32)fractionalPart * (real32)fractionalPartMultiplier;
  282. }
  283. } else if (c > 0) {
  284. result = (real32)parsePositiveInt(str, lengthPointer);
  285. }
  286. return result;
  287. }
  288. // ### File IO ###
  289. string readEntireFile(Arena *arena, string filename) {
  290. #if ENVIRONMENT_WINDOWS
  291. string result = {0};
  292. HANDLE fileHandle = CreateFileA(cstring(arena, filename), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
  293. if (fileHandle != INVALID_HANDLE_VALUE) {
  294. LARGE_INTEGER fileSize;
  295. if (GetFileSizeEx(fileHandle, &fileSize)) {
  296. string readfile = PushString(arena, (size_t)fileSize.QuadPart);
  297. if (readfile.str) {
  298. DWORD bytesRead;
  299. if (ReadFile(fileHandle, readfile.str, (DWORD)fileSize.QuadPart, &bytesRead, NULL) && (fileSize.QuadPart == bytesRead)) {
  300. result = readfile;
  301. }
  302. }
  303. }
  304. CloseHandle(fileHandle);
  305. }
  306. return result;
  307. #endif
  308. #if ENVIRONMENT_LINUX
  309. FILE *input = fopen((char *)file.str, "r");
  310. struct stat st;
  311. stat((char *)file.str, &st);
  312. size_t fsize = st.st_size;
  313. string readBuffer = PushString(arena, filesize);
  314. readBuffer.length = filesize;
  315. fread(readBuffer.str, sizeof(byte), filesize, input);
  316. fclose(input);
  317. return readBuffer;
  318. #endif
  319. }
  320. bool writeEntireFile(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
  321. #if ENVIRONMENT_WINDOWS
  322. bool result = false;
  323. HANDLE fileHandle = CreateFileA(cstring(arena, filename), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, NULL, NULL);
  324. if (fileHandle != INVALID_HANDLE_VALUE) {
  325. DWORD bytesWritten;
  326. if (WriteFile(fileHandle, contents, (DWORD)contentsLength, &bytesWritten, NULL)) {
  327. // file written successfully
  328. result = bytesWritten == contentsLength;
  329. }
  330. CloseHandle(fileHandle);
  331. }
  332. return result;
  333. #endif
  334. #if ENVIRONMENT_LINUX
  335. Assert(false);
  336. #endif
  337. }
  338. bool fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
  339. #if ENVIRONMENT_WINDOWS
  340. bool result = false;
  341. HANDLE fileHandle = CreateFileA(cstring(arena, filename), FILE_APPEND_DATA | FILE_GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  342. if (fileHandle != INVALID_HANDLE_VALUE) {
  343. DWORD bytesWritten;
  344. DWORD position = SetFilePointer(fileHandle, 0, NULL, FILE_END);
  345. if (WriteFile(fileHandle, contents, (DWORD)contentsLength, &bytesWritten, NULL)) {
  346. // file written successfully
  347. result = bytesWritten == contentsLength;
  348. }
  349. CloseHandle(fileHandle);
  350. }
  351. return result;
  352. #endif
  353. #if ENVIRONMENT_LINUX
  354. Assert(false);
  355. #endif
  356. }
  357. // ### Misc ###
  358. int cmpint(const void *a, const void *b) {
  359. int *x = (int *)a;
  360. int *y = (int *)b;
  361. return (*x > *y) - (*x < *y);
  362. }
  363. list<string> getArgs(Arena *arena, int argc, char **argv) {
  364. list<string> args = PushList(arena, string, (size_t)argc);
  365. for (int i = 1; i < argc; i++) {
  366. appendList(&args, strFromCString(arena, argv[i]));
  367. }
  368. return args;
  369. }
  370. uint64 getSystemUnixTime() {
  371. time_t now;
  372. time(&now);
  373. return now;
  374. }
  375. string formatTimeHms(Arena *arena, time_t time) {
  376. static const string format = strlit("HH-MM-SS");
  377. string buf = PushString(arena, format.length);
  378. tm timestamp;
  379. gmtime_s(&timestamp, &time);
  380. strftime(buf.str, buf.length + 1, "%T", &timestamp);
  381. return buf;
  382. }
  383. string formatTimeHms(Arena *arena, tm *time) {
  384. static const string format = strlit("HH-MM-SS");
  385. string buf = PushString(arena, format.length);
  386. strftime(buf.str, buf.length + 1, "%T", time);
  387. return buf;
  388. }
  389. string formatTimeYmd(Arena *arena, time_t time) {
  390. static const string format = strlit("YYYY-mm-dd");
  391. string buf = PushString(arena, format.length);
  392. tm timestamp;
  393. gmtime_s(&timestamp, &time);
  394. strftime(buf.str, buf.length + 1, "%Y-%m-%d", &timestamp);
  395. return buf;
  396. }
  397. string formatTimeYmd(Arena *arena, tm *time) {
  398. static const string format = strlit("YYYY-mm-dd");
  399. string buf = PushString(arena, format.length);
  400. strftime(buf.str, buf.length + 1, "%Y-%m-%d", time);
  401. return buf;
  402. }
  403. // ### Logging ###
  404. void print(Arena *arena, list<int> l) {
  405. for (size_t i = 0; i < l.length; i++) {
  406. if (i != 0) {
  407. printf(", ");
  408. } else {
  409. printf("{ ");
  410. }
  411. printf("%i", l.data[i]);
  412. }
  413. printf(" } length: %zu, capacity: %zu\n", l.capacity, l.length);
  414. }
  415. void print(Arena *arena, list<string> l) {
  416. for (size_t i = 0; i < l.length; i++) {
  417. if (i != 0) {
  418. printf(", ");
  419. } else {
  420. printf("{ ");
  421. }
  422. printf("\"%s\"", cstring(arena, l.data[i]));
  423. }
  424. printf(" } length: %zu, capacity: %zu\n", l.capacity, l.length);
  425. }
  426. #endif