I find myself allocating a big chunk of memory of u8s and then repartitioning it into equally sized slices of []u8. I need to build some kind of table and the slices here are the rows in that table. Now to my question:
Is there a good std function for this (I saw std.mem.window as the closes thing)
If not, how can i do this in a better way?
I just dont really like doing two allocations for this kind of problem.
Maybe I should just write my own function. Here is some example code:
You could allocate your data as, or cast it to, a slice of arrays (e.g. [][10]u8) although this requires you to know one dimension at comptime.
Another option is allocating it and casting the first segment into the table
var data = try gpa.alloc(u8, @sizeOf([]u8) * rows + cols * rows);
defer gpa.free(data);
const chunk = data[@sizeOf([]u8) * rows ..];
const table: [][]const u8 = @ptrCast(@alignCast(data[0 .. @sizeOf([]u8) * rows]));
var it = std.mem.window(u8, chunk, cols, cols);
for (table) |*row| row.* = it.next() orelse unreachable;
Given row and col are not comptime known when splitting it, you’re either going to have an iterator or an allocating function so I believe using std.mem.window is probably as good as you’re going to get if you don’t mind std.mem.WindowIterator.next returning ?[]const T.