diffx-core 0.7.1

Core library for diffx - blazing fast semantic diff engine for structured data. Zero-copy parsing, streaming support, memory-efficient algorithms
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
use diffx_core::*;
use regex::Regex;
use serde_json::{json, Value};

// ============================================================================
// UNIFIED API TESTS - Core Functionality
// ============================================================================

#[test]
fn test_diff_basic_modification() {
    let old = json!({"name": "Alice", "age": 30});
    let new = json!({"name": "Alice", "age": 31});

    let results = diff(&old, &new, None).unwrap();

    assert_eq!(results.len(), 1);
    match &results[0] {
        DiffResult::Modified(path, old_val, new_val) => {
            assert_eq!(path, "age");
            assert_eq!(old_val, &json!(30));
            assert_eq!(new_val, &json!(31));
        }
        _ => panic!("Expected Modified result"),
    }
}

#[test]
fn test_diff_added_field() {
    let old = json!({"name": "Alice"});
    let new = json!({"name": "Alice", "age": 30});

    let results = diff(&old, &new, None).unwrap();

    assert_eq!(results.len(), 1);
    match &results[0] {
        DiffResult::Added(path, value) => {
            assert_eq!(path, "age");
            assert_eq!(value, &json!(30));
        }
        _ => panic!("Expected Added result"),
    }
}

#[test]
fn test_diff_removed_field() {
    let old = json!({"name": "Alice", "age": 30});
    let new = json!({"name": "Alice"});

    let results = diff(&old, &new, None).unwrap();

    assert_eq!(results.len(), 1);
    match &results[0] {
        DiffResult::Removed(path, value) => {
            assert_eq!(path, "age");
            assert_eq!(value, &json!(30));
        }
        _ => panic!("Expected Removed result"),
    }
}

#[test]
fn test_diff_type_changed() {
    let old = json!({"value": 123});
    let new = json!({"value": "123"});

    let results = diff(&old, &new, None).unwrap();

    assert_eq!(results.len(), 1);
    match &results[0] {
        DiffResult::TypeChanged(path, old_val, new_val) => {
            assert_eq!(path, "value");
            assert_eq!(old_val, &json!(123));
            assert_eq!(new_val, &json!("123"));
        }
        _ => panic!("Expected TypeChanged result"),
    }
}

#[test]
fn test_diff_no_changes() {
    let old = json!({"name": "Alice", "age": 30});
    let new = json!({"name": "Alice", "age": 30});

    let results = diff(&old, &new, None).unwrap();

    assert_eq!(results.len(), 0);
}

// ============================================================================
// OPTIONS TESTING - All Options Coverage
// ============================================================================

#[test]
fn test_diff_with_epsilon() {
    let old = json!({"value": 1.0});
    let new = json!({"value": 1.001});

    let options = DiffOptions {
        epsilon: Some(0.01),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();
    assert_eq!(results.len(), 0); // Within epsilon

    let options = DiffOptions {
        epsilon: Some(0.0001),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();
    assert_eq!(results.len(), 1); // Outside epsilon
}

#[test]
fn test_diff_with_array_id_key() {
    let old = json!({
        "users": [
            {"id": 1, "name": "Alice"},
            {"id": 2, "name": "Bob"}
        ]
    });
    let new = json!({
        "users": [
            {"id": 2, "name": "Bob"},
            {"id": 1, "name": "Alice Updated"}
        ]
    });

    let options = DiffOptions {
        array_id_key: Some("id".to_string()),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();

    // Should detect modification of Alice's name, not array reordering
    assert_eq!(results.len(), 1);
    match &results[0] {
        DiffResult::Modified(path, _, new_val) => {
            assert!(path.contains("[id=1]"));
            assert!(path.contains("name"));
            assert_eq!(new_val, &json!("Alice Updated"));
        }
        _ => panic!("Expected Modified result"),
    }
}

#[test]
fn test_diff_with_ignore_keys_regex() {
    let old = json!({
        "data": "important",
        "timestamp": "2023-01-01",
        "debug_info": "old"
    });
    let new = json!({
        "data": "important",
        "timestamp": "2023-01-02",
        "debug_info": "new"
    });

    let regex = Regex::new(r"^(timestamp|debug_)").unwrap();
    let options = DiffOptions {
        ignore_keys_regex: Some(regex),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();
    assert_eq!(results.len(), 0); // All changes ignored
}

#[test]
fn test_diff_with_path_filter() {
    let old = json!({
        "config": {"value": 1},
        "metadata": {"value": 2}
    });
    let new = json!({
        "config": {"value": 10},
        "metadata": {"value": 20}
    });

    let options = DiffOptions {
        path_filter: Some("config".to_string()),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();
    assert_eq!(results.len(), 1);

    match &results[0] {
        DiffResult::Modified(path, _, _) => {
            assert!(path.contains("config"));
        }
        _ => panic!("Expected Modified result"),
    }
}

#[test]
fn test_diff_with_output_format() {
    let old = json!({"name": "Alice"});
    let new = json!({"name": "Bob"});

    // Test all output formats
    for format in OutputFormat::value_variants() {
        let options = DiffOptions {
            output_format: Some(*format),
            ..Default::default()
        };

        let results = diff(&old, &new, Some(&options)).unwrap();
        assert_eq!(results.len(), 1);

        // Test formatting
        let formatted = format_output(&results, *format).unwrap();
        assert!(!formatted.is_empty());
    }
}

#[test]
fn test_diff_with_diffx_specific_options() {
    let old = json!({"text": "Hello World"});
    let new = json!({"text": "HELLO WORLD"});

    let diffx_options = DiffxSpecificOptions {
        ignore_case: Some(true),
        ignore_whitespace: Some(false),
        ..Default::default()
    };

    let options = DiffOptions {
        diffx_options: Some(diffx_options),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();
    assert_eq!(results.len(), 0); // Ignored due to case insensitive
}

#[test]
fn test_diff_with_ignore_whitespace() {
    let old = json!({"text": "Hello World"});
    let new = json!({"text": "HelloWorld"});

    let diffx_options = DiffxSpecificOptions {
        ignore_whitespace: Some(true),
        ..Default::default()
    };

    let options = DiffOptions {
        diffx_options: Some(diffx_options),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();
    assert_eq!(results.len(), 0); // Ignored due to whitespace
}

// ============================================================================
// ARRAY HANDLING TESTS
// ============================================================================

#[test]
fn test_diff_arrays_by_index() {
    let old = json!([1, 2, 3]);
    let new = json!([1, 3, 4]);

    let results = diff(&old, &new, None).unwrap();

    assert_eq!(results.len(), 2);
    // Should detect changes at indices 1 and 2
}

#[test]
fn test_diff_arrays_with_id_key() {
    let old = json!([
        {"id": "a", "value": 1},
        {"id": "b", "value": 2}
    ]);
    let new = json!([
        {"id": "b", "value": 20},
        {"id": "c", "value": 3}
    ]);

    let options = DiffOptions {
        array_id_key: Some("id".to_string()),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();

    // Should detect: removed 'a', modified 'b', added 'c'
    assert_eq!(results.len(), 3);
}

#[test]
fn test_diff_arrays_mixed_id_and_index() {
    let old = json!([
        {"id": "a", "value": 1},
        {"value": 2}, // No ID
        {"id": "b", "value": 3}
    ]);
    let new = json!([
        {"id": "b", "value": 30},
        {"value": 20}, // No ID
        {"id": "c", "value": 4}
    ]);

    let options = DiffOptions {
        array_id_key: Some("id".to_string()),
        ..Default::default()
    };

    let results = diff(&old, &new, Some(&options)).unwrap();

    // Should handle both ID-based and index-based comparisons
    assert!(!results.is_empty());
}

// ============================================================================
// COMPLEX DATA STRUCTURES
// ============================================================================

#[test]
fn test_diff_nested_objects() {
    let old = json!({
        "user": {
            "profile": {
                "name": "Alice",
                "settings": {
                    "theme": "dark"
                }
            }
        }
    });
    let new = json!({
        "user": {
            "profile": {
                "name": "Alice",
                "settings": {
                    "theme": "light",
                    "notifications": true
                }
            }
        }
    });

    let results = diff(&old, &new, None).unwrap();

    assert_eq!(results.len(), 2);
    // Should find theme change and notifications addition
}

#[test]
fn test_diff_large_dataset() {
    let mut old_data = serde_json::Map::new();
    let mut new_data = serde_json::Map::new();

    // Create large dataset
    for i in 0..1000 {
        old_data.insert(format!("key_{i}"), json!(i));
        new_data.insert(format!("key_{i}"), json!(i + 1));
    }

    let old = Value::Object(old_data);
    let new = Value::Object(new_data);

    let results = diff(&old, &new, None).unwrap();
    assert_eq!(results.len(), 1000);
}

// ============================================================================
// OUTPUT FORMAT TESTS
// ============================================================================

#[test]
fn test_output_format_parsing() {
    assert_eq!(
        OutputFormat::parse_format("json").unwrap(),
        OutputFormat::Json
    );
    assert_eq!(
        OutputFormat::parse_format("yaml").unwrap(),
        OutputFormat::Yaml
    );
    assert_eq!(
        OutputFormat::parse_format("yml").unwrap(),
        OutputFormat::Yaml
    );
    assert_eq!(
        OutputFormat::parse_format("diffx").unwrap(),
        OutputFormat::Diffx
    );

    assert!(OutputFormat::parse_format("invalid").is_err());
}

#[test]
fn test_all_output_formats() {
    let results = vec![DiffResult::Added("test".to_string(), json!("value"))];

    for format in OutputFormat::value_variants() {
        let output = format_output(&results, *format).unwrap();
        assert!(!output.is_empty());

        match format {
            OutputFormat::Json => assert!(output.contains("{")),
            OutputFormat::Yaml => assert!(output.contains("Added")),
            OutputFormat::Diffx => assert!(output.contains("Added")),
        }
    }
}

// ============================================================================
// PARSER FUNCTION TESTS (Internal Use)
// ============================================================================

#[test]
fn test_parse_json() {
    let content = r#"{"name": "test", "value": 123}"#;
    let result = parse_json(content).unwrap();

    assert_eq!(result["name"], json!("test"));
    assert_eq!(result["value"], json!(123));
}

#[test]
fn test_parse_csv() {
    let content = "name,age\nAlice,30\nBob,25";
    let result = parse_csv(content).unwrap();

    if let Value::Array(records) = result {
        assert_eq!(records.len(), 2);
        assert_eq!(records[0]["name"], json!("Alice"));
        assert_eq!(records[0]["age"], json!("30"));
    } else {
        panic!("Expected array result");
    }
}

#[test]
fn test_parse_yaml() {
    let content = "name: test\nvalue: 123";
    let result = parse_yaml(content).unwrap();

    assert_eq!(result["name"], json!("test"));
    assert_eq!(result["value"], json!(123));
}

#[test]
fn test_parse_invalid_json() {
    let content = "invalid json {";
    let result = parse_json(content);
    assert!(result.is_err());
}

// ============================================================================
// UTILITY FUNCTION TESTS (Internal Use)
// ============================================================================

#[test]
fn test_value_type_name() {
    assert_eq!(value_type_name(&json!(null)), "Null");
    assert_eq!(value_type_name(&json!(true)), "Boolean");
    assert_eq!(value_type_name(&json!(123)), "Number");
    assert_eq!(value_type_name(&json!("test")), "String");
    assert_eq!(value_type_name(&json!([])), "Array");
    assert_eq!(value_type_name(&json!({})), "Object");
}

// ============================================================================
// LIGHTWEIGHT DIFF RESULT TESTS
// ============================================================================

#[test]
fn test_lightweight_diff_result_conversion() {
    let result = DiffResult::Added("test".to_string(), json!({"key": "value"}));
    let lightweight = LightweightDiffResult::from(&result);

    match lightweight {
        LightweightDiffResult::Added(path, value_str) => {
            assert_eq!(path, "test");
            assert!(value_str.contains("key"));
            assert!(value_str.contains("value"));
        }
        _ => panic!("Expected Added result"),
    }
}