jshift 0.2.0

Schema-guided, safe in-place JSON path reader and mutator for raw byte buffers.
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
use memchr::memchr;

use crate::error::Error;
use crate::path::PathSegment;

/// Locates a JSON value byte-slice within a raw JSON buffer by its path.
///
/// Returns the slice of the raw JSON value (e.g., `b"123"`, `b"\"hello\""`, or `b"{\"nested\": true}"`).
///
/// # Examples
/// ```
/// use jshift::{find_value, parse_path};
///
/// let json = b"{\"metadata\": {\"author\": \"farmer\"}}";
/// let val = find_value(json, &parse_path("metadata.author")).unwrap();
/// assert_eq!(val, b"\"farmer\"");
/// ```
pub fn find_value<'a>(json: &'a [u8], path: &[PathSegment]) -> Result<&'a [u8], Error> {
    let (start, end) = find_value_offsets(json, path)?;
    Ok(&json[start..end])
}

/// Locate a member of the object at `object_path` whose key content equals `key_raw`
/// (escaped form as stored between quotes).
///
/// Returns `(key_open_quote, value_start, value_end)`.
pub(crate) fn find_object_member_offsets(
    json: &[u8],
    object_path: &[PathSegment],
    key_raw: &[u8],
) -> Result<(usize, usize, usize), Error> {
    let (obj_start, obj_end) = find_value_offsets(json, object_path)?;
    if obj_start >= json.len() || json[obj_start] != b'{' {
        return Err(Error::TypeMismatch {
            expected: "object",
            found: "primitive/array",
        });
    }

    let mut pos = obj_start + 1;
    loop {
        pos = skip_whitespace(json, pos);
        if pos >= obj_end {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unexpected EOF inside object",
            });
        }
        if json[pos] == b'}' {
            return Err(Error::PathNotFound);
        }
        if json[pos] != b'"' {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Expected object key string starting with double quote",
            });
        }

        let key_open = pos;
        let key_start = pos + 1;
        let key_end = find_string_end(json, key_start)?;
        let key = &json[key_start..key_end];

        pos = key_end + 1;
        pos = skip_whitespace(json, pos);
        if pos >= json.len() || json[pos] != b':' {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Expected colon ':' key separator",
            });
        }
        pos += 1;
        pos = skip_whitespace(json, pos);
        let val_start = pos;
        let val_end = skip_value(json, val_start)?;

        if key == key_raw {
            return Ok((key_open, val_start, val_end));
        }

        pos = skip_whitespace(json, val_end);
        if pos >= json.len() {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unexpected EOF",
            });
        }
        if json[pos] == b',' {
            pos += 1;
        } else if json[pos] == b'}' {
            return Err(Error::PathNotFound);
        } else {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Expected comma ',' or closing brace '}'",
            });
        }
    }
}

/// Helper that locates a JSON value byte-slice boundaries within a raw JSON buffer by its path.
/// Returns a tuple of `(start_index, end_index)`.
pub(crate) fn find_value_offsets(json: &[u8], path: &[PathSegment]) -> Result<(usize, usize), Error> {
    if path.is_empty() {
        return Ok((0, json.len()));
    }
    let pos = skip_whitespace(json, 0);
    if pos >= json.len() {
        return Err(Error::InvalidJsonSyntax {
            pos,
            msg: "Unexpected EOF",
        });
    }

    match &path[0] {
        PathSegment::Key(_) => {
            if byte_at(json, pos)? != b'{' {
                return Err(Error::InvalidJsonSyntax {
                    pos,
                    msg: "Expected opening brace '{' for object",
                });
            }
            find_in_object_offsets(json, pos + 1, path)
        }
        PathSegment::Index(_) => {
            if byte_at(json, pos)? != b'[' {
                return Err(Error::InvalidJsonSyntax {
                    pos,
                    msg: "Expected opening bracket '[' for array",
                });
            }
            find_in_array_offsets(json, pos + 1, path)
        }
    }
}

/// Recursively or iteratively scans an object starting after the '{' or after a key-value comma.
fn find_in_object_offsets(
    json: &[u8],
    mut pos: usize,
    path: &[PathSegment],
) -> Result<(usize, usize), Error> {
    let target_key = match &path[0] {
        PathSegment::Key(key) => key.as_bytes(),
        _ => return Err(Error::PathNotFound),
    };

    loop {
        pos = skip_whitespace(json, pos);
        if pos >= json.len() {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unexpected EOF",
            });
        }

        // Check if we hit the end of the object before finding the key
        if json[pos] == b'}' {
            return Err(Error::PathNotFound);
        }

        // We expect a string key starting with '"'
        if json[pos] != b'"' {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Expected object key string starting with double quote",
            });
        }

        let key_start = pos + 1;
        let key_end = find_string_end(json, key_start)?;
        let key = &json[key_start..key_end];

        pos = key_end + 1; // move past closing '"'

        // Skip whitespace and locate the ':' delimiter
        pos = skip_whitespace(json, pos);
        if pos >= json.len() || json[pos] != b':' {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Expected colon ':' key separator",
            });
        }
        pos += 1; // move past ':'

        pos = skip_whitespace(json, pos);
        let val_start = pos;
        let val_end = skip_value(json, val_start)?;

        if key == target_key {
            // We found the matching key!
            if path.len() == 1 {
                return Ok((val_start, val_end));
            } else {
                // We need to go deeper
                match &path[1] {
                    PathSegment::Key(_) => {
                        if json[val_start] == b'{' {
                            return find_in_object_offsets(json, val_start + 1, &path[1..]);
                        } else {
                            return Err(Error::TypeMismatch {
                                expected: "object",
                                found: "primitive/array",
                            });
                        }
                    }
                    PathSegment::Index(_) => {
                        if json[val_start] == b'[' {
                            return find_in_array_offsets(json, val_start + 1, &path[1..]);
                        } else {
                            return Err(Error::TypeMismatch {
                                expected: "array",
                                found: "primitive/object",
                            });
                        }
                    }
                }
            }
        }

        // Key didn't match, skip this value and look for the next comma ',' or object end '}'
        pos = val_end;
        pos = skip_whitespace(json, pos);
        if pos >= json.len() {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unexpected EOF",
            });
        }

        if json[pos] == b',' {
            pos += 1; // Move past comma to scan next key-value pair
        } else if json[pos] == b'}' {
            return Err(Error::PathNotFound); // End of object
        } else {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Expected comma ',' or closing brace '}'",
            });
        }
    }
}

/// Recursively scans an array starting after the '[' or after an element comma.
fn find_in_array_offsets(
    json: &[u8],
    mut pos: usize,
    path: &[PathSegment],
) -> Result<(usize, usize), Error> {
    let target_idx = match path[0] {
        PathSegment::Index(idx) => idx,
        _ => return Err(Error::PathNotFound),
    };

    // Skip elements to reach the target index
    for _ in 0..target_idx {
        pos = skip_whitespace(json, pos);
        if pos >= json.len() || json[pos] == b']' {
            return Err(Error::IndexOutOfBounds {
                index: target_idx,
            });
        }
        pos = skip_value(json, pos)?;
        pos = skip_whitespace(json, pos);
        if pos >= json.len() {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unexpected EOF",
            });
        }
        if json[pos] != b',' {
            if json[pos] == b']' {
                return Err(Error::IndexOutOfBounds {
                    index: target_idx,
                });
            }
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Expected comma ',' array element separator",
            });
        }
        pos += 1; // skip comma
    }

    pos = skip_whitespace(json, pos);
    if pos >= json.len() || json[pos] == b']' {
        return Err(Error::IndexOutOfBounds {
            index: target_idx,
        });
    }

    let val_start = pos;
    let val_end = skip_value(json, val_start)?;

    if path.len() == 1 {
        Ok((val_start, val_end))
    } else {
        // Go deeper
        match &path[1] {
            PathSegment::Key(_) => {
                if json[val_start] == b'{' {
                    find_in_object_offsets(json, val_start + 1, &path[1..])
                } else {
                    Err(Error::TypeMismatch {
                        expected: "object",
                        found: "primitive/array",
                    })
                }
            }
            PathSegment::Index(_) => {
                if json[val_start] == b'[' {
                    find_in_array_offsets(json, val_start + 1, &path[1..])
                } else {
                    Err(Error::TypeMismatch {
                        expected: "array",
                        found: "primitive/object",
                    })
                }
            }
        }
    }
}

pub(crate) fn scan_backwards_whitespace(json: &[u8], mut pos: usize) -> usize {
    while pos > 0 {
        match json[pos - 1] {
            b' ' | b'\t' | b'\n' | b'\r' => pos -= 1,
            _ => break,
        }
    }
    pos
}

/// Skips a JSON value (primitive, string, array, or object) starting at `pos`.
/// Returns the index immediately following the value.
pub(crate) fn skip_value(json: &[u8], mut pos: usize) -> Result<usize, Error> {
    pos = skip_whitespace(json, pos);
    if pos >= json.len() {
        return Err(Error::InvalidJsonSyntax {
            pos,
            msg: "Unexpected EOF",
        });
    }

    match json[pos] {
        b'"' => {
            let end = find_string_end(json, pos + 1)?;
            Ok(end + 1)
        }
        b'{' => {
            // Scan and balance curly braces, taking string escapes into account
            let mut depth = 1;
            pos += 1;
            while depth > 0 && pos < json.len() {
                match json[pos] {
                    b'"' => {
                        pos = find_string_end(json, pos + 1)? + 1;
                    }
                    b'{' => {
                        depth += 1;
                        pos += 1;
                    }
                    b'}' => {
                        depth -= 1;
                        pos += 1;
                    }
                    _ => pos += 1,
                }
            }
            if depth == 0 {
                Ok(pos)
            } else {
                Err(Error::InvalidJsonSyntax {
                    pos,
                    msg: "Unclosed object brace '}'",
                })
            }
        }
        b'[' => {
            // Scan and balance square brackets
            let mut depth = 1;
            pos += 1;
            while depth > 0 && pos < json.len() {
                match json[pos] {
                    b'"' => {
                        pos = find_string_end(json, pos + 1)? + 1;
                    }
                    b'[' => {
                        depth += 1;
                        pos += 1;
                    }
                    b']' => {
                        depth -= 1;
                        pos += 1;
                    }
                    _ => pos += 1,
                }
            }
            if depth == 0 {
                Ok(pos)
            } else {
                Err(Error::InvalidJsonSyntax {
                    pos,
                    msg: "Unclosed array bracket ']'",
                })
            }
        }
        _ => {
            // Primitive (number, true, false, null)
            // Stop at structural JSON characters or whitespace.
            let start = pos;
            while pos < json.len() {
                match json[pos] {
                    b' ' | b'\t' | b'\n' | b'\r' | b',' | b'}' | b']' => break,
                    _ => pos += 1,
                }
            }
            // Empty primitive (e.g. value starts with `,` or `}`) is invalid.
            if pos == start {
                return Err(Error::InvalidJsonSyntax {
                    pos: start,
                    msg: "Expected JSON value",
                });
            }
            Ok(pos)
        }
    }
}

/// Finds the end of a JSON string starting *after* the opening double-quote.
/// Returns the index of the closing double-quote.
pub(crate) fn find_string_end(json: &[u8], mut pos: usize) -> Result<usize, Error> {
    while pos < json.len() {
        // Fast scan for next quote
        if let Some(next_pos) = memchr(b'"', &json[pos..]) {
            let found_idx = pos + next_pos;
            // Quote is escaped iff an odd number of consecutive backslashes precede it.
            let mut backslashes = 0usize;
            let mut check = found_idx;
            while check > 0 && json[check - 1] == b'\\' {
                backslashes += 1;
                check -= 1;
            }
            if backslashes % 2 == 0 {
                return Ok(found_idx); // unescaped quote
            }
            pos = found_idx + 1; // escaped quote, keep scanning
        } else {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unclosed string literal",
            });
        }
    }
    Err(Error::InvalidJsonSyntax {
        pos,
        msg: "Unclosed string literal",
    })
}

/// Read `json[pos]` or return a syntax error (no panic on empty / short buffers).
#[inline]
pub(crate) fn byte_at(json: &[u8], pos: usize) -> Result<u8, Error> {
    json.get(pos).copied().ok_or(Error::InvalidJsonSyntax {
        pos,
        msg: "Unexpected EOF",
    })
}

/// Skips whitespace characters starting at `pos`.
#[inline(always)]
pub(crate) fn skip_whitespace(json: &[u8], mut pos: usize) -> usize {
    while pos < json.len() {
        match json[pos] {
            b' ' | b'\t' | b'\n' | b'\r' => pos += 1,
            _ => break,
        }
    }
    pos
}