Draupnir: magic ring buffer Io.Reader/Writer

Draupnir: magic ring buffer Io.Reader/Io.Writer


https://codeberg.org/benburkert/draupnir

Draupnir is a fast, concurrent, thread-safe ring buffer with an std.Io.Reader/std.Io.Writer interface. It implements the magic ring buffer pattern to provide a single contiguous slice for io interface buffers. Reading from and writing to an interface buffer does not require holding a lock.

var ring: draupnir.Ring = try .init(io, std.heap.pageSize());
defer ring.deinit() catch unreachable;

// read 128 MiB
var read_future = try io.concurrent(std.Io.Reader.readAllocAll, .{ &ring.reader, gpa, 128 << 20 });

// write 128 MiB
for (0..128) |i| {
    var data: [1 << 20]u8 = @splat(@intCast(i));
    try ring.writer.writeAll(&data);
}

const result = try read_future.await(io);
try gpa.free(result);

Supported Zig versions

0.17 and later

9 Likes

Man, this reminded me that I should implement one for my own project! Magic ring buffers are so cool, I wish computers were real…

Jokes aside, I think I may have found a bug:

test "concurrent write and read" {
    const io = std.testing.io;

    var ring: Ring = try .init(io, std.heap.pageSize());
    defer ring.deinit() catch unreachable;

    const Tester = union(enum) {
        read: std.Io.Reader.Error!void,
        write: std.Io.Writer.Error!void,

        const n = 1024;

        pub fn doRead(r: *std.Io.Reader) std.Io.Reader.Error!void {
            var buf: [n]u8 = undefined;
            try r.readSliceAll(&buf);
        }
        pub fn doWrite(w: *std.Io.Writer) std.Io.Writer.Error!void {
            var data: [n]u8 = @splat(1);
            try w.writeAll(&data);
            try w.flush();
        }
    };

    const rounds = 64;
    var select_buffer: [rounds * 2]Tester = undefined;
    var select: std.Io.Select(Tester) = .init(io, &select_buffer);

    for (0..rounds) |_| {
        try select.concurrent(.write, Tester.doWrite, .{&ring.writer});
        try select.concurrent(.read, Tester.doRead, .{&ring.reader});
    }
    for (0..rounds * 2) |_| {
        switch (try select.await()) {
            .read => |read| try read,
            .write => |write| try write,
        }
    }
}
error: 'root.test.concurrent write and read' terminated with signal ABRT with stderr:
       thread 345025 panic: start index 1024 is larger than end index 0
       /home/inspectorboat/.local/share/zigup/0.17.0/files/lib/std/Io/Reader.zig:686:30: 0x1106845 in readSliceShort (std.zig)
           const contents = r.buffer[r.seek..r.end];
                                    ^
       /home/inspectorboat/.local/share/zigup/0.17.0/files/lib/std/Io/Reader.zig:671:33: 0x1106637 in readSliceAll (std.zig)
           const n = try readSliceShort(r, buffer);
                                       ^
       /home/inspectorboat/src/draupnir/src/root.zig:260:31: 0x1236a53 in doRead (root.zig)
                   try r.readSliceAll(&buf);

Not sure of the cause, it might be my user error (I’m definitely not an expert at this stuff) so I’m haven’t filed an issue yet.

2 Likes

Hey @InspectorBoat, I think the reason for the crash is that the test is issuing multiple concurrent reads/writes. I forgot to document it, but draupnir.Ring is a Single Producer Single Consumer (SPSC) queue. Multiple concurrent reads/writes can result in the crashes you are seeing. I modified this test to concurrently run a single read and single write and it no longer crashes.

AFAIK, there is no way to make a MPMC/SPMC/MPSC queue and keep the single Io.Reader/Io.Writer interface, but would love to be proven wrong on this. The closest I have come up with is to add reader(buffer: []u8) Io.Reader and writer(buffer: []u8) Io.Writer methods, but i think you give up serializability with all those independent buffers.

1 Like

What makes this one different compared to the ringbuffer in the standard library?

1 Like

This one presents itself as a contiguous slice in virtual memory by creating two mappings that refer to the same memory:

[        ][        ]
  ^h  ^t    ^h  ^t

In this example, a writer can write straight from the tail in the first mapping to the head in the second mapping. Normally, it would have to do two writes: from the head until the end of the buffer and from the beginning of the buffer to the head. You can do this with std.Deque, and I’ve written a few functions that help with this. But the Draupnir interface is nicer.

1 Like