jc/memory/buffer.jai
2025-07-23 15:22:00 -06:00

51 lines
1 KiB
Text

#module_parameters(RUN_TESTS := false);
Buffer :: struct {
allocator: Allocator;
data: [..]byte;
count: int;
}
append :: inline (buf: *Buffer, ptr: rawptr, size: int) {
inline mem.lazy_set_allocator(buf);
free_space := ensure_buffer_has_room(buf, size);
memcpy(free_space, ptr, size);
buf.size += size;
}
append :: inline (buf: *Buffer, data: []byte) {
append(buf, data.data, data.count);
}
append :: inline (buf: *Buffer, ptr: *$T) {
append(buf, ptr, size_of(T));
}
reset :: inline (buf: *Buffer) {
buf.count = 0;
}
#scope_file;
#import "jc";
array :: #import "jc/array";
mem :: #import "jc/memory";
meta :: #import "jc/meta";
ensure_buffer_has_room :: (buf: *Buffer, count: int) -> *u8 {
ptr := buf.data.data + buf.count;
if buf.count + count >= buf.data.allocated {
array.resize(*buf.data, buf.data.allocated * 2);
ptr = buf.data.data + buf.count;
buf.data.count = buf.data.allocated;
}
return ptr;
}
#if RUN_TESTS #run {
test :: #import "jc/meta/test";
}