Commit fd5a5db400

Andrew Kelley <superjoe30@gmail.com>
2017-09-28 04:59:58
implement IncrementingAllocator for Windows
1 parent 9ae66b4
Changed files (2)
std
os
windows
std/os/windows/index.zig
@@ -39,6 +39,11 @@ pub extern "kernel32" stdcallcc fn WriteFile(in_hFile: HANDLE, in_lpBuffer: &con
 
 pub extern "kernel32" stdcallcc fn Sleep(dwMilliseconds: DWORD);
 
+pub extern "kernel32" stdcallcc fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID;
+
+pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL;
+
+pub extern "kernel32" stdcallcc fn GetProcessHeap() -> HANDLE;
 
 pub extern "user32" stdcallcc fn MessageBoxA(hWnd: ?HANDLE, lpText: ?LPCTSTR, lpCaption: ?LPCTSTR, uType: UINT) -> c_int;
 
@@ -50,6 +55,7 @@ pub const LPWSTR = &WCHAR;
 pub const LPSTR = &CHAR;
 pub const CHAR = u8;
 pub const PWSTR = &WCHAR;
+pub const SIZE_T = usize;
 
 pub const BOOL = bool;
 pub const BYTE = u8;
std/mem.zig
@@ -86,12 +86,34 @@ pub const IncrementingAllocator = struct {
                     .end_index = 0,
                 };
             },
+            Os.windows => {
+                const heap_handle = os.windows.GetProcessHeap();
+                const ptr = os.windows.HeapAlloc(heap_handle, 0, capacity);
+                return IncrementingAllocator {
+                    .allocator = Allocator {
+                        .allocFn = alloc,
+                        .reallocFn = realloc,
+                        .freeFn = free,
+                    },
+                    .bytes = @ptrCast(&u8, ptr)[0..capacity],
+                    .end_index = 0,
+                };
+            },
             else => @compileError("Unsupported OS"),
         }
     }
 
     fn deinit(self: &IncrementingAllocator) {
-        _ = os.posix.munmap(self.bytes.ptr, self.bytes.len);
+        switch (builtin.os) {
+            Os.linux, Os.darwin, Os.macosx, Os.ios => {
+                _ = os.posix.munmap(self.bytes.ptr, self.bytes.len);
+            },
+            Os.windows => {
+                const heap_handle = os.windows.GetProcessHeap();
+                _ = os.windows.HeapFree(heap_handle, 0, @ptrCast(os.windows.LPVOID, self.bytes.ptr));
+            },
+            else => @compileError("Unsupported OS"),
+        }
     }
 
     fn reset(self: &IncrementingAllocator) {