default_temporary_allocator.odin 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package runtime
  2. DEFAULT_TEMP_ALLOCATOR_BACKING_SIZE: int : #config(DEFAULT_TEMP_ALLOCATOR_BACKING_SIZE, 4 * Megabyte)
  3. NO_DEFAULT_TEMP_ALLOCATOR: bool : ODIN_OS == .Freestanding || ODIN_OS == .JS || ODIN_DEFAULT_TO_NIL_ALLOCATOR
  4. when NO_DEFAULT_TEMP_ALLOCATOR {
  5. Default_Temp_Allocator :: struct {}
  6. default_temp_allocator_init :: proc(s: ^Default_Temp_Allocator, size: int, backing_allocator := context.allocator) {}
  7. default_temp_allocator_destroy :: proc(s: ^Default_Temp_Allocator) {}
  8. default_temp_allocator_proc :: nil_allocator_proc
  9. @(require_results)
  10. default_temp_allocator_temp_begin :: proc(loc := #caller_location) -> (temp: Arena_Temp) {
  11. return
  12. }
  13. default_temp_allocator_temp_end :: proc(temp: Arena_Temp, loc := #caller_location) {
  14. }
  15. } else {
  16. Default_Temp_Allocator :: struct {
  17. arena: Arena,
  18. }
  19. default_temp_allocator_init :: proc(s: ^Default_Temp_Allocator, size: int, backing_allocator := context.allocator) {
  20. _ = arena_init(&s.arena, uint(size), backing_allocator)
  21. }
  22. default_temp_allocator_destroy :: proc(s: ^Default_Temp_Allocator) {
  23. if s != nil {
  24. arena_destroy(&s.arena)
  25. s^ = {}
  26. }
  27. }
  28. default_temp_allocator_proc :: proc(allocator_data: rawptr, mode: Allocator_Mode,
  29. size, alignment: int,
  30. old_memory: rawptr, old_size: int, loc := #caller_location) -> (data: []byte, err: Allocator_Error) {
  31. s := (^Default_Temp_Allocator)(allocator_data)
  32. return arena_allocator_proc(&s.arena, mode, size, alignment, old_memory, old_size, loc)
  33. }
  34. @(require_results)
  35. default_temp_allocator_temp_begin :: proc(loc := #caller_location) -> (temp: Arena_Temp) {
  36. if context.temp_allocator.data == &global_default_temp_allocator_data {
  37. temp = arena_temp_begin(&global_default_temp_allocator_data.arena, loc)
  38. }
  39. return
  40. }
  41. default_temp_allocator_temp_end :: proc(temp: Arena_Temp, loc := #caller_location) {
  42. arena_temp_end(temp, loc)
  43. }
  44. @(fini, private)
  45. _destroy_temp_allocator_fini :: proc() {
  46. default_temp_allocator_destroy(&global_default_temp_allocator_data)
  47. }
  48. }
  49. @(deferred_out=default_temp_allocator_temp_end)
  50. DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD :: #force_inline proc(ignore := false, loc := #caller_location) -> (Arena_Temp, Source_Code_Location) {
  51. if ignore {
  52. return {}, loc
  53. } else {
  54. return default_temp_allocator_temp_begin(loc), loc
  55. }
  56. }
  57. default_temp_allocator :: proc(allocator: ^Default_Temp_Allocator) -> Allocator {
  58. return Allocator{
  59. procedure = default_temp_allocator_proc,
  60. data = allocator,
  61. }
  62. }