Skip to content

Instantly share code, notes, and snippets.

@Tetralux
Last active March 26, 2023 10:36
Show Gist options
  • Save Tetralux/b97ddfe18754ead7617c075ed634f147 to your computer and use it in GitHub Desktop.
Save Tetralux/b97ddfe18754ead7617c075ed634f147 to your computer and use it in GitHub Desktop.
Back of the envolope counting allocator implementation
import "core:mem"
import "core:runtime"
Counting_Allocator :: struct {
total_used: uint,
backing_ally: mem.Allocator,
}
counting_allocator :: proc(ca: ^Counting_Allocator) -> mem.Allocator {
return {
data = ca,
procedure = counting_allocator_proc,
}
}
counting_allocator_proc :: proc(allocator_data: rawptr, mode: mem.Allocator_Mode,
size, alignment: int,
old_memory: rawptr, old_size: int,
location: runtime.Source_Code_Location = #caller_location) -> ([]byte, mem.Allocator_Error) {
ca := (^Counting_Allocator)(allocator_data)
switch mode {
case .Alloc:
memory, err := mem.alloc_bytes(size, alignment, ca.backing_ally)
if err != nil do return nil, err
ca.total_used += cast(uint) len(memory)
return memory, nil
case .Resize:
old_slice := ([^]byte)(old_memory)[:old_size]
memory, err := mem.resize_bytes(old_slice, size, alignment, ca.backing_ally)
if err != nil do return nil, err
ca.total_used -= cast(uint) len(old_slice)
ca.total_used += cast(uint) len(memory)
return memory, nil
case .Free:
old_slice := ([^]byte)(old_memory)[:old_size]
err := mem.free_bytes(old_slice, ca.backing_ally)
if err != nil do return nil, err
ca.total_used -= cast(uint) len(old_slice)
return nil, nil
case .Free_All:
ca.total_used = 0
return nil, nil
case .Query_Info, .Query_Features:
return nil, nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment