virtual_platform.odin 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //+private
  2. package mem_virtual
  3. import "core:sync"
  4. Platform_Memory_Block :: struct {
  5. block: Memory_Block,
  6. committed: uint,
  7. reserved: uint,
  8. prev, next: ^Platform_Memory_Block,
  9. }
  10. platform_memory_alloc :: proc "contextless" (to_commit, to_reserve: uint) -> (block: ^Platform_Memory_Block, err: Allocator_Error) {
  11. to_commit, to_reserve := to_commit, to_reserve
  12. to_reserve = max(to_commit, to_reserve)
  13. total_to_reserved := max(to_reserve, size_of(Platform_Memory_Block))
  14. to_commit = clamp(to_commit, size_of(Platform_Memory_Block), total_to_reserved)
  15. data := reserve(total_to_reserved) or_return
  16. commit(raw_data(data), to_commit)
  17. block = (^Platform_Memory_Block)(raw_data(data))
  18. block.committed = to_commit
  19. block.reserved = to_reserve
  20. return
  21. }
  22. platform_memory_free :: proc "contextless" (block: ^Platform_Memory_Block) {
  23. if block != nil {
  24. release(block, block.reserved)
  25. }
  26. }
  27. platform_mutex_lock :: proc() {
  28. sync.mutex_lock(&global_memory_block_mutex)
  29. }
  30. platform_mutex_unlock :: proc() {
  31. sync.mutex_unlock(&global_memory_block_mutex)
  32. }
  33. global_memory_block_mutex: sync.Mutex
  34. global_platform_memory_block_sentinel: Platform_Memory_Block
  35. global_platform_memory_block_sentinel_set: bool
  36. @(init)
  37. platform_memory_init :: proc() {
  38. if !global_platform_memory_block_sentinel_set {
  39. _platform_memory_init()
  40. global_platform_memory_block_sentinel.prev = &global_platform_memory_block_sentinel
  41. global_platform_memory_block_sentinel.next = &global_platform_memory_block_sentinel
  42. global_platform_memory_block_sentinel_set = true
  43. }
  44. }
  45. platform_memory_commit :: proc "contextless" (block: ^Platform_Memory_Block, to_commit: uint) -> (err: Allocator_Error) {
  46. if to_commit < block.committed {
  47. return nil
  48. }
  49. if to_commit > block.reserved {
  50. return .Out_Of_Memory
  51. }
  52. commit(block, to_commit) or_return
  53. block.committed = to_commit
  54. return nil
  55. }