|
- #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) {
- 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;
- }
-
- bool os_writeEntireFile(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
- bool result = false;
- FILE *output = fopen((char *)filename.str, "w");
- if (output) {
- fwrite(contents, contentsLength, contentsLength, output);
- fclose(output);
- result = true;
- }
- return result;
- }
-
- bool os_fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
- bool result = false;
- FILE *output = fopen((char *)filename.str, "a");
- if (output) {
- fwrite(contents, sizeof(byte), contentsLength, output);
- fclose(output);
- result = true;
- }
- return result;
- }
-
- void os_log(LogTarget target, const char *fmt, va_list argList) {
- Scratch scratch = scratchStart(0, 0);
- string result = strPrintfv(scratch.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(scratch);
- }
-
- #endif
|