1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
//
// Copyright (c) The yang2-rs Core Contributors
//
// See LICENSE for license details.
//

//! YANG iterators.

use crate::context::Context;
use crate::data::Metadata;
use crate::schema::SchemaModule;
use crate::utils::Binding;
use libyang2_sys as ffi;

/// Common methods used by multiple data and schema node iterators.
#[doc(hidden)]
pub trait NodeIterable<'a>: Sized + Clone + PartialEq + Binding<'a> {
    /// Returns the parent node.
    fn parent(&self) -> Option<Self>;

    /// Returns the next sibling node.
    fn next_sibling(&self) -> Option<Self>;

    /// Returns the fist child none.
    fn first_child(&self) -> Option<Self>;
}

/// An iterator over the sibings of a node.
#[derive(Debug)]
pub struct Siblings<'a, T>
where
    T: NodeIterable<'a>,
{
    next: Option<T>,
    _marker: std::marker::PhantomData<&'a T>,
}

/// An iterator over the ancestors of a node.
#[derive(Debug)]
pub struct Ancestors<'a, T>
where
    T: NodeIterable<'a>,
{
    next: Option<T>,
    _marker: std::marker::PhantomData<&'a T>,
}

/// An iterator over all elements in a tree (depth-first search algorithm).
///
/// When traversing over schema trees, note that _actions_ and _notifications_
/// are ignored.
#[derive(Debug)]
pub struct Traverse<'a, T>
where
    T: NodeIterable<'a>,
{
    start: T,
    next: Option<T>,
    _marker: std::marker::PhantomData<&'a T>,
}

/// An iterator over a set of nodes.
///
/// This is a safe wrapper around ffi::ly_set.
#[derive(Debug)]
pub struct Set<'a, T>
where
    T: NodeIterable<'a>,
{
    container: &'a T::Container,
    slice: &'a [*mut T::CType],
}

/// An iterator over an array of nodes or substatements.
///
/// This is a safe wrapper around libyang2's
/// [sized arrays](https://netopeer.liberouter.org/doc/libyang/libyang2/html/howto_structures.html#sizedarrays).
#[derive(Debug)]
pub struct Array<'a, S: Binding<'a>> {
    context: &'a Context,
    raw: *mut S::CType,
    ptr_size: usize,
    count: usize,
}

/// An iterator over a list of schema modules.
#[derive(Debug)]
pub struct SchemaModules<'a> {
    context: &'a Context,
    index: u32,
}

/// An iterator over a list of metadata.
#[derive(Debug)]
pub struct MetadataList<'a> {
    next: Option<Metadata<'a>>,
}

// ===== impl Siblings =====

impl<'a, T> Siblings<'a, T>
where
    T: NodeIterable<'a>,
{
    pub fn new(next: Option<T>) -> Siblings<'a, T> {
        Siblings {
            next,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<'a, T> Iterator for Siblings<'a, T>
where
    T: NodeIterable<'a>,
{
    type Item = T;

    fn next(&mut self) -> Option<T> {
        let ret = self.next.clone();
        if let Some(next) = &self.next {
            self.next = next.next_sibling();
        }
        ret
    }
}

// ===== impl Ancestors =====

impl<'a, T> Ancestors<'a, T>
where
    T: NodeIterable<'a>,
{
    pub fn new(next: Option<T>) -> Ancestors<'a, T> {
        Ancestors {
            next,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<'a, T> Iterator for Ancestors<'a, T>
where
    T: NodeIterable<'a>,
{
    type Item = T;

    fn next(&mut self) -> Option<T> {
        let node = self.next.clone();
        if let Some(next) = &self.next {
            self.next = next.parent();
        }
        node
    }
}

// ===== impl Traverse =====

impl<'a, T> Traverse<'a, T>
where
    T: NodeIterable<'a>,
{
    pub fn new(start: T) -> Traverse<'a, T> {
        let next = start.clone();

        Traverse {
            start,
            next: Some(next),
            _marker: std::marker::PhantomData,
        }
    }
}

impl<'a, T> Iterator for Traverse<'a, T>
where
    T: NodeIterable<'a>,
{
    type Item = T;

    fn next(&mut self) -> Option<T> {
        let ret = self.next.clone();

        if let Some(elem) = &mut self.next {
            // Select element for the next run - children first.
            let mut next_elem = elem.first_child();
            if next_elem.is_none() {
                // Check end condition.
                if *elem == self.start {
                    self.next = None;
                    return ret;
                }

                // No children, try siblings.
                next_elem = elem.next_sibling();
            }

            while next_elem.is_none() {
                // Parent is already processed, go to its sibling.
                *elem = elem.parent().unwrap();

                // Check end condition.
                if *elem == self.start {
                    self.next = None;
                    return ret;
                }
                next_elem = elem.next_sibling();
            }

            *elem = next_elem.unwrap();
        }

        ret
    }
}

// ===== impl Set =====

impl<'a, T> Set<'a, T>
where
    T: NodeIterable<'a>,
{
    pub fn new(
        container: &'a T::Container,
        slice: &'a [*mut T::CType],
    ) -> Set<'a, T> {
        Set { container, slice }
    }
}

impl<'a, T> Iterator for Set<'a, T>
where
    T: NodeIterable<'a>,
{
    type Item = T;

    fn next(&mut self) -> Option<T> {
        if !self.slice.is_empty() {
            let dnode = Some(T::from_raw(self.container, self.slice[0]));
            self.slice = &self.slice[1..];
            dnode
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.slice.len()))
    }
}

unsafe impl<'a, T> Send for Set<'a, T> where T: NodeIterable<'a> {}
unsafe impl<'a, T> Sync for Set<'a, T> where T: NodeIterable<'a> {}

// ===== impl Array =====

impl<'a, S> Array<'a, S>
where
    S: Binding<'a>,
{
    pub fn new(
        context: &'a Context,
        raw: *mut S::CType,
        ptr_size: usize,
    ) -> Array<'a, S> {
        // Get the number of records in the array (equivalent to
        // LY_ARRAY_COUNT).
        let count = if raw.is_null() {
            0
        } else {
            unsafe { (raw as *const usize).offset(-1).read() }
        };

        Array {
            context,
            raw,
            ptr_size,
            count,
        }
    }
}

impl<'a, S> Iterator for Array<'a, S>
where
    S: Binding<'a, Container = Context>,
{
    type Item = S;

    fn next(&mut self) -> Option<S> {
        if self.count > 0 {
            let next = S::from_raw_opt(self.context, self.raw);
            self.count -= 1;
            self.raw = (self.raw as usize + self.ptr_size) as *mut S::CType;
            next
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.count))
    }
}

unsafe impl<'a, S> Send for Array<'a, S> where S: NodeIterable<'a> {}
unsafe impl<'a, S> Sync for Array<'a, S> where S: NodeIterable<'a> {}

// ===== impl SchemaModules =====

impl<'a> SchemaModules<'a> {
    pub fn new(context: &'a Context, skip_internal: bool) -> SchemaModules<'a> {
        let index = if skip_internal {
            context.internal_module_count()
        } else {
            0
        };
        SchemaModules { context, index }
    }
}

impl<'a> Iterator for SchemaModules<'a> {
    type Item = SchemaModule<'a>;

    fn next(&mut self) -> Option<SchemaModule<'a>> {
        let rmodule = unsafe {
            ffi::ly_ctx_get_module_iter(self.context.raw, &mut self.index)
        };
        SchemaModule::from_raw_opt(self.context, rmodule as *mut _)
    }
}

// ===== impl MetadataList =====

impl MetadataList<'_> {
    pub fn new(next: Option<Metadata<'_>>) -> MetadataList<'_> {
        MetadataList { next }
    }
}

impl<'a> Iterator for MetadataList<'a> {
    type Item = Metadata<'a>;

    fn next(&mut self) -> Option<Metadata<'a>> {
        let meta = self.next.clone();
        if let Some(next) = &self.next {
            self.next = next.next();
        }
        meta
    }
}