|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- #ifndef OS_IMPL_LINUX_CPP
- #define OS_IMPL_LINUX_CPP
-
- #include "os.h"
-
- #include <sys/mman.h>
- #include <sys/stat.h>
- #include <unistd.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);
- }
-
- string os_readEntireFile(Arena *arena, string filename) {
- Scratch temp = scratchStart(&arena, 1);
-
- FILE *input = fopen(cstring(temp.arena, filename), "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);
- }
-
- scratchEnd(temp);
- return readBuffer;
- }
-
- bool os_writeEntireFile(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
- Scratch temp = scratchStart(&arena, 1);
-
- bool result = false;
- FILE *output = fopen(cstring(temp.arena, filename), "w");
- if (output) {
- fwrite(contents, sizeof(byte), contentsLength, output);
- fclose(output);
- result = true;
- }
-
- scratchEnd(temp);
- return result;
- }
-
- bool os_fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
- Scratch temp = scratchStart(&arena, 1);
-
- bool result = false;
- FILE *output = fopen(cstring(temp.arena, filename), "a");
- if (output) {
- fwrite(contents, sizeof(byte), contentsLength, output);
- fclose(output);
- result = true;
- }
-
- scratchEnd(temp);
- return result;
- }
-
- void os_log(LogTarget target, const char *fmt, va_list argList) {
- Scratch temp = scratchStart(0, 0);
-
- string result = strPrintfv(temp.arena, fmt, argList);
- // 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;
- }
-
- scratchEnd(temp);
- }
-
- #endif
|