1 # Iterators
2
3 Iterators generalize the iteration over elements of an arbitrary collection.
4 This allows iteration over arrays, lists, maps, trees, etc. in a unified way.
5
6 Creating an iterator is as simple as creating a `CxIterator` struct and setting the fields in a meaningful way.
7 The UCX collections provide various functions to create such iterators.
8
9 If the predefined fields are not enough (or introduce too much bloat) for your use case,
10 you can alternatively create your own iterator structure
11 and place the `CX_ITERATOR_BASE` macro as first member of that structure.
12
13 ```C
14 #include <cx/iterator.h>
15
16 struct my_fancy_iterator_s {
17 CX_ITERATOR_BASE; // the base members used by cx_foreach()
18 // ... custom fields ...
19 };
20 ```
21
22 ## Creating an Iterator
23
24 The following functions create iterators over plain C arrays.
25
26 ```C
27 #include <cx/iterator.h>
28
29 CxIterator cxIterator(const void *array,
30 size_t elem_size, size_t elem_count,
31 bool remove_keeps_order);
32
33 CxIterator cxIteratorPtr(const void *array,
34 size_t elem_count,
35 bool remove_keeps_order);
36 ```
37
38 The `cxIterator()` function creates an iterator over the elements of `array` where
39 each element is `elem_size` bytes large and the array contains a total of `elem_count` elements.
40
41 The `cxIteratorPtr()` function is equivalent to `cxIterator()`, except it assumes `sizeof(void*)` as the `elem_size`.
42
43 The UCX collections also define functions for creating iterators over their items.
44 You can read more about them in the respective Sections of the documentation.
45
46 ## Using an Iterator
47
48 The following macros work with arbitrary structures using `CX_ITERATOR_BASE`
49 and invoke the respective function pointers `valid`, `current`, or `next`.
50 ```C
51 cxIteratorValid(iter)
52 cxIteratorCurrent(iter)
53 cxIteratorNext(iter)
54 ```
55
56 You may use them for manual iterator, but usually you do not need them.
57 Every iterator can be used with the `cx_foreach` macro.
58
59 ```C
60 #include <cx/iterator.h>
61
62 // some custom array and its size
63 MyData *array = // ...
64 size_t size = // ...
65
66 CxIterator iter = cxIterator(array, sizeof(MyData), size);
67 cx_foreach(MyData*, elem, iter) {
68 // .. do something with elem ..
69 }
70 ```
71
72 The macro takes three arguments:
73 1. the pointer-type of a pointer to an element,
74 2. the name of the variable you want to use for accessing the element,
75 3. and the iterator.
76
77 > An iterator does not necessarily need to iterate over the concrete elements of a collection.
78 > Map iterators, for example, can iterator over the key/value pairs,
79 > but they can also iterate over just the values or just the keys.
80 >
81 > You should read the documentation of the function creating the iterator to learn
82 > what exactly the iterator is iterating over.
83
84 ## Removing Elements via Iterators
85
86 Usually an iterator is not mutating the collection it is iterating over.
87 But sometimes it is desirable to remove an element from the collection while iterating over it.
88
89 For this purpose, most collections allow to use `cxIteratorFlagRemoval()`, which instructs the iterator to remove
90 the current element from the collection on the next call to `cxIteratorNext()`.
91 If you are implementing your own iterator, it is up to you to implement this behavior.
92
93 ## Passing Iterators to Functions
94
95 To eliminate the need of memory management for iterators, the structures are usually used by value.
96 This does not come with additional costs because iteration is implemented entirely by using macros.
97
98 However, sometimes it is necessary to pass an iterator to another function.
99 To make that possible in a generalized way, such functions should accept a `CxIteratorBase*` pointer
100 which can be obtained with the `cxIteratorRef()` macro on the calling site.
101
102 In the following example, elements from a list are inserted into a tree:
103
104 ```C
105 CxList *list = // ...
106 CxTree *tree = // ...
107
108 CxIterator iter = cxListIterator(list);
109 cxTreeInsertIter(tree, cxIteratorRef(iter), cxListSize(list));
110 ```
111
112 > This is the reason, why `CX_ITERATOR_BASE` must be the first member of any iterator structure.
113 > Otherwise, the address taken by `cxIteratorRef()` would not equal the address of the iterator.
114 {style="note"}
115
116 ## Custom Iterators
117
118 The base structure is defined as follows:
119 ```C
120 struct cx_iterator_base_s {
121 bool (*valid)(const void *);
122 bool (*valid_impl)(const void *);
123 void *(*current)(const void *);
124 void (*next)(void *);
125 void *(*current_impl)(const void *);
126 void (*next_impl)(void *);
127 bool allow_remove;
128 bool remove;
129 };
130
131 typedef struct cx_iterator_base_s CxIteratorBase;
132 ```
133
134 The `valid` function indicates whether the iterator is currently pointing to an element in the collection.
135 The `current` function is supposed to return that element,
136 and the `next` function shall advance the iterator to the next element.
137
138 The booleans `allow_remove` and `remove` are used for [removing elements](#removing-elements-via-iterators) as explained above.
139 When an iterator is created, the `allow_remove` field is set to indicate if removal of elements is supported.
140 The `remove` field is set to indicate if the current element should be removed on the next call to `next()` (see `cxIteratorFlagRemoval()`).
141
142 Iterators may be wrapped in which case the original implementation can be stored in the `*_impl` function pointers.
143 They can then be called by a wrapper implementation pointed to by `current` and `next`, respectively.
144 This can be useful when you want to support the `store_pointer` field of the [](collection.h.md) API.
145
146 A specialized, simple, and fast iterator over an array of a certain type
147 that does not support removing elements can be implemented as follows:
148 ```C
149 #include <cx/iterator.h>
150
151 typedef struct my_foo_s {
152 // ... your data ...
153 } MyFoo;
154
155 typedef struct my_foo_iterator_s {
156 CX_ITERATOR_BASE;
157 MyFoo *array;
158 size_t index;
159 size_t elem_count;
160 } MyFooIterator;
161
162 static bool my_foo_iter_valid(const void *it) {
163 const MyFooIterator *iter = it;
164 return iter->index < iter->elem_count;
165 }
166
167 static void *my_foo_iter_current(const void *it) {
168 const MyFooIterator *iter = it;
169 return &iter->array[iter->index];
170 }
171
172 static void my_foo_iter_next(void *it) {
173 MyFooIterator *iter = it;
174 iter->index++;
175 }
176
177 MyFooIterator myFooIterator(MyFoo *array, size_t elem_count) {
178 MyFooIterator iter;
179
180 // base fields
181 iter.base.valid = my_foo_iter_valid;
182 iter.base.current = my_foo_iter_current;
183 iter.base.next = my_foo_iter_next;
184 iter.base.remove = false;
185 iter.base.allow_remove = false;
186
187 // custom fields
188 iter.index = 0;
189 iter.elem_count = elem_count;
190
191 return iter;
192 }
193 ```
194
195 > Note, that the behavior of `current` is undefined when `valid` returns `false`.
196 > That means, on the one hand, `current` does not need to check for validity of the iterator,
197 > but on the other hand, it is forbidden to invoke `current` when `valid` would return `false`.
198 {style="note"}
199
200 > If performance matters in your application, it is recommended that you indeed create specialized iterators
201 > for your collections. The default UCX implementations trade some performance for generality.
202
203 <seealso>
204 <category ref="apidoc">
205 <a href="https://ucx.sourceforge.io/api/iterator_8h.html">iterator.h</a>
206 </category>
207 </seealso>
208