add realloc (and update c_allocator)
This commit is contained in:
@@ -3,6 +3,7 @@ c :: import "@ffi/c"
|
||||
Allocator :: struct {
|
||||
context ?*mut anyopaque
|
||||
alloc @func(context ?*mut anyopaque, size usize, alignment usize) ?*mut u8
|
||||
realloc @func(context ?*mut anyopaque, memory ?*mut u8, old_size usize, new_size usize, alignment usize) ?*mut u8
|
||||
free @func(context ?*mut anyopaque, memory ?*mut u8, size usize, alignment usize) void
|
||||
}
|
||||
|
||||
@@ -43,6 +44,39 @@ _c_alloc func(_ ?*mut anyopaque, size usize, alignment usize) ?*mut u8 {
|
||||
return ptr_cast(u8, memory[0])
|
||||
}
|
||||
|
||||
_c_realloc func(_ ?*mut anyopaque, memory ?*mut u8, old_size usize, new_size usize, alignment usize) ?*mut u8 {
|
||||
if _power_of_two(alignment) == false {
|
||||
return none
|
||||
}
|
||||
|
||||
if new_size == 0 {
|
||||
c.free(memory)
|
||||
return none
|
||||
}
|
||||
|
||||
if memory |old_memory| {
|
||||
if alignment <= _malloc_alignment {
|
||||
return ptr_cast(u8, c.realloc(old_memory, c_ulong(new_size)))
|
||||
}
|
||||
|
||||
new_memory ?*mut u8 = _c_alloc(none, new_size, alignment)
|
||||
if new_memory |new_bytes| {
|
||||
copy_size usize = old_size
|
||||
if new_size < copy_size {
|
||||
copy_size = new_size
|
||||
}
|
||||
i usize = 0
|
||||
while i < copy_size : i += 1 {
|
||||
new_bytes[i] = old_memory[i]
|
||||
}
|
||||
c.free(old_memory)
|
||||
}
|
||||
return new_memory
|
||||
}
|
||||
|
||||
return _c_alloc(none, new_size, alignment)
|
||||
}
|
||||
|
||||
_c_free func(_ ?*mut anyopaque, memory ?*mut u8, _ usize, _ usize) void {
|
||||
c.free(memory)
|
||||
}
|
||||
@@ -50,6 +84,7 @@ _c_free func(_ ?*mut anyopaque, memory ?*mut u8, _ usize, _ usize) void {
|
||||
c_allocator Allocator :: Allocator {
|
||||
context = none,
|
||||
alloc = _c_alloc,
|
||||
realloc = _c_realloc,
|
||||
free = _c_free,
|
||||
}
|
||||
|
||||
@@ -57,6 +92,10 @@ alloc func(allocator Allocator, size usize, alignment usize) ?*mut u8 {
|
||||
return allocator.alloc(allocator.context, size, alignment)
|
||||
}
|
||||
|
||||
realloc func(allocator Allocator, memory ?*mut u8, old_size usize, new_size usize, alignment usize) ?*mut u8 {
|
||||
return allocator.realloc(allocator.context, memory, old_size, new_size, alignment)
|
||||
}
|
||||
|
||||
free func(allocator Allocator, memory ?*mut u8, size usize, alignment usize) void {
|
||||
allocator.free(allocator.context, memory, size, alignment)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user