Improve the Allocator interface to support returning Allocator_Error to allow for safer calls

Virtually all code (except for user-written custom allocators) should work as normal. Extra features will need to be added to make the current procedures support the `Allocator_Error` return value (akin to #optional_ok)
This commit is contained in:
gingerBill
2021-04-19 12:31:31 +01:00
parent a4d0092b16
commit f98c4d6837
13 changed files with 386 additions and 276 deletions
+14 -9
View File
@@ -133,7 +133,12 @@ read_ptr :: proc(fd: Handle, data: rawptr, len: int) -> (int, Errno) {
heap_allocator_proc :: proc(allocator_data: rawptr, mode: mem.Allocator_Mode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64 = 0, loc := #caller_location) -> rawptr {
old_memory: rawptr, old_size: int, loc := #caller_location) -> ([]byte, mem.Allocator_Error) {
byte_slice :: #force_inline proc "contextless" (data: rawptr, len: int) -> (res: []byte) {
r := (^mem.Raw_Slice)(&res);
r.data, r.len = data, len;
return;
}
//
// NOTE(tetra, 2020-01-14): The heap doesn't respect alignment.
@@ -142,7 +147,7 @@ heap_allocator_proc :: proc(allocator_data: rawptr, mode: mem.Allocator_Mode,
// the pointer we return to the user.
//
aligned_alloc :: proc(size, alignment: int, old_ptr: rawptr = nil) -> rawptr {
aligned_alloc :: proc(size, alignment: int, old_ptr: rawptr = nil) -> ([]byte, mem.Allocator_Error) {
a := max(alignment, align_of(rawptr));
space := size + a - 1;
@@ -159,13 +164,13 @@ heap_allocator_proc :: proc(allocator_data: rawptr, mode: mem.Allocator_Mode,
aligned_ptr := (ptr - 1 + uintptr(a)) & -uintptr(a);
diff := int(aligned_ptr - ptr);
if (size + diff) > space {
return nil;
return nil, .Out_Of_Memory;
}
aligned_mem = rawptr(aligned_ptr);
mem.ptr_offset((^rawptr)(aligned_mem), -1)^ = allocated_mem;
return aligned_mem;
return byte_slice(aligned_mem, size), .None;
}
aligned_free :: proc(p: rawptr) {
@@ -174,9 +179,9 @@ heap_allocator_proc :: proc(allocator_data: rawptr, mode: mem.Allocator_Mode,
}
}
aligned_resize :: proc(p: rawptr, old_size: int, new_size: int, new_alignment: int) -> rawptr {
aligned_resize :: proc(p: rawptr, old_size: int, new_size: int, new_alignment: int) -> ([]byte, mem.Allocator_Error) {
if p == nil {
return nil;
return nil, nil;
}
return aligned_alloc(new_size, new_alignment, p);
}
@@ -202,13 +207,13 @@ heap_allocator_proc :: proc(allocator_data: rawptr, mode: mem.Allocator_Mode,
if set != nil {
set^ = {.Alloc, .Free, .Resize, .Query_Features};
}
return set;
return byte_slice(set, size_of(set^)), .None;
case .Query_Info:
return nil;
return nil, nil;
}
return nil;
return nil, nil;
}
heap_allocator :: proc() -> mem.Allocator {