Files
djstdlib/os_win32.cpp
Daniel Ledda 28b99e2b83 update
2025-01-16 09:33:37 +01:00

93 lines
3.1 KiB
C++

#ifndef OS_IMPL_WIN32_CPP
#define OS_IMPL_WIN32_CPP
#include "Windows.h"
#include "os.h"
void *os_alloc(size_t commitSize) {
return VirtualAlloc(NULL, commitSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
}
void os_reserve(void *ptr) {
}
void os_decommit(void *ptr) {
}
void os_free(void *ptr, size_t size) {
VirtualFree(ptr, NULL, MEM_RELEASE);
}
string os_readEntireFile(Arena *arena, string filename) {
string result = {0};
HANDLE fileHandle = CreateFileA(cstring(arena, filename), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (fileHandle != INVALID_HANDLE_VALUE) {
LARGE_INTEGER fileSize;
if (GetFileSizeEx(fileHandle, &fileSize)) {
string readfile = PushString(arena, (size_t)fileSize.QuadPart);
if (readfile.str) {
DWORD bytesRead;
if (ReadFile(fileHandle, readfile.str, (DWORD)fileSize.QuadPart, &bytesRead, NULL) && (fileSize.QuadPart == bytesRead)) {
result = readfile;
}
}
}
CloseHandle(fileHandle);
}
return result;
}
bool os_writeEntireFile(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
bool result = false;
HANDLE fileHandle = CreateFileA(cstring(arena, filename), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, NULL, NULL);
if (fileHandle != INVALID_HANDLE_VALUE) {
DWORD bytesWritten;
if (WriteFile(fileHandle, contents, (DWORD)contentsLength, &bytesWritten, NULL)) {
// file written successfully
result = bytesWritten == contentsLength;
}
CloseHandle(fileHandle);
}
return result;
}
bool os_fileAppend(Arena *arena, string filename, const byte *contents, size_t contentsLength) {
bool result = false;
HANDLE fileHandle = CreateFileA(cstring(arena, filename), FILE_APPEND_DATA | FILE_GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (fileHandle != INVALID_HANDLE_VALUE) {
DWORD bytesWritten;
DWORD position = SetFilePointer(fileHandle, 0, NULL, FILE_END);
if (WriteFile(fileHandle, contents, (DWORD)contentsLength, &bytesWritten, NULL)) {
// file written successfully
result = bytesWritten == contentsLength;
}
CloseHandle(fileHandle);
}
return result;
}
function void os_log(LogTarget target, const char *fmt, va_list argList) {
Scratch scratch = scratchStart(0, 0);
string result = strPrintfv(scratch.arena, fmt, argList);
DWORD done;
HANDLE stdHandle;
switch (target) {
case LogTarget_stdin:
stdHandle = GetStdHandle(STD_INPUT_HANDLE);
break;
case LogTarget_stdout:
stdHandle = GetStdHandle(STD_ERROR_HANDLE);
break;
case LogTarget_stderr:
stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
break;
default:
stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
break;
}
WriteFile(stdHandle, result.str, (DWORD)result.length, &done, 0);
scratchEnd(scratch);
}
#endif