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.
 
 
 
 

85 lines
2.2 KiB

  1. #ifndef OS_IMPL_LINUX_CPP
  2. #define OS_IMPL_LINUX_CPP
  3. #include "os.h"
  4. #include <sys/mman.h>
  5. #include <sys/stat.h>
  6. #include <unistd.h>
  7. void *os_alloc(size_t capacity) {
  8. return mmap(0, capacity, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  9. }
  10. void os_commit(void *ptr) {
  11. }
  12. void os_decommit(void *ptr) {
  13. }
  14. void os_free(void *ptr, size_t size) {
  15. int err = munmap(ptr, size);
  16. Assert(err != -1);
  17. }
  18. string os_readEntireFile(Arena *arena, string filename) {
  19. FILE *input = fopen((char *)filename.str, "r");
  20. string readBuffer;
  21. if (input) {
  22. struct stat st;
  23. stat((char *)filename.str, &st);
  24. size_t fsize = st.st_size;
  25. readBuffer = PushString(arena, fsize);
  26. fread(readBuffer.str, sizeof(byte), readBuffer.length, input);
  27. fclose(input);
  28. } else {
  29. readBuffer = PushString(arena, 0);
  30. }
  31. return readBuffer;
  32. }
  33. bool os_writeEntireFile(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
  34. bool result = false;
  35. FILE *output = fopen((char *)filename.str, "w");
  36. if (output) {
  37. fwrite(contents, contentsLength, contentsLength, output);
  38. fclose(output);
  39. result = true;
  40. }
  41. return result;
  42. }
  43. bool os_fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
  44. bool result = false;
  45. FILE *output = fopen((char *)filename.str, "a");
  46. if (output) {
  47. fwrite(contents, sizeof(byte), contentsLength, output);
  48. fclose(output);
  49. result = true;
  50. }
  51. return result;
  52. }
  53. void os_log(LogTarget target, const char *fmt, va_list argList) {
  54. Scratch scratch = scratchStart(0, 0);
  55. string result = strPrintfv(scratch.arena, fmt, argList);
  56. // TODO(djledda): finish implementation without cstdlib
  57. switch (target) {
  58. case LogTarget_stdin:
  59. write(0, (const void *)result.str, result.length);
  60. break;
  61. case LogTarget_stderr:
  62. fflush(stderr);
  63. write(2, (const void *)result.str, result.length);
  64. break;
  65. case LogTarget_stdout:
  66. default:
  67. fflush(stdout);
  68. write(1, (const void *)result.str, result.length);
  69. break;
  70. }
  71. scratchEnd(scratch);
  72. }
  73. #endif