v2 / vlib / arrays / reverse_iterator.v
37 lines · 33 sloc · 1.12 KB · 35af6a8d12b70bf59e1df5d4fb517d04a6892b49
Raw
1module arrays
2
3// ReverseIterator provides a convenient way to iterate in reverse over all elements of an array without allocations.
4// I.e. it allows you to use this syntax: `for elem in arrays.reverse_iterator(a) {` .
5pub struct ReverseIterator[T] {
6mut:
7 a []T
8 i int
9}
10
11// reverse_iterator can be used to iterate over the elements in an array.
12// i.e. you can use this syntax: `for elem in arrays.reverse_iterator(a) {` .
13pub fn reverse_iterator[T](a []T) ReverseIterator[T] {
14 return ReverseIterator[T]{
15 a: a
16 i: a.len
17 }
18}
19
20// next is the required method, to implement an iterator in V.
21// It returns none when the iteration should stop.
22// Otherwise it returns the current element of the array.
23@[direct_array_access]
24pub fn (mut iter ReverseIterator[T]) next() ?&T {
25 iter.i--
26 if iter.i < 0 {
27 return none
28 }
29 return unsafe { &iter.a[iter.i] }
30}
31
32// free frees the iterator resources.
33pub fn (iter &ReverseIterator[T]) free() {
34 // The array stored in the iterator is not owned by the iterator.
35 // It should not be freed, when the iterator goes out of scope.
36 // This is the reason, that this manual free method exists and is empty.
37}
38