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
//! This module contains the functionality to process a stream of bytes to
//! convert JSON to JSONL.

use crate::{
    brackets::{is_closing_bracket, is_opening_bracket, BracketStack},
    json_object::JSONLString,
};

/// This struct contains the functionality to process a stream of bytes to
/// convert JSON to JSONL. It keeps track of the brackets that have been opened
/// but not closed, as well as the JSONL string that is being built.
///
/// # Fields
///
/// * `bracket_stack` - A stack of brackets that have been opened but not closed.
/// * `jsonl_string` - The JSONL string that is being built.
pub struct ByteProcessor {
    pub bracket_stack: BracketStack,
    jsonl_string: JSONLString,
    inside_string: bool,
    last_char_escape: bool,
}

impl ByteProcessor {
    /// Creates a new instance of `ByteProcessor`.
    pub fn new() -> Self {
        ByteProcessor {
            bracket_stack: BracketStack::new(),
            jsonl_string: JSONLString::new(),
            inside_string: false,
            last_char_escape: false,
        }
    }

    /// Adds a bracket to the `bracket_stack`.
    ///
    /// # Arguments
    ///
    /// * `byte` - A character.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonl_converter::processors::byte_processor::ByteProcessor;
    ///
    /// let mut processor = ByteProcessor::new();
    /// processor.push_bracket(&'[');
    /// ```
    pub fn push_bracket(&mut self, byte: &char) {
        self.bracket_stack.push(&byte);
    }

    /// Processes a character. This function will either add the character to the
    /// `jsonl_string` or print the `jsonl_string` if the character is a closing
    /// bracket and the `bracket_stack` is empty (except for the initial
    /// opening bracket).
    ///
    /// # Arguments
    ///
    /// * `byte` - A character.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonl_converter::processors::byte_processor::ByteProcessor;
    ///
    /// let mut processor = ByteProcessor::new();
    /// processor.push_bracket(&'[');
    /// processor.process_char(&'{');
    /// processor.process_char(&'a');
    /// processor.process_char(&':');
    /// processor.process_char(&'1');
    /// processor.process_char(&'}');
    /// ```
    pub fn process_char(&mut self, byte: &char) {
        match byte {
            &'"' => self.process_quote(byte),
            b if !self.inside_string && is_opening_bracket(&b) => self.process_opening_bracket(b),
            b if !self.inside_string && is_closing_bracket(&b) => self.process_closing_bracket(b),
            _ => self.process_other_char(byte),
        }

        self.update_last_char_escape(byte);
    }

    /// If the current character is an escape character, this function will
    /// set the `last_char_escape` flag to `true` unless the previous character
    /// was also an escape character
    fn update_last_char_escape(&mut self, byte: &char) {
        self.last_char_escape = byte == &'\\' && !self.last_char_escape;
    }

    /// Processes a character that is a quote. This function will add the
    /// character to the `jsonl_string` and toggle the `inside_string` flag.
    fn process_quote(&mut self, byte: &char) {
        self.jsonl_string.push_char(&byte);
        if !self.last_char_escape {
            self.inside_string = !self.inside_string;
        }
    }

    /// Processes an opening bracket by adding it to the `bracket_stack` and
    /// `jsonl_string`.
    fn process_opening_bracket(&mut self, byte: &char) {
        self.bracket_stack.push(&byte);
        self.jsonl_string.push_char(&byte);
    }

    /// Processes a closing bracket by popping the corresponding opening bracket
    /// from the `bracket_stack` and adding it to the `jsonl_string`. If the
    /// `bracket_stack` is empty (except for the initial opening bracket), the
    /// `jsonl_string` is printed and cleared.
    fn process_closing_bracket(&mut self, byte: &char) {
        self.bracket_stack.pop_pair(&byte).unwrap();

        if self.should_print() {
            self.jsonl_string.push_char(&byte);

            println!("{}", self.jsonl_string);
            self.jsonl_string.clear();
        } else {
            self.jsonl_string.push_char(&byte);
        }
    }

    /// Processes a character that is not a bracket by adding it to the
    /// `jsonl_string`.
    fn process_other_char(&mut self, byte: &char) {
        self.jsonl_string.push_char(&byte);
    }

    /// Checks if the `jsonl_string` should be printed. This is the case if the
    /// `bracket_stack` is empty (except for the initial opening bracket).
    fn should_print(&mut self) -> bool {
        self.bracket_stack.len() == 1
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_processor_new_returns_processor_with_empty_attrs() {
        let processor = ByteProcessor::new();
        assert_eq!(processor.bracket_stack.is_empty(), true);
    }

    #[test]
    fn test_processor_push_bracket_adds_bracket_to_bracket_stack() {
        let mut processor = ByteProcessor::new();
        processor.push_bracket(&'[');
        assert_eq!(processor.bracket_stack.stack, vec!['[']);
    }

    #[test]
    fn test_processor_process_quote_pushes_quote_to_jsonl_string() {
        let mut processor = ByteProcessor::new();
        processor.process_quote(&'"');
        assert_eq!(processor.jsonl_string.to_string(), String::from("\""));
    }

    #[test]
    fn test_processor_process_quote_flips_inside_string_flag() {
        let mut processor = ByteProcessor::new();
        processor.process_quote(&'"');
        assert_eq!(processor.inside_string, true);
        processor.process_quote(&'"');
        assert_eq!(processor.inside_string, false);
    }

    #[test]
    fn test_last_char_escape_flag_flipped_on_escape_char() {
        let mut processor = ByteProcessor::new();
        processor.process_char(&'\\');
        assert_eq!(processor.last_char_escape, true);
        processor.process_char(&'a');
        assert_eq!(processor.last_char_escape, false);
    }

    #[test]
    fn test_bracket_inside_str_is_treated_as_string() {
        let mut processor = ByteProcessor::new();
        processor.process_char(&'"');
        processor.process_char(&'[');
        assert_eq!(processor.jsonl_string.to_string(), String::from("\"["));
        assert_eq!(processor.inside_string, true);
        assert_eq!(processor.bracket_stack.stack.len(), 0);
    }

    #[test]
    fn test_process_opening_bracket() {
        let mut processor = ByteProcessor::new();
        processor.process_opening_bracket(&'[');
        assert_eq!(processor.bracket_stack.stack, vec!['[']);
        assert_eq!(processor.jsonl_string.to_string(), String::from("["));
    }

    #[test]
    fn test_process_opening_bracket_recognises_entire_line_not_ready() {
        let mut processor = ByteProcessor::new();
        processor.bracket_stack.push(&'[');
        processor.bracket_stack.push(&'{');
        processor.bracket_stack.push(&'{');
        processor.jsonl_string.push_str(&"{'a': {'a': 1");
        processor.process_closing_bracket(&'}');

        assert_eq!(
            processor.jsonl_string.to_string(),
            String::from("{'a': {'a': 1}")
        );
        assert_eq!(processor.bracket_stack.stack, vec!['[', '{']);
    }

    #[test]
    fn test_process_opening_bracket_recognises_line_is_ready() {
        let mut processor = ByteProcessor::new();
        processor.bracket_stack.push(&'[');
        processor.bracket_stack.push(&'{');
        processor.jsonl_string.push_str(&"{'a': {'a': 1}");
        processor.process_closing_bracket(&'}');

        // After it notices that the line is complete, it prints the line
        // and clears the `jsonl_string`.
        assert_eq!(processor.jsonl_string.to_string(), String::from(""));
        assert_eq!(processor.bracket_stack.stack, vec!['[']);
    }

    #[test]
    fn test_process_other_char_pushes_char_to_jsonl_string() {
        let mut processor = ByteProcessor::new();
        processor.process_other_char(&'a');
        assert_eq!(processor.jsonl_string.to_string(), String::from("a"));
        assert_eq!(processor.bracket_stack.len(), 0);
    }

    #[test]
    fn test_should_print_true_if_bracket_stack_len_1() {
        let mut processor = ByteProcessor::new();
        processor.bracket_stack.push(&'[');
        assert_eq!(processor.should_print(), true);
    }

    #[test]
    fn test_should_print_false_if_bracket_stack_len_not_1() {
        let mut processor = ByteProcessor::new();
        processor.bracket_stack.push(&'[');
        processor.bracket_stack.push(&'{');
        assert_eq!(processor.should_print(), false);
    }

    #[test]
    fn test_process_char_flow_with_curly_inner_bracket() {
        let mut processor = ByteProcessor::new();
        processor.bracket_stack.push(&'[');

        // {
        processor.process_char(&'{');
        assert_eq!(processor.jsonl_string.to_string(), String::from("{"));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '{']);

        // {a
        processor.process_char(&'a');
        assert_eq!(processor.jsonl_string.to_string(), String::from("{a"));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '{']);

        // {a:
        processor.process_char(&':');
        assert_eq!(processor.jsonl_string.to_string(), String::from("{a:"));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '{']);

        // {a:{
        processor.process_char(&'{');
        assert_eq!(processor.jsonl_string.to_string(), String::from("{a:{"));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '{', '{']);

        // {a:{b
        processor.process_char(&'b');
        assert_eq!(processor.jsonl_string.to_string(), String::from("{a:{b"));

        // {a:{b:
        processor.process_char(&':');
        assert_eq!(processor.jsonl_string.to_string(), String::from("{a:{b:"));

        // {a:{b:1
        processor.process_char(&'1');
        assert_eq!(processor.jsonl_string.to_string(), String::from("{a:{b:1"));

        // {a:{b:1}
        processor.process_char(&'}');
        assert_eq!(processor.jsonl_string.to_string(), String::from("{a:{b:1}"));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '{']);

        // {a:{b:1}}
        processor.process_char(&'}');
        assert_eq!(processor.jsonl_string.to_string(), String::from(""));
        assert_eq!(processor.bracket_stack.stack, vec!['[']);
    }

    #[test]
    fn test_process_char_flow_with_square_inner_bracket() {
        let mut processor = ByteProcessor::new();
        processor.bracket_stack.push(&'[');

        // [
        processor.process_char(&'[');
        assert_eq!(processor.jsonl_string.to_string(), String::from("["));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '[']);

        // [a
        processor.process_char(&'a');
        assert_eq!(processor.jsonl_string.to_string(), String::from("[a"));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '[']);

        // [a:
        processor.process_char(&':');
        assert_eq!(processor.jsonl_string.to_string(), String::from("[a:"));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '[']);

        // [a:[
        processor.process_char(&'[');
        assert_eq!(processor.jsonl_string.to_string(), String::from("[a:["));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '[', '[']);

        // [a:[b
        processor.process_char(&'b');
        assert_eq!(processor.jsonl_string.to_string(), String::from("[a:[b"));

        // [a:[b:
        processor.process_char(&':');
        assert_eq!(processor.jsonl_string.to_string(), String::from("[a:[b:"));

        // [a:[b:1
        processor.process_char(&'1');
        assert_eq!(processor.jsonl_string.to_string(), String::from("[a:[b:1"));

        // [a:[b:1]
        processor.process_char(&']');
        assert_eq!(processor.jsonl_string.to_string(), String::from("[a:[b:1]"));
        assert_eq!(processor.bracket_stack.stack, vec!['[', '[']);

        // [a:[b:1]]
        processor.process_char(&']');
        assert_eq!(processor.jsonl_string.to_string(), String::from(""));
        assert_eq!(processor.bracket_stack.stack, vec!['[']);
    }
}