2023-04-19 01:25:35 +02:00
|
|
|
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 {
|
2023-05-06 03:47:52 +02:00
|
|
|
return io.Writer.bind(self, struct {
|
|
|
|
fn fallible_write(fixed: *Fixed, buffer: []const u8) io.WriteError!usize {
|
|
|
|
return fixed.write(buffer);
|
|
|
|
}
|
|
|
|
}.fallible_write);
|
2023-04-19 01:25:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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();
|
|
|
|
}
|
|
|
|
};
|