rjd 1.2.1

Compare two JSON files or inline JSON strings and output the differences
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Type-safe JSON path representation and manipulation
//!
//! This module provides a structured way to work with JSON paths in dot notation,
//! with compile-time type safety and clear error messages.
//!
//! # Format
//!
//! Paths use dot notation with bracket-based array indexing:
//! - Root property: `"name"`
//! - Nested property: `"user.profile.email"`
//! - Array index: `"items[0]"`
//! - Combined: `"users[0].email"`
//!
//! # Example
//!
//! ```rust
//! use rjd::json_path::{JsonPath, PathSegment};
//! use std::str::FromStr;
//!
//! // Parse a path
//! let path = JsonPath::from_str("users[0].email").unwrap();
//! assert_eq!(path.to_string(), "users[0].email");
//!
//! // Convert to JSON Pointer (RFC 6901)
//! assert_eq!(path.to_json_pointer(), "/users/0/email");
//! ```

use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::FromStr;

/// A single segment in a JSON path
///
/// Represents either an object property key or an array index.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathSegment {
    /// Object property key (e.g., "user" in "user.name")
    Key(String),
    /// Array index (e.g., 0 in "items\[0\]")
    Index(usize),
}

impl Hash for PathSegment {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            PathSegment::Key(s) => {
                state.write_u8(0);
                s.hash(state);
            }
            PathSegment::Index(i) => {
                state.write_u8(1);
                i.hash(state);
            }
        }
    }
}

/// A type-safe JSON path
///
/// Represents a path to a location in a JSON value using dot notation.
/// Paths are composed of segments that can be either object keys or array indices.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct JsonPath {
    /// The segments that make up this path
    segments: Vec<PathSegment>,
}

impl JsonPath {
    /// Create a new empty JsonPath representing the root
    ///
    /// An empty path (with no segments) represents the root of a JSON value.
    /// This is used when the entire JSON value is replaced, or when working
    /// with root-level changes.
    ///
    /// # Examples
    ///
    /// ```
    /// use rjd::JsonPath;
    ///
    /// // Root path (no segments)
    /// let root = JsonPath::new();
    /// assert_eq!(root.to_string(), "");
    /// assert!(root.is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            segments: Vec::new(),
        }
    }

    /// Create a JsonPath from a vector of segments
    pub fn from_segments(segments: Vec<PathSegment>) -> Self {
        Self { segments }
    }

    /// Get the segments of this path
    pub fn segments(&self) -> &[PathSegment] {
        &self.segments
    }

    /// Check if this path is empty
    pub fn is_empty(&self) -> bool {
        self.segments.is_empty()
    }

    /// Get the number of segments in this path
    pub fn len(&self) -> usize {
        self.segments.len()
    }

    /// Add a segment to this path
    pub fn push(&mut self, segment: PathSegment) {
        self.segments.push(segment);
    }

    /// Get the parent path (all segments except the last)
    pub fn parent(&self) -> Option<Self> {
        if self.segments.len() <= 1 {
            None
        } else {
            Some(Self {
                segments: self.segments[..self.segments.len() - 1].to_vec(),
            })
        }
    }

    /// Check if this path starts with the given prefix
    pub fn matches_prefix(&self, prefix: &JsonPath) -> bool {
        if prefix.segments.len() > self.segments.len() {
            return false;
        }
        self.segments
            .iter()
            .zip(prefix.segments.iter())
            .all(|(a, b)| a == b)
    }

    /// Get the first n segments as a new JsonPath
    pub fn prefix(&self, n: usize) -> Option<Self> {
        if n == 0 || n > self.segments.len() {
            return None;
        }
        Some(Self {
            segments: self.segments[..n].to_vec(),
        })
    }

    /// Convert this path to JSON Pointer format (RFC 6901)
    ///
    /// JSON Pointer uses a slash-separated path with special encoding:
    /// - `~0` represents `~`
    /// - `~1` represents `/`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rjd::json_path::JsonPath;
    /// use std::str::FromStr;
    ///
    /// let path = JsonPath::from_str("users[0].email").unwrap();
    /// assert_eq!(path.to_json_pointer(), "/users/0/email");
    /// ```
    pub fn to_json_pointer(&self) -> String {
        if self.segments.is_empty() {
            return String::new();
        }

        let mut result = String::new();
        for segment in &self.segments {
            result.push('/');
            match segment {
                PathSegment::Key(key) => {
                    // Encode special characters per RFC 6901
                    let encoded = key.replace('~', "~0").replace('/', "~1");
                    result.push_str(&encoded);
                }
                PathSegment::Index(i) => {
                    result.push_str(&i.to_string());
                }
            }
        }
        result
    }
}

impl Default for JsonPath {
    fn default() -> Self {
        Self::new()
    }
}

/// Display implementation outputs dot notation
///
/// # Examples
///
/// ```rust
/// use rjd::json_path::JsonPath;
/// use std::str::FromStr;
///
/// let path = JsonPath::from_str("users[0].email").unwrap();
/// assert_eq!(path.to_string(), "users[0].email");
/// ```
impl fmt::Display for JsonPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, segment) in self.segments.iter().enumerate() {
            match segment {
                PathSegment::Key(key) => {
                    if i > 0 {
                        write!(f, ".")?;
                    }
                    write!(f, "{}", key)?;
                }
                PathSegment::Index(idx) => {
                    write!(f, "[{}]", idx)?;
                }
            }
        }
        Ok(())
    }
}

/// Error type for path parsing failures
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum ParseError {
    #[error("Empty path")]
    EmptyPath,

    #[error("Invalid array index at position {position}: expected digit, found '{found}'")]
    InvalidArrayIndex { position: usize, found: char },

    #[error("Unclosed bracket at position {position}")]
    UnclosedBracket { position: usize },

    #[error("Unexpected character '{0}' at position {1}")]
    UnexpectedCharacter(char, usize),
}

/// Parse dot notation to create a JsonPath
///
/// # Examples
///
/// ```rust
/// use rjd::json_path::JsonPath;
/// use std::str::FromStr;
///
/// let path = JsonPath::from_str("users[0].email").unwrap();
/// assert_eq!(path.to_string(), "users[0].email");
/// ```
impl FromStr for JsonPath {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.trim().is_empty() {
            return Ok(Self::new());
        }

        let mut segments = Vec::new();
        let mut chars = s.chars().peekable();
        let mut pos = 0;

        while let Some(ch) = chars.next() {
            match ch {
                '.' => {
                    // Dot separator - skip, next segment starts
                    pos += 1;
                }
                '[' => {
                    // Array index
                    pos += 1;
                    let mut index_str = String::new();

                    // Parse digits
                    while let Some(&c) = chars.peek() {
                        if c.is_ascii_digit() {
                            index_str.push(c);
                            chars.next();
                            pos += 1;
                        } else {
                            break;
                        }
                    }

                    if index_str.is_empty() {
                        return Err(ParseError::InvalidArrayIndex {
                            position: pos,
                            found: chars.next().unwrap_or(' '),
                        });
                    }

                    // Expect closing bracket
                    match chars.next() {
                        Some(']') => {
                            pos += 1;
                        }
                        Some(c) => {
                            return Err(ParseError::UnexpectedCharacter(c, pos));
                        }
                        None => {
                            return Err(ParseError::UnclosedBracket { position: pos });
                        }
                    }

                    let index: usize =
                        index_str
                            .parse()
                            .map_err(|_| ParseError::InvalidArrayIndex {
                                position: pos - index_str.len() - 1,
                                found: index_str.chars().next().unwrap_or(' '),
                            })?;

                    segments.push(PathSegment::Index(index));
                }
                ']' => {
                    return Err(ParseError::UnexpectedCharacter(ch, pos));
                }
                _ => {
                    // Property key
                    let mut key = String::new();
                    key.push(ch);
                    pos += 1;

                    // Consume until we hit a delimiter
                    while let Some(&c) = chars.peek() {
                        if c == '.' || c == '[' {
                            break;
                        }
                        key.push(c);
                        chars.next();
                        pos += 1;
                    }

                    if !key.is_empty() {
                        segments.push(PathSegment::Key(key));
                    }
                }
            }
        }

        if segments.is_empty() {
            return Err(ParseError::EmptyPath);
        }

        Ok(Self { segments })
    }
}

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

    #[test]
    fn test_empty_path() {
        let path = JsonPath::new();
        assert!(path.is_empty());
        assert_eq!(path.len(), 0);
        assert_eq!(path.to_string(), "");
        assert_eq!(path.to_json_pointer(), "");
    }

    #[test]
    fn test_parse_root_key() {
        let path: JsonPath = "name".parse().unwrap();
        assert_eq!(path.segments(), &[PathSegment::Key("name".to_string())]);
        assert_eq!(path.to_string(), "name");
    }

    #[test]
    fn test_parse_nested_keys() {
        let path: JsonPath = "user.profile.email".parse().unwrap();
        assert_eq!(
            path.segments(),
            &[
                PathSegment::Key("user".to_string()),
                PathSegment::Key("profile".to_string()),
                PathSegment::Key("email".to_string())
            ]
        );
        assert_eq!(path.to_string(), "user.profile.email");
    }

    #[test]
    fn test_parse_array_index() {
        let path: JsonPath = "items[0]".parse().unwrap();
        assert_eq!(
            path.segments(),
            &[PathSegment::Key("items".to_string()), PathSegment::Index(0)]
        );
        assert_eq!(path.to_string(), "items[0]");
    }

    #[test]
    fn test_parse_combined() {
        let path: JsonPath = "users[0].email".parse().unwrap();
        assert_eq!(
            path.segments(),
            &[
                PathSegment::Key("users".to_string()),
                PathSegment::Index(0),
                PathSegment::Key("email".to_string())
            ]
        );
        assert_eq!(path.to_string(), "users[0].email");
    }

    #[test]
    fn test_parse_deep_nesting() {
        let path: JsonPath = "a.b.c.d.e".parse().unwrap();
        assert_eq!(path.len(), 5);
        assert_eq!(path.to_string(), "a.b.c.d.e");
    }

    #[test]
    fn test_to_json_pointer_simple() {
        let path: JsonPath = "name".parse().unwrap();
        assert_eq!(path.to_json_pointer(), "/name");
    }

    #[test]
    fn test_to_json_pointer_nested() {
        let path: JsonPath = "user.name".parse().unwrap();
        assert_eq!(path.to_json_pointer(), "/user/name");
    }

    #[test]
    fn test_to_json_pointer_array() {
        let path: JsonPath = "users[0]".parse().unwrap();
        assert_eq!(path.to_json_pointer(), "/users/0");
    }

    #[test]
    fn test_to_json_pointer_combined() {
        let path: JsonPath = "users[0].email".parse().unwrap();
        assert_eq!(path.to_json_pointer(), "/users/0/email");
    }

    #[test]
    fn test_to_json_pointer_special_chars() {
        let path: JsonPath = "user/name".parse().unwrap();
        assert_eq!(path.to_json_pointer(), "/user~1name");

        let path: JsonPath = "user~name".parse().unwrap();
        assert_eq!(path.to_json_pointer(), "/user~0name");
    }

    #[test]
    fn test_parent() {
        let path: JsonPath = "user.profile.email".parse().unwrap();
        let parent = path.parent().unwrap();
        assert_eq!(parent.to_string(), "user.profile");

        let root: JsonPath = "name".parse().unwrap();
        assert!(root.parent().is_none());
    }

    #[test]
    fn test_matches_prefix() {
        let path: JsonPath = "user.profile.email".parse().unwrap();
        let prefix: JsonPath = "user.profile".parse().unwrap();

        assert!(path.matches_prefix(&prefix));
        assert!(!prefix.matches_prefix(&path));
    }

    #[test]
    fn test_push_segment() {
        let mut path = JsonPath::new();
        path.push(PathSegment::Key("users".to_string()));
        path.push(PathSegment::Index(0));
        path.push(PathSegment::Key("email".to_string()));

        assert_eq!(path.to_string(), "users[0].email");
    }

    #[test]
    fn test_round_trip() {
        let original = "users[0].profile.email";
        let path: JsonPath = original.parse().unwrap();
        assert_eq!(path.to_string(), original);
    }

    #[test]
    fn test_parse_empty_string() {
        let path: Result<JsonPath, _> = "".parse();
        assert!(path.is_ok());
        assert!(path.unwrap().is_empty());
    }

    #[test]
    fn test_parse_invalid_array_no_digits() {
        let path: Result<JsonPath, _> = "items[]".parse();
        assert!(path.is_err());
    }

    #[test]
    fn test_parse_unclosed_bracket() {
        let path: Result<JsonPath, _> = "items[0".parse();
        assert!(path.is_err());
    }

    #[test]
    fn test_equality() {
        let path1: JsonPath = "users[0].email".parse().unwrap();
        let path2: JsonPath = "users[0].email".parse().unwrap();
        assert_eq!(path1, path2);
    }

    #[test]
    fn test_hash() {
        use std::collections::HashSet;
        let path1: JsonPath = "users[0].email".parse().unwrap();
        let path2: JsonPath = "users[0].email".parse().unwrap();
        let path3: JsonPath = "users[1].email".parse().unwrap();

        let mut set = HashSet::new();
        set.insert(path1.clone());
        set.insert(path2);
        set.insert(path3.clone());

        assert_eq!(set.len(), 2); // path1 and path2 are the same
        assert!(set.contains(&path1));
        assert!(set.contains(&path3));
    }
}