streamson-lib 7.1.0

Library for processing large JSONs
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Handler which alters indentation of matched data
//!
//! # Example
//! ```
//! use streamson_lib::{handler, matcher, strategy::{self, Strategy}};
//! use std::sync::{Arc, Mutex};
//!
//! let handler = Arc::new(Mutex::new(handler::Indenter::new(Some(2))));
//! let mut all = strategy::All::new();
//! all.set_convert(true);
//!
//! // Set the handler for all strategy
//! all.add_handler(handler);
//!
//! for input in vec![
//!     br#"{"users": [{"password": "1234", "name": "first"}, {"#.to_vec(),
//!     br#""password": "0000", "name": "second}]}"#.to_vec(),
//! ] {
//!     for converted_data in all.process(&input).unwrap() {
//!         println!("{:?}", converted_data);
//!     }
//! }
//! ```

use super::Handler;
use crate::{
    error,
    path::{Element, Path},
    streamer::{ParsedKind, Token},
};
use std::{any::Any, str::FromStr};

/// Handler which alters indentation of matched data
#[derive(Debug)]
pub struct Indenter {
    /// How many spaces should be used for indentation
    spaces: Option<usize>,
    /// Currently processed element on each level
    stack: Option<Vec<(usize, ParsedKind)>>,
}

impl Indenter {
    /// Creates a new handler which alters indentation
    ///
    /// # Arguments
    /// * spaces - how many spaces should be used for indentation (if None - no indentation or newline should be added)
    pub fn new(spaces: Option<usize>) -> Self {
        Self {
            spaces,
            stack: None,
        }
    }

    fn write_indent_level(&self, buff: &mut Vec<u8>) {
        if let Some(stack) = self.stack.as_ref() {
            for _ in 0..(stack.len() - 1) * self.spaces.unwrap_or(0) {
                buff.push(b' ');
            }
        }
    }
}

impl FromStr for Indenter {
    type Err = error::Handler;
    fn from_str(intend_str: &str) -> Result<Self, Self::Err> {
        if intend_str.is_empty() {
            Ok(Self::new(None))
        } else {
            Ok(Self::new(Some(
                intend_str.parse::<usize>().map_err(error::Handler::new)?,
            )))
        }
    }
}

impl Handler for Indenter {
    fn start(
        &mut self,
        path: &Path,
        _matcher_idx: usize,
        token: Token,
    ) -> Result<Option<Vec<u8>>, error::Handler> {
        let kind = if let Token::Start(_, kind) = token {
            kind
        } else {
            unreachable![];
        };

        let mut res = vec![];
        self.stack = if let Some(mut stack) = self.stack.take() {
            stack.push((0, kind));
            // We need to add separators for nested elements
            if stack.len() > 1 {
                if stack[stack.len() - 2].0 != 0 {
                    res.push(b',');
                }
                if self.spaces.is_some() {
                    res.push(b'\n');
                }
            }
            Some(stack)
        } else {
            // stack will always have one element
            Some(vec![(0, kind)])
        };

        self.write_indent_level(&mut res);
        // stack  should have at least one element now
        let stack = self.stack.as_ref().unwrap();
        if stack.len() > 1 {
            // Write key of parent object
            if matches!(stack[stack.len() - 2].1, ParsedKind::Obj) {
                if let Element::Key(key) = &path.get_path()[path.depth() - 1] {
                    res.push(b'"');
                    res.extend(key.as_bytes());
                    res.extend(br#"":"#);
                    if self.spaces.is_some() {
                        res.push(b' ');
                    }
                } else {
                    unreachable!();
                }
            }
        }

        match kind {
            ParsedKind::Arr => {
                res.push(b'[');
            }
            ParsedKind::Obj => {
                res.push(b'{');
            }
            _ => {}
        }

        if res.is_empty() {
            Ok(None)
        } else {
            Ok(Some(res))
        }
    }

    fn feed(
        &mut self,
        data: &[u8],
        _matcher_idx: usize,
    ) -> Result<Option<Vec<u8>>, error::Handler> {
        let mut result = vec![];
        if let Some(stack) = self.stack.as_ref() {
            if let Some((_, kind)) = stack.last() {
                match kind {
                    ParsedKind::Obj | ParsedKind::Arr => {}
                    _ => {
                        result.extend(data.to_vec());
                    }
                }
            }
        }
        Ok(Some(result))
    }

    fn end(
        &mut self,
        _path: &Path,
        _matcher_idx: usize,
        token: Token,
    ) -> Result<Option<Vec<u8>>, error::Handler> {
        let kind = if let Token::End(_, kind) = token {
            kind
        } else {
            unreachable![];
        };

        let mut res = vec![];
        if let Some(stack) = self.stack.as_ref() {
            match kind {
                ParsedKind::Arr => {
                    if stack.last().unwrap().0 != 0 && self.spaces.is_some() {
                        res.push(b'\n');
                        self.write_indent_level(&mut res);
                    }
                    res.push(b']');
                }
                ParsedKind::Obj => {
                    if stack.last().unwrap().0 != 0 && self.spaces.is_some() {
                        res.push(b'\n');
                        self.write_indent_level(&mut res);
                    }
                    res.push(b'}');
                }
                _ => {}
            };
        }

        if let Some(stack) = self.stack.as_mut() {
            // remove item from stack and increase parent count
            stack.pop();
            // Increase count
            if let Some((idx, _)) = stack.last_mut() {
                *idx += 1;
            }

            // finish newline
            if stack.is_empty() && self.spaces.is_some() {
                res.push(b'\n');
                self.stack = None;
            }
        }

        if res.is_empty() {
            Ok(None)
        } else {
            Ok(Some(res))
        }
    }

    fn is_converter(&self) -> bool {
        true
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::Indenter;
    use crate::strategy::{All, OutputConverter, Strategy};
    use rstest::*;
    use std::sync::{Arc, Mutex};

    fn make_all_with_spaces(level: Option<usize>) -> All {
        let mut all = All::new();
        all.set_convert(true);
        all.add_handler(Arc::new(Mutex::new(Indenter::new(level))));
        all
    }

    #[rstest(
        spaces,
        input,
        output,
        case::null_none(None, b"null", b"null"),
        case::null_0(Some(0), b"null", b"null\n"),
        case::null_2(Some(2), b"null", b"null\n"),
        case::obj_none(None, b"{}", b"{}"),
        case::obj_0(Some(0), b"{}", b"{}\n"),
        case::obj_2(Some(2), b"{}", b"{}\n"),
        case::arr_none(None, b"[]", b"[]"),
        case::arr_0(Some(0), b"[]", b"[]\n"),
        case::arr_2(Some(2), b"[]", b"[]\n"),
        case::str_none(None, br#""str""#, br#""str""#),
        case::str_0(Some(0), br#""str""#, b"\"str\"\n"),
        case::str_2(Some(2), br#""str""#, b"\"str\"\n"),
        before => [b"\n\n", b"\n", b" ", b""],
        after => [b"\n\n", b"\n", b" "]
    )]
    fn leafs(spaces: Option<usize>, input: &[u8], output: &[u8], before: &[u8], after: &[u8]) {
        let mut all = make_all_with_spaces(spaces);
        let mut final_input = vec![];
        final_input.extend(before);
        final_input.extend(input);
        final_input.extend(after);
        let result = OutputConverter::new().convert(&all.process(&final_input).unwrap());

        assert_eq!(result.len(), 1);
        assert_eq!((None, output.to_vec()), result[0]);
    }

    #[test]
    fn flat_array() {
        let input = b" [ \n 3 \n , null,true,\n false, \"10\"\n]".to_vec();

        // No indentation or spaces
        let mut all = make_all_with_spaces(None);
        assert_eq!(
            br#"[3,null,true,false,"10"]"#.to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // No indentation
        let mut all = make_all_with_spaces(Some(0));
        assert_eq!(
            b"[\n3,\nnull,\ntrue,\nfalse,\n\"10\"\n]\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // 2 indentation
        let mut all = make_all_with_spaces(Some(2));
        assert_eq!(
            b"[\n  3,\n  null,\n  true,\n  false,\n  \"10\"\n]\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );
    }

    #[test]
    fn nested_array() {
        let input = b" [ \n [3] \n , [],null,[[]], \"10\"\n,[[[]]]]".to_vec();

        // No indentation or spaces
        let mut all = make_all_with_spaces(None);
        assert_eq!(
            br#"[[3],[],null,[[]],"10",[[[]]]]"#.to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // No indentation
        let mut all = make_all_with_spaces(Some(0));
        assert_eq!(
            b"[\n[\n3\n],\n[],\nnull,\n[\n[]\n],\n\"10\",\n[\n[\n[]\n]\n]\n]\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // 2 indentation
        let mut all = make_all_with_spaces(Some(2));
        assert_eq!(
            b"[\n  [\n    3\n  ],\n  [],\n  null,\n  [\n    []\n  ],\n  \"10\",\n  [\n    [\n      []\n    ]\n  ]\n]\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );
    }

    #[test]
    fn flat_object() {
        let input =
            b" { \n \"1\" \n: 1 , \"2\":\"2\",   \"3\": null\n, \"4\":\n\nfalse\n\n\n}".to_vec();

        // No indentation or spaces
        let mut all = make_all_with_spaces(None);
        assert_eq!(
            br#"{"1":1,"2":"2","3":null,"4":false}"#.to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // No indentation
        let mut all = make_all_with_spaces(Some(0));
        assert_eq!(
            b"{\n\"1\": 1,\n\"2\": \"2\",\n\"3\": null,\n\"4\": false\n}\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // 2 indentation
        let mut all = make_all_with_spaces(Some(2));
        assert_eq!(
            b"{\n  \"1\": 1,\n  \"2\": \"2\",\n  \"3\": null,\n  \"4\": false\n}\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );
    }

    #[test]
    fn nested_object() {
        let input =
            b" { \n \"1\" \n: {} , \"2\":{\"2a\": {}},   \"3\": null\n, \"4\":\n\n{\"4a\": {\"4aa\": {}}}\n\n\n}".to_vec();

        // No indentation or spaces
        let mut all = make_all_with_spaces(None);
        assert_eq!(
            br#"{"1":{},"2":{"2a":{}},"3":null,"4":{"4a":{"4aa":{}}}}"#.to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // No indentation
        let mut all = make_all_with_spaces(Some(0));
        assert_eq!(
            b"{\n\"1\": {},\n\"2\": {\n\"2a\": {}\n},\n\"3\": null,\n\"4\": {\n\"4a\": {\n\"4aa\": {}\n}\n}\n}\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // 2 indentation
        let mut all = make_all_with_spaces(Some(2));
        assert_eq!(
            b"{\n  \"1\": {},\n  \"2\": {\n    \"2a\": {}\n  },\n  \"3\": null,\n  \"4\": {\n    \"4a\": {\n      \"4aa\": {}\n    }\n  }\n}\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );
    }

    #[test]
    fn complex() {
        let input =
            b" { \n \"1\" \n: [] , \"2\":{\"2a\": []},   \"3\": null\n, \"4\":\n\n[ {\"4aa\": {}}]\n\n\n}".to_vec();

        // No indentation or spaces
        let mut all = make_all_with_spaces(None);
        assert_eq!(
            br#"{"1":[],"2":{"2a":[]},"3":null,"4":[{"4aa":{}}]}"#.to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // No indentation
        let mut all = make_all_with_spaces(Some(0));
        assert_eq!(
            b"{\n\"1\": [],\n\"2\": {\n\"2a\": []\n},\n\"3\": null,\n\"4\": [\n{\n\"4aa\": {}\n}\n]\n}\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );

        // 2 indentation
        let mut all = make_all_with_spaces(Some(2));
        assert_eq!(
            b"{\n  \"1\": [],\n  \"2\": {\n    \"2a\": []\n  },\n  \"3\": null,\n  \"4\": [\n    {\n      \"4aa\": {}\n    }\n  ]\n}\n".to_vec(),
            OutputConverter::new().convert(&all.process(&input).unwrap())[0].1
        );
    }
}