ona/source/coral/buffer.zig

66 lines
1.4 KiB
Zig

const io = @import("./io.zig");
const math = @import("./math.zig");
pub const Fixed = struct {
data: []u8,
write_index: usize = 0,
pub fn as_writer(self: *Fixed) io.Writer {
return io.Writer.bind(self, Fixed);
}
pub fn remaining(self: Fixed) usize {
return self.data.len - self.write_index;
}
pub fn is_empty(self: Fixed) bool {
return !self.is_full();
}
pub fn is_full(self: Fixed) bool {
return self.write_index == self.data.len;
}
pub fn write(self: *Fixed, buffer: []const u8) usize {
const range = math.min(usize, buffer.len, self.remaining());
io.copy(self.data[self.write_index ..], buffer[0 .. range]);
self.write_index += range;
return range;
}
};
pub const Ring = struct {
data: []u8,
read_index: usize = 0,
write_index: usize = 0,
pub fn as_reader(self: *Ring) io.Reader {
return io.Reader.bind(self, Ring);
}
pub fn as_writer(self: *Ring) io.Writer {
return io.Writer.bind(self, Ring);
}
pub fn filled(self: Ring) usize {
return (self.write_index + (2 * self.data.len *
@boolToInt(self.write_index < self.read_index))) - self.read_index;
}
pub fn is_empty(self: Ring) bool {
return self.write_index == self.read_index;
}
pub fn is_full(self: Ring) bool {
return ((self.write_index + self.data.len) % (self.data.len * 2)) != self.read_index;
}
pub fn remaining(self: Ring) usize {
return self.data.len - self.filled();
}
};