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
//! Iterators and extension for working with crawlers that are pointing to
//! arrays.
use crate::{
    CrawlerError, CrawlerResult, JsonCrawler, JsonCrawlerBorrowed, JsonCrawlerOwned, JsonPath,
    PathList,
};
use std::{borrow::Borrow, slice::IterMut, sync::Arc, vec::IntoIter};

/// Iterator extension trait containing special methods for Json Crawler
/// iterators to help with error handling.
pub trait JsonCrawlerIterator: Iterator
where
    Self::Item: JsonCrawler,
{
    /// Return the first crawler found at `path`, or error.
    fn find_path(self, path: impl AsRef<str>) -> CrawlerResult<Self::Item>;
    /// Get a context object that can be used to generate error types that are
    /// unable to be expressed declaratively.
    /// # Note
    /// This allocates internally, to allow it to outlive the original iterator.
    fn get_context(&self) -> JsonCrawlerArrayIterContext;
    /// Return the last item of the array, or return an error with context.
    fn try_last(self) -> CrawlerResult<Self::Item>;
}

pub struct JsonCrawlerArrayIterContext {
    pub(crate) source: Arc<String>,
    pub(crate) path: String,
}

pub struct JsonCrawlerArrayIterMut<'a> {
    pub(crate) source: Arc<String>,
    pub(crate) array: IterMut<'a, serde_json::Value>,
    pub(crate) path: PathList,
    pub(crate) cur_front: usize,
    pub(crate) cur_back: usize,
}

#[derive(Clone)]
pub struct JsonCrawlerArrayIntoIter {
    pub(crate) source: Arc<String>,
    pub(crate) array: IntoIter<serde_json::Value>,
    pub(crate) path: PathList,
    pub(crate) cur_front: usize,
    pub(crate) cur_back: usize,
}

impl<'a> Iterator for JsonCrawlerArrayIterMut<'a> {
    type Item = JsonCrawlerBorrowed<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        let crawler = self.array.next()?;
        let out = Some(JsonCrawlerBorrowed {
            // Low cost as this is an Arc
            source: self.source.clone(),
            crawler,
            // Ideally there should be a Borrowed version of this struct - otherwise we need to
            // clone every time here.
            path: self.path.clone().with(JsonPath::IndexNum(self.cur_front)),
        });
        self.cur_front += 1;
        out
    }
    // Required to be exact to implement ExactSizeIterator.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.array.len(), Some(self.array.len()))
    }
}

// Default implementation is correct, due to implementation of size_hint.
impl<'a> ExactSizeIterator for JsonCrawlerArrayIterMut<'a> {}

impl<'a> DoubleEndedIterator for JsonCrawlerArrayIterMut<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        let crawler = self.array.next_back()?;
        let out = Some(JsonCrawlerBorrowed {
            // Low cost as this is an Arc
            source: self.source.clone(),
            crawler,
            // Ideally there should be a Borrowed version of this struct - otherwise we need to
            // clone every time here.
            path: self.path.clone().with(JsonPath::IndexNum(self.cur_back)),
        });
        self.cur_back = self.cur_back.saturating_sub(1);
        out
    }
}

impl<'a> JsonCrawlerIterator for JsonCrawlerArrayIterMut<'a> {
    fn find_path(mut self, path: impl AsRef<str>) -> CrawlerResult<Self::Item> {
        self.find_map(|crawler| crawler.navigate_pointer(path.as_ref()).ok())
            .ok_or_else(|| {
                CrawlerError::path_not_found_in_array(self.path, self.source, path.as_ref())
            })
    }
    fn get_context(&self) -> JsonCrawlerArrayIterContext {
        JsonCrawlerArrayIterContext {
            source: self.source.clone(),
            path: self.path.borrow().into(),
        }
    }
    fn try_last(self) -> CrawlerResult<Self::Item> {
        let Self {
            source,
            array,
            mut path,
            ..
        } = self;
        let len = array.len();
        path.push(JsonPath::IndexNum(len));
        let Some(last_item) = array.last() else {
            return Err(CrawlerError::array_size(path, source, 0));
        };
        Ok(Self::Item {
            source,
            crawler: last_item,
            path,
        })
    }
}

impl Iterator for JsonCrawlerArrayIntoIter {
    type Item = JsonCrawlerOwned;
    fn next(&mut self) -> Option<Self::Item> {
        let crawler = self.array.next()?;
        let out = Some(JsonCrawlerOwned {
            // Low cost as this is an Arc
            source: self.source.clone(),
            crawler,
            // Ideally there should be a Borrowed version of this struct - otherwise we need to
            // clone every time here.
            path: self.path.clone().with(JsonPath::IndexNum(self.cur_front)),
        });
        self.cur_front += 1;
        out
    }
    // Required to be exact to implement ExactSizeIterator.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.array.len(), Some(self.array.len()))
    }
}
// Default implementation is correct, due to implementation of size_hint.
impl ExactSizeIterator for JsonCrawlerArrayIntoIter {}

impl DoubleEndedIterator for JsonCrawlerArrayIntoIter {
    fn next_back(&mut self) -> Option<Self::Item> {
        let crawler = self.array.next_back()?;
        let out = Some(JsonCrawlerOwned {
            // Low cost as this is an Arc
            source: self.source.clone(),
            crawler,
            // Ideally there should be a Borrowed version of this struct - otherwise we need to
            // clone every time here.
            path: self.path.clone().with(JsonPath::IndexNum(self.cur_back)),
        });
        self.cur_back = self.cur_back.saturating_sub(1);
        out
    }
}
impl JsonCrawlerIterator for JsonCrawlerArrayIntoIter {
    fn find_path(mut self, path: impl AsRef<str>) -> CrawlerResult<Self::Item> {
        self.find_map(|crawler| crawler.navigate_pointer(path.as_ref()).ok())
            .ok_or_else(|| {
                CrawlerError::path_not_found_in_array(self.path, self.source, path.as_ref())
            })
    }
    fn get_context(&self) -> JsonCrawlerArrayIterContext {
        JsonCrawlerArrayIterContext {
            source: self.source.clone(),
            path: self.path.borrow().into(),
        }
    }
    fn try_last(self) -> CrawlerResult<Self::Item> {
        let Self {
            source,
            array,
            mut path,
            ..
        } = self;
        let len = array.len();
        path.push(JsonPath::IndexNum(len));
        let Some(last_item) = array.last() else {
            return Err(CrawlerError::array_size(path, source, 0));
        };
        Ok(Self::Item {
            source,
            crawler: last_item,
            path,
        })
    }
}