#Traversing list backwards
1 messages · Page 1 of 1 (latest)
Im asking because im trying to write this function in zig https://github.com/rust-bitcoin/rust-bitcoin/blob/master/bitcoin/src/base58.rs#L43
and here they start from the end of the scratch list https://github.com/rust-bitcoin/rust-bitcoin/blob/master/bitcoin/src/base58.rs#L58
maybe unusual not sure. but i've been doing this recently:
const items = [2]u8{ 0, 1 };
{
var i = @bitCast(isize, items.len) - 1;
while (i >= 0) : (i -= 1) { _ = items[@bitCast(usize, i)]; }
}
otherwise:
const items = [2]u8{ 0, 1 };
{
var i = items.len - 1;
while (true) : (i -= 1) {
_ = items[i];
if(i == 0) break;
}
}
would this work
var index = buffer.len - 1;
while(index >= 0) : (index--) {
// do stuff by accessing buffer by doing buffer[index]
}
no, in that case, index is a usize and will underflow.
think this would also work if you want less verbose but slightly less perf:
const items = [2]u8{ 0, 1 };
for(0..items.len) |i| {
_ = items[items.len - i];
}
EDIT - fixed
oh thats true
is there some cool std thing that would allow one to create an iterator of a list?
or a revers iterator?
not that i know of.
i like this one
const items = [2]u8{ 0, 1 };
{
var i = items.len - 1;
while (true) : (i -= 1) {
_ = items[i];
if(i == 0) break;
}
}
thank you 🙂
is there a reason you do i -= 1 and not i--
?
i-- not a thing in zig 😆
ha no worries. pretty sure i've typed that into a zig file a few times.
Alas, I think the while-true is probably the best you can do.
There might be a slightly better alternative that someone suggested a while ago, but I cannot find it in the search unfortunately.
It would certainly be very nice if you just do this though:
for reverse (items) |e| {
...
}