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
use std::{marker::PhantomData, ptr::NonNull};

use simdjson_sys as ffi;

use super::{document::Document, field::Field};
use crate::{error::Result, macros::map_result};

pub struct ObjectIterator<'a> {
    begin: NonNull<ffi::SJ_OD_object_iterator>,
    end: NonNull<ffi::SJ_OD_object_iterator>,
    running: bool,
    _doc: PhantomData<&'a mut Document<'a, 'a>>,
}

impl<'a> ObjectIterator<'a> {
    pub fn new(
        begin: NonNull<ffi::SJ_OD_object_iterator>,
        end: NonNull<ffi::SJ_OD_object_iterator>,
    ) -> Self {
        Self {
            begin,
            end,
            running: false,
            _doc: PhantomData,
        }
    }

    pub fn get(&mut self) -> Result<Field<'a>> {
        map_result!(
            ffi::SJ_OD_object_iterator_get(self.begin.as_mut()),
            ffi::SJ_OD_field_result_error,
            ffi::SJ_OD_field_result_value_unsafe
        )
        .map(Field::new)
    }

    pub fn not_equal(&self) -> bool {
        unsafe { ffi::SJ_OD_object_iterator_not_equal(self.begin.as_ref(), self.end.as_ref()) }
    }

    pub fn step(&mut self) {
        unsafe { ffi::SJ_OD_object_iterator_step(self.begin.as_mut()) }
    }
}

impl<'a> Drop for ObjectIterator<'a> {
    fn drop(&mut self) {
        unsafe {
            ffi::SJ_OD_object_iterator_free(self.begin.as_mut());
            ffi::SJ_OD_object_iterator_free(self.end.as_mut());
        }
    }
}

impl<'a> Iterator for ObjectIterator<'a> {
    type Item = Result<Field<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.running {
            self.step();
        }

        if self.not_equal() {
            self.running = true;
            Some(self.get())
        } else {
            self.running = false;
            None
        }
    }
}