(zig noob here)
Am I doing something wrong with this code ?
It is just a "string" that grows with the append function.
I am having issues finding simple code snippets in the wild.
const AppendBuffer = struct {
allocator: Allocator,
buffer: ?[]u8 = null,
fn init(allocator: Allocator) AppendBuffer {
return AppendBuffer {
.allocator = allocator,
};
}
fn append(self: *AppendBuffer, new: []const u8 ) !void {
if(self.buffer==null){
self.buffer = try self.allocator.alloc(u8, new.len);
std.mem.copy(u8, self.buffer.?, new);
}
else {
const len = self.buffer.?.len;
self.buffer = try self.allocator.realloc(self.buffer.?, self.buffer.?.len+new.len);
std.mem.copy(u8, self.buffer.?[len..self.buffer.?.len], new);
}
}
fn deinit(self: *AppendBuffer) void {
if(self.buffer != null) self.allocator.free(self.buffer.?);
}
};