neo_types/iterator.rs
1use std::vec::Vec;
2
3/// Neo N3 Iterator type
4///
5/// This iterator efficiently traverses elements using an internal cursor,
6/// avoiding O(n) overhead of Vec::remove(0) that would occur with a naive
7/// implementation.
8#[derive(Debug, Clone)]
9pub struct NeoIterator<T> {
10 data: Vec<T>,
11 cursor: usize,
12}
13
14impl<T> NeoIterator<T> {
15 /// Creates a new iterator from a vector.
16 pub fn new(data: Vec<T>) -> Self {
17 Self { data, cursor: 0 }
18 }
19
20 /// Returns the next element and advances the iterator.
21 ///
22 /// # Performance
23 /// This operation is O(1) due to cursor-based iteration.
24 #[allow(clippy::should_implement_trait)]
25 pub fn next(&mut self) -> Option<T>
26 where
27 T: Clone,
28 {
29 if self.cursor >= self.data.len() {
30 None
31 } else {
32 let item = self.data[self.cursor].clone();
33 self.cursor += 1;
34 Some(item)
35 }
36 }
37
38 /// Returns true if there are more elements to iterate.
39 pub fn has_next(&self) -> bool {
40 self.cursor < self.data.len()
41 }
42
43 /// Returns the number of remaining elements.
44 pub fn len(&self) -> usize {
45 self.data.len().saturating_sub(self.cursor)
46 }
47
48 /// Returns true if no more elements are available.
49 pub fn is_empty(&self) -> bool {
50 self.len() == 0
51 }
52
53 /// Resets the iterator to the beginning.
54 pub fn reset(&mut self) {
55 self.cursor = 0;
56 }
57
58 /// Returns the total number of elements (including already consumed).
59 pub fn total_len(&self) -> usize {
60 self.data.len()
61 }
62}