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
350
351
//! The main logic of JSON filtering
//!
//! It uses matchers and filters matched parts
//! from output

use std::{collections::VecDeque, mem::swap};

use crate::{
    error,
    matcher::MatchMaker,
    path::Path,
    streamer::{Output, Streamer},
};

/// Processes data from input and remove matched parts (and keeps the json valid)
pub struct Filter {
    /// Buffer idx against total idx
    buffer_idx: usize,
    /// Buffer use for input buffering
    buffer: VecDeque<u8>,
    /// Responsible for data extraction
    streamer: Streamer,
    /// Matchers which will cause filtering
    matchers: Vec<Box<dyn MatchMaker>>,
    /// Path which is matched
    matched_path: Option<Path>,
    /// Level of last element which is not filtered
    last_output_level: usize,
    /// Index of last element which is not filtered
    last_output_idx: Option<usize>,
    /// discard on next not filtered start or end token
    delayed_discard: bool,
}

impl Default for Filter {
    fn default() -> Self {
        Self {
            buffer_idx: 0,
            buffer: VecDeque::new(),
            matchers: vec![],
            streamer: Streamer::new(),
            matched_path: None,
            last_output_idx: None,
            delayed_discard: false,
            last_output_level: 0,
        }
    }
}

impl Filter {
    /// Create new filter
    ///
    /// It removes matched parts of the input
    pub fn new() -> Self {
        Self::default()
    }

    /// Split working buffer and return the removed part
    ///
    /// # Arguments
    /// * `idx` - total idx to split
    fn move_forward(&mut self, idx: usize) -> VecDeque<u8> {
        let mut splitted = self.buffer.split_off(idx - self.buffer_idx);

        // Swap to return cut part
        swap(&mut self.buffer, &mut splitted);

        self.buffer_idx = idx;

        splitted
    }

    /// Adds new matcher into filtering
    ///
    /// # Arguments
    /// * `matcher` - matcher which matches the path
    ///
    /// # Example
    ///
    /// ```
    /// use streamson_lib::{strategy, matcher};
    /// use std::sync::{Arc, Mutex};
    ///
    /// let mut filter = strategy::Filter::new();
    /// let matcher = matcher::Simple::new(r#"{"list"}[]"#).unwrap();
    /// filter.add_matcher(
    ///     Box::new(matcher),
    /// );
    /// ```
    pub fn add_matcher(&mut self, matcher: Box<dyn MatchMaker>) {
        self.matchers.push(matcher);
    }

    /// Processes input data
    ///
    /// # Returns
    /// * `Ok(_) processing passed, more data might be needed
    /// * `Err(_)` when input is not correct json
    ///
    /// # Errors
    /// * Error is triggered when incorrect json is detected
    ///   Note that not all json errors are detected
    pub fn process(&mut self, input: &[u8]) -> Result<Vec<u8>, error::General> {
        // Feed the streamer
        self.streamer.feed(input);

        // Feed the input buffer
        self.buffer.extend(input);

        // initialize result
        let mut result = Vec::new();
        loop {
            match self.streamer.read()? {
                Output::Pending => {
                    if self.matched_path.is_none() {
                        if let Some(final_idx) = self.last_output_idx {
                            result.extend(self.move_forward(final_idx));
                        }
                    }
                    return Ok(result);
                }
                Output::Start(idx) => {
                    // The path is not matched yet
                    if self.matched_path.is_none() {
                        // Discard first
                        if self.delayed_discard {
                            self.move_forward(idx);
                            self.delayed_discard = false;
                        }

                        let current_path = self.streamer.current_path().clone();

                        // check whether matches
                        if self.matchers.iter().any(|e| e.match_path(&current_path)) {
                            self.matched_path = Some(current_path);

                            // We can move idx forward (export last data which can be exported
                            let move_to_idx = if let Some(last_idx) = self.last_output_idx.take() {
                                last_idx
                            } else {
                                idx
                            };
                            result.extend(self.move_forward(move_to_idx));

                            // Special handling of first item in array / dict for output
                            if self.last_output_level < self.streamer.current_path().depth() {
                                self.delayed_discard = true;
                            }
                        } else {
                            self.last_output_idx = Some(idx + 1); // one element before
                            self.last_output_level = self.streamer.current_path().depth();
                        }
                    }
                }
                Output::End(idx) => {
                    if let Some(path) = self.matched_path.as_ref() {
                        if path == self.streamer.current_path() {
                            self.matched_path = None;

                            // move idx without storing it
                            if !self.delayed_discard {
                                self.move_forward(idx);
                            }
                        }
                    } else {
                        // Discard
                        if self.delayed_discard {
                            self.move_forward(idx - 1); // idx is on closing `]` or `}`
                            self.delayed_discard = false;
                        }

                        self.last_output_idx = Some(idx);
                        self.last_output_level = self.streamer.current_path().depth();
                    }
                }
                Output::Separator(idx) => {
                    if self.matched_path.is_none() {
                        if self.delayed_discard {
                            // special first child to filter case
                            self.move_forward(idx + 1); // rmeove with separator
                            self.delayed_discard = false;
                            self.last_output_idx = Some(idx + 1);
                        } else {
                            // just update output index to separator index
                            self.last_output_idx = Some(idx);
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Filter;
    use crate::matcher::{Combinator, Simple};

    fn get_input() -> Vec<Vec<u8>> {
        vec![
            br#"{"users": [{"uid": 1}, {"uid": 2}, {"uid": 3}], "groups": [{"gid": 1}, {"gid": 2}], "void": {}}"#
                .iter()
                .map(|e| *e)
                .collect(),
        ]
    }

    #[test]
    fn single_matcher_no_match() {
        let input = get_input();

        let matcher = Simple::new(r#"{"no-existing"}[]{"uid"}"#).unwrap();
        let mut filter = Filter::new();
        filter.add_matcher(Box::new(matcher));

        assert_eq!(filter.process(&input[0]).unwrap(), input[0].clone());
    }

    #[test]
    fn single_matcher_array_first() {
        let input = get_input();
        let matcher = Simple::new(r#"{"users"}[0]"#).unwrap();

        let mut filter = Filter::new();
        filter.add_matcher(Box::new(matcher));

        assert_eq!(
            String::from_utf8(filter.process(&input[0]).unwrap()).unwrap(),
            r#"{"users": [ {"uid": 2}, {"uid": 3}], "groups": [{"gid": 1}, {"gid": 2}], "void": {}}"#
        );
    }

    #[test]
    fn single_matcher_array_last() {
        let input = get_input();
        let matcher = Simple::new(r#"{"users"}[2]"#).unwrap();

        let mut filter = Filter::new();
        filter.add_matcher(Box::new(matcher));

        assert_eq!(
            String::from_utf8(filter.process(&input[0]).unwrap()).unwrap(),
            r#"{"users": [{"uid": 1}, {"uid": 2}], "groups": [{"gid": 1}, {"gid": 2}], "void": {}}"#
        );
    }

    #[test]
    fn single_matcher_array_middle() {
        let input = get_input();
        let matcher = Simple::new(r#"{"users"}[1]"#).unwrap();

        let mut filter = Filter::new();
        filter.add_matcher(Box::new(matcher));

        assert_eq!(
            String::from_utf8(filter.process(&input[0]).unwrap()).unwrap(),
            r#"{"users": [{"uid": 1}, {"uid": 3}], "groups": [{"gid": 1}, {"gid": 2}], "void": {}}"#
        );
    }

    #[test]
    fn single_matcher_array_all() {
        let input = get_input();
        let matcher = Simple::new(r#"{"users"}[]"#).unwrap();

        let mut filter = Filter::new();
        filter.add_matcher(Box::new(matcher));

        assert_eq!(
            String::from_utf8(filter.process(&input[0]).unwrap()).unwrap(),
            r#"{"users": [], "groups": [{"gid": 1}, {"gid": 2}], "void": {}}"#
        );
    }

    #[test]
    fn single_matcher_object_first() {
        let input = get_input();
        let matcher = Simple::new(r#"{"users"}"#).unwrap();

        let mut filter = Filter::new();
        filter.add_matcher(Box::new(matcher));

        assert_eq!(
            String::from_utf8(filter.process(&input[0]).unwrap()).unwrap(),
            r#"{ "groups": [{"gid": 1}, {"gid": 2}], "void": {}}"#
        );
    }

    #[test]
    fn single_matcher_object_last() {
        let input = get_input();
        let matcher = Simple::new(r#"{"void"}"#).unwrap();

        let mut filter = Filter::new();
        filter.add_matcher(Box::new(matcher));

        assert_eq!(
            String::from_utf8(filter.process(&input[0]).unwrap()).unwrap(),
            r#"{"users": [{"uid": 1}, {"uid": 2}, {"uid": 3}], "groups": [{"gid": 1}, {"gid": 2}]}"#
        );
    }

    #[test]
    fn single_matcher_object_middle() {
        let input = get_input();
        let matcher = Simple::new(r#"{"groups"}"#).unwrap();

        let mut filter = Filter::new();
        filter.add_matcher(Box::new(matcher));

        assert_eq!(
            String::from_utf8(filter.process(&input[0]).unwrap()).unwrap(),
            r#"{"users": [{"uid": 1}, {"uid": 2}, {"uid": 3}], "void": {}}"#
        );
    }

    #[test]
    fn single_matcher_object_all() {
        let input = get_input();
        let matcher = Simple::new(r#"{}"#).unwrap();

        let mut filter = Filter::new();
        filter.add_matcher(Box::new(matcher));

        assert_eq!(
            String::from_utf8(filter.process(&input[0]).unwrap()).unwrap(),
            r#"{}"#
        );
    }

    #[test]
    fn combinator_slices() {
        let input = get_input();
        for i in 0..input.len() {
            let start_input = &input[0][0..i];
            let end_input = &input[0][i..];
            let matcher = Combinator::new(Simple::new(r#"{"users"}"#).unwrap())
                | Combinator::new(Simple::new(r#"{"void"}"#).unwrap());
            let mut filter = Filter::new();
            filter.add_matcher(Box::new(matcher));
            let mut result: Vec<u8> = Vec::new();

            result.extend(filter.process(&start_input).unwrap());
            result.extend(filter.process(&end_input).unwrap());
            assert_eq!(
                String::from_utf8(result).unwrap(),
                r#"{ "groups": [{"gid": 1}, {"gid": 2}]}"#
            )
        }
    }
}