jsonic 0.2.14

Fast, small JSON parsing library for rust with no dependencies
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use crate::json_error::JsonError;
use crate::json_item::JsonItem;
use crate::json_type::JsonType::{JsonFalse, JsonNull, JsonNumber, JsonString, JsonTrue};
use crate::key::Key;
use crate::slice::Slice;

pub mod json_error;
pub mod slice;
pub mod json_item;

pub mod json_type;
pub mod key;
pub mod generics;

const DEFAULT_VEC_CAPACITY: usize = 2;

#[inline(always)]
fn shift_index(item: &JsonItem) -> usize {
    if item.json_type == JsonString {
        item.slice.len + 2
    } else {
        item.slice.len
    }
}

#[inline(always)]
fn skip_spaces(bytes: &[u8], mut index: usize) -> Result<usize, JsonError> {
    while index < bytes.len() {
        match bytes[index] {
            b' ' | b'\n' | b'\r' | b'\t' => {}
            _ => { return Ok(index); }
        }
        index += 1;
    }
    Err(JsonError::new(bytes, index))
}

#[inline(always)]
fn parse_null(bytes: &[u8], index: usize) -> Result<JsonItem, JsonError> {
    if index + 3 < bytes.len() {
        if bytes[index + 1] == b'u' && bytes[index + 2] == b'l' && bytes[index + 3] == b'l' {
            return Ok(JsonItem::new(Slice::from_bytes(bytes, index, index + 4), JsonNull));
        }
    }
    Err(JsonError::new(bytes, index))
}

#[inline(always)]
fn parse_true(bytes: &[u8], index: usize) -> Result<JsonItem, JsonError> {
    if index + 3 < bytes.len() {
        if bytes[index + 1] == b'r' && bytes[index + 2] == b'u' && bytes[index + 3] == b'e' {
            return Ok(JsonItem::new(Slice::from_bytes(bytes, index, index + 4), JsonTrue));
        }
    }
    Err(JsonError::new(bytes, index))
}

#[inline(always)]
fn parse_false(bytes: &[u8], index: usize) -> Result<JsonItem, JsonError> {
    if index + 4 < bytes.len() {
        if bytes[index + 1] == b'a' && bytes[index + 2] == b'l' && bytes[index + 3] == b's' && bytes[index + 4] == b'e' {
            return Ok(JsonItem::new(Slice::from_bytes(bytes, index, index + 5), JsonFalse));
        }
    }
    Err(JsonError::new(bytes, index))
}

#[inline(always)]
fn parse_number(bytes: &[u8], mut index: usize) -> Result<JsonItem, JsonError> {
    let mark = index;
    index += 1;
    while index < bytes.len() {
        match bytes[index] {
            b'0'..=b'9' | b'+' | b'-' | b'.' | b'e' | b'E' => {}
            _ => {
                return Ok(JsonItem::new(Slice::from_bytes(bytes, mark, index), JsonNumber));
            }
        }
        index += 1;
    }
    Err(JsonError::new(bytes, index))
}

#[inline(always)]
fn parse_string(bytes: &[u8], mut index: usize) -> Result<JsonItem, JsonError> {
    index += 1;
    let mark = index;
    let mut b = 0;
    while index < bytes.len() {
        let p = b;
        b = bytes[index];
        if b == b'"' {
            if p != b'\\' {
                return Ok(JsonItem::new(Slice::from_bytes(bytes, mark, index), JsonString));
            }
        }
        index += 1;
    }
    Err(JsonError::new(bytes, index))
}

#[inline(always)]
fn parse_item(bytes: &[u8], index: usize) -> Result<JsonItem, JsonError> {
    match bytes[index] {
        b'n' => { Ok(parse_null(bytes, index)?) }
        b't' => { Ok(parse_true(bytes, index)?) }
        b'f' => { Ok(parse_false(bytes, index)?) }
        b'+' | b'-' | b'0'..=b'9' => { Ok(parse_number(bytes, index)?) }
        b'"' => { Ok(parse_string(bytes, index)?) }
        b'{' => { Ok(parse_map(bytes, index)?) }
        b'[' => { Ok(parse_array(bytes, index)?) }
        _ => {
            Err(JsonError::new(bytes, index))
        }
    }
}

#[inline(always)]
fn parse_map(bytes: &[u8], mut index: usize) -> Result<JsonItem, JsonError> {
    let mark = index;
    index += 1;
    let mut map = None;
    loop {
        // Spaces
        index = skip_spaces(bytes, index)?;

        // Check ending
        match bytes[index] {
            b'}' => {
                return Ok(JsonItem::new_map(Slice::from_bytes(bytes, mark, index + 1), map));
            }
            b',' => {
                index = skip_spaces(bytes, index + 1)?;
            }
            _ => {
                if !map.is_none() {
                    return Err(JsonError::new(bytes, index));
                }
            }
        }

        // Key
        let key = parse_string(bytes, index)?;
        index += shift_index(&key);

        // Separator
        index = skip_spaces(bytes, index)?;
        if bytes[index] != b':' {
            return Err(JsonError::new(bytes, index));
        } else {
            index = skip_spaces(bytes, index + 1)?;
        }

        // Value
        let item = parse_item(bytes, index)?;
        index += shift_index(&item);

        // Store
        if let Some(m) = &mut map {
            m.push((Key::from_slice(key.slice), item));
        } else {
            let mut m = Vec::with_capacity(DEFAULT_VEC_CAPACITY);
            m.push((Key::from_slice(key.slice), item));
            map = Some(m);
        }
    }
}

#[inline(always)]
fn parse_array(bytes: &[u8], mut index: usize) -> Result<JsonItem, JsonError> {
    let mark = index;
    let mut array = None;
    index += 1;
    loop {
        // Spaces
        index = skip_spaces(bytes, index)?;

        // Check ending
        match bytes[index] {
            b']' => {
                return Ok(JsonItem::new_array(Slice::from_bytes(bytes, mark, index + 1), array));
            }
            b',' => {
                index = skip_spaces(bytes, index + 1)?;
            }
            _ => {
                if !array.is_none() {
                    return Err(JsonError::new(bytes, index));
                }
            }
        }

        // Item
        let item = parse_item(bytes, index)?;
        index += shift_index(&item);

        // Store
        if let Some(a) = &mut array {
            a.push(item);
        } else {
            let mut a = Vec::with_capacity(DEFAULT_VEC_CAPACITY);
            a.push(item);
            array = Some(a);
        }
    }
}

/// Main library function. Parses JSON data.
///
/// # Arguments
/// * `source` - Text content to be parsed
///
/// # Example
///
/// ```rust
/// fn main() {
///    let json = "{\"jsonic\": \"Fast, small JSON parsing library for rust with no dependencies\"}";
///
///    match jsonic::parse(json) {
///        Ok(parsed) => { println!("Describe jsonic? {:?}", parsed["jsonic"].as_str()); }
///        Err(error) => { eprintln!("{}", error); }
///    }
/// }
pub fn parse(source: &str) -> Result<JsonItem, JsonError> {
    let bytes = source.as_bytes();
    let mut index = 0_usize;
    index = skip_spaces(bytes, index)?;
    match bytes[index] {
        b'{' => { parse_map(bytes, index) }
        b'[' => { parse_array(bytes, index) }
        _ => { Err(JsonError::new(bytes, index)) }
    }
}

#[cfg(test)]
mod tests {
    use crate::parse;

    const CORRECT_JSON: &str = " {\n\"test\": \"why not?\",\"b\": true,\"another one\":  \"hey#çà@â&éè\" \r ,\"obj2\":{\"k\":{\"k2\":\"v\"}}, \"num\":4.2344, \"int\":-234,  \"obj\":{\"a\":\"b\", \"c\":\"d\"}, \"arr\":[1,2,3],\"bool\":false, \"exp\":3.3e-21, \"exp2\":-4.5e-213,\"exp3\":3.7391238e+24,\"depth\":[\"a\",[\"b\",\"c\"]],\"emp_a\":[],\"emp_m\":{}}  ";
    const INCORRECT_JSON: &str = "{\"test\": \"num\", \"int\":234[] ,,}";

    #[test]
    fn parse_correct() {
        match parse(CORRECT_JSON) {
            Ok(_) => {
                assert!(true);
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_incorrect() {
        match parse(INCORRECT_JSON) {
            Ok(_) => {
                assert!(false);
            }
            Err(_) => {
                assert!(true);
            }
        }
    }

    #[test]
    fn parse_string() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                assert_eq!(parsed["test"].as_str(), Some("why not?"));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_float() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                assert_eq!(parsed["num"].as_f64(), Some(4.2344));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_int() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                assert_eq!(parsed["int"].as_i128(), Some(-234));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_object() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                assert_eq!(parsed["obj"]["a"].as_str(), Some("b"));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_object_depth() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                assert_eq!(parsed["obj2"]["k"]["k2"].as_str(), Some("v"));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn traverse_object() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                let mut iterator = parsed["obj"].entries().unwrap();
                let (k, v) = iterator.next().unwrap();
                assert_eq!(k.as_str(), "a");
                assert_eq!(v.as_str(), Some("b"));
                let (k, v) = iterator.next().unwrap();
                assert_eq!(k.as_str(), "c");
                assert_eq!(v.as_str(), Some("d"));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_array() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                assert_eq!(parsed["arr"][1].as_i128(), Some(2));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_array_depth() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                assert_eq!(parsed["depth"][1][1].as_str(), Some("c"));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn traverse_array() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                let mut iterator = parsed["arr"].elements().unwrap();
                assert_eq!(iterator.next().unwrap().as_i128(), Some(1));
                assert_eq!(iterator.next().unwrap().as_i128(), Some(2));
                assert_eq!(iterator.next().unwrap().as_i128(), Some(3));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_bool() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                assert_eq!(parsed["bool"].as_bool(), Some(false));
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_exp() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                match parsed["exp"].as_f64() {
                    None => { assert!(false); }
                    Some(value) => { assert!(f64::abs(value / 3.3e-21 - 1.0) < 1e-8); }   // floating point error
                }
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn parse_exp_3_digits() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                match parsed["exp2"].as_f64() {
                    None => { assert!(false); }
                    Some(value) => { assert!(f64::abs(value / -4.5e-213 - 1.0) < 1e-8); }   // floating point error
                }
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn missing_key() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                assert_eq!(parsed["a"].exists(), false);
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn missing_key_get_value() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                match parsed["a"][1].as_i128() {
                    None => { assert!(true); }
                    Some(_) => { assert!(false); }
                }
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn empty_array_iterator() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                if let Some(mut elements) = parsed["emp_a"].elements() {
                    match elements.next() {
                        None => { assert!(true); }
                        Some(_) => { assert!(false); }
                    }
                }
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }

    #[test]
    fn empty_map_iterator() {
        match parse(CORRECT_JSON) {
            Ok(parsed) => {
                if let Some(mut entries) = parsed["emp_m"].entries() {
                    match entries.next() {
                        None => { assert!(true); }
                        Some(_) => { assert!(false); }
                    }
                }
            }
            Err(error) => {
                assert!(false, "{}", error.to_string());
            }
        }
    }
}