Looping through BoundedArray slice in reverse

We can loop through a bounded array slice (ar) with:
for (ar.slice())
but is there a neat way to go backwards instead of indexing myself?

I don’t think there is, at least not using a for loop. You could write your own iterator to go in reverse and use that in a while loop:

$ cat main.zig 
const std = @import("std");

fn ReverseIterator(comptime Slice: type) type {
    const Elem = std.meta.Elem(Slice);
    return struct {
        position: usize,
        slice: Slice,

        pub fn next(self: *@This()) ?Elem {
            if (self.position >= self.slice.len) return null;
            const elem = self.slice[self.slice.len - 1 - self.position];
            self.position += 1;
            return elem;
        }
    };
}

fn reverse(slice: anytype) ReverseIterator(@TypeOf(slice)) {
    return ReverseIterator(@TypeOf(slice)){
        .position = 0,
        .slice = slice,
    };
}

pub fn main() !void {
    var a = try std.BoundedArray(u8, 128).init(3);
    a.appendSliceAssumeCapacity(&.{ 1, 2, 3 });

    const s = a.constSlice();
    std.debug.print("slice length={d}\n", .{s.len});

    var it = reverse(s);
    while (it.next()) |n| {
        std.debug.print(" - {d}\n", .{n});
    }
}

$ zig run main.zig
slice length=6
 - 3
 - 2
 - 1
 - 0
 - 0
 - 0

See one of these links, maybe it suits your needs:

4 Likes

Are these new? I missed the existence of std.mem.reverseIterator() completely… Well, go use that one, it’s better than my toy version above :innocent:

2 Likes

I will have a look. Thanks!
std.mem is full of surprises.

There are available since 0.11.0

I don’t know how long they’ve been around, I just remembered them.