Files
corelang/base.kl
2022-06-13 23:44:40 +02:00

58 lines
1.4 KiB
Plaintext

Windows :: #import "Windows.kl"
#import "Windows.kl"
SizeU :: #strict U64
OS_PAGE_SIZE :: 4096
OS_Memory :: struct
commit : SizeU
reserve: SizeU
data : *U8
Arena :: struct
memory: OS_Memory
alignment: U64
len: SizeU
clamp_top_sizeu :: (val: SizeU, max: SizeU): SizeU
if val > max
return max
return val
get_align_offset :: (size: SizeU, align: SizeU): SizeU
mask := align - 1
val := size & mask
if val != 0
val = align - val
return val
align_up :: (size: SizeU, align: SizeU): SizeU
result := size + get_align_offset(size, align)
return result
reserve :: (size: SizeU): OS_Memory
result := OS_Memory{reserve=align_up(size, OS_PAGE_SIZE)}
result.data = Windows.VirtualAlloc(
flProtect = Windows.PAGE_READWRITE,
dwSize = result.reserve,
flAllocationType = Windows.MEM_RESERVE,
lpAddress = 0)->*U8
return result
commit :: (m: *OS_Memory, size: SizeU): Bool
commit_size := align_up(size, OS_PAGE_SIZE)
total_commit := m.commit + commit_size
clamped_commit := clamp_top_sizeu(total_commit, m.reserve)
adjusted_commit := clamped_commit - m.commit
if adjusted_commit != 0
result := Windows.VirtualAlloc(
lpAddress = (m.data + m.commit)->*void,
dwSize = adjusted_commit,
flAllocationType = Windows.MEM_COMMIT,
flProtect = Windows.PAGE_READWRITE,
)
m.commit += adjusted_commit
return true
return false