Here is another option I found that seems a bit more safe.
const std = @import("std");
const print = std.debug.print;
const Header = struct { id: u8, len: u8 };
fn readBytes(data: []const u8, offset: *usize) ?[]const u8 {
if (offset.* >= data.len) return null;
const header = @ptrCast(*const Header, data[offset.* .. offset.* + 2]);
offset.* += @sizeOf(Header);
const bytes = data[offset.* .. offset.* + header.len];
offset.* += header.len;
return bytes;
}
pub fn main() !void {
const data = "\x00\x05\x48\x65\x6c\x6c\x6f\x01\x03\x61\x6c\x6c";
var offset: usize = 0;
while (readBytes(data, &offset)) |bytes| {
print("{s}\n", .{bytes});
}
}
I am interested to see other options though!