100 lines
2.5 KiB
C
100 lines
2.5 KiB
C
#ifndef OS_IMPL_LINUX_C
|
|
#define OS_IMPL_LINUX_C
|
|
|
|
#include "os.h"
|
|
|
|
#include "sys/mman.h"
|
|
#include "sys/stat.h"
|
|
#include "unistd.h" // POSIX Standard
|
|
#include "stdio.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_print(StdStream 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 StdStream_stdin:
|
|
write(0, (const void *)result.str, result.length);
|
|
break;
|
|
case StdStream_stderr:
|
|
fflush(stderr);
|
|
write(2, (const void *)result.str, result.length);
|
|
break;
|
|
case StdStream_stdout:
|
|
default:
|
|
fflush(stdout);
|
|
write(1, (const void *)result.str, result.length);
|
|
break;
|
|
}
|
|
|
|
scratchEnd(temp);
|
|
}
|
|
|
|
#endif
|