| 1 | module 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) {` . |
| 5 | pub struct ReverseIterator[T] { |
| 6 | mut: |
| 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) {` . |
| 13 | pub 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] |
| 24 | pub 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. |
| 33 | pub 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 | |