succinctly 0.7.0

High-performance succinct data structures for Rust
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Integration tests for the succinctly json validate CLI command
//!
//! These tests verify RFC 8259 compliance and CLI behavior.
//! Run with: cargo test --features cli --test json_validate_tests

use std::io::Write;
use std::process::{Command, Stdio};
use std::time::Duration;

use anyhow::Result;
use tempfile::NamedTempFile;

/// Maximum retries for cargo run commands that fail with exit code 101.
/// This handles flaky failures from cargo lock contention when tests run in parallel.
const MAX_CARGO_RETRIES: u32 = 3;

/// Helper to run json validate command with input from stdin
fn run_validate_stdin(input: &str, extra_args: &[&str]) -> Result<(String, String, i32)> {
    for attempt in 0..MAX_CARGO_RETRIES {
        let mut cmd = Command::new("cargo")
            .args([
                "run",
                "--features",
                "cli",
                "--bin",
                "succinctly",
                "--",
                "json",
                "validate",
            ])
            .args(extra_args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;

        if let Some(mut stdin) = cmd.stdin.take() {
            stdin.write_all(input.as_bytes())?;
        }

        let output = cmd.wait_with_output()?;
        let exit_code = output.status.code().unwrap_or(-1);

        // Exit code 101 often indicates cargo lock contention; retry
        if exit_code == 101 && attempt + 1 < MAX_CARGO_RETRIES {
            std::thread::sleep(Duration::from_millis(100 * (attempt as u64 + 1)));
            continue;
        }

        let stdout = String::from_utf8(output.stdout)?;
        let stderr = String::from_utf8(output.stderr)?;
        return Ok((stdout, stderr, exit_code));
    }
    unreachable!()
}

/// Helper to run json validate command with file input
fn run_validate_file(file_path: &str, extra_args: &[&str]) -> Result<(String, String, i32)> {
    for attempt in 0..MAX_CARGO_RETRIES {
        let output = Command::new("cargo")
            .args([
                "run",
                "--features",
                "cli",
                "--bin",
                "succinctly",
                "--",
                "json",
                "validate",
            ])
            .args(extra_args)
            .arg(file_path)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()?;

        let exit_code = output.status.code().unwrap_or(-1);

        // Exit code 101 often indicates cargo lock contention; retry
        if exit_code == 101 && attempt + 1 < MAX_CARGO_RETRIES {
            std::thread::sleep(Duration::from_millis(100 * (attempt as u64 + 1)));
            continue;
        }

        let stdout = String::from_utf8(output.stdout)?;
        let stderr = String::from_utf8(output.stderr)?;
        return Ok((stdout, stderr, exit_code));
    }
    unreachable!()
}

// ============================================================================
// Exit code tests
// ============================================================================

#[test]
fn test_valid_json_exit_code_0() -> Result<()> {
    let (stdout, stderr, exit_code) = run_validate_stdin(r#"{"key": "value"}"#, &[])?;
    assert_eq!(exit_code, 0, "stdout: {}, stderr: {}", stdout, stderr);
    assert!(stdout.is_empty(), "stdout should be empty for valid JSON");
    Ok(())
}

#[test]
fn test_invalid_json_exit_code_1() -> Result<()> {
    let (_, _, exit_code) = run_validate_stdin(r#"{"key": }"#, &[])?;
    assert_eq!(exit_code, 1);
    Ok(())
}

/// Strip ANSI escape codes from a string.
fn strip_ansi_codes(s: &str) -> String {
    // ANSI escape sequences: ESC [ ... m (where ... is digits and semicolons)
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '\x1b' {
            // Consume the escape sequence
            if chars.peek() == Some(&'[') {
                chars.next(); // consume '['
                              // Consume until 'm' or end
                while let Some(&c) = chars.peek() {
                    chars.next();
                    if c == 'm' {
                        break;
                    }
                }
            }
        } else {
            result.push(ch);
        }
    }
    result
}

#[test]
fn test_quiet_mode_no_output() -> Result<()> {
    let (stdout, stderr, exit_code) = run_validate_stdin(r#"{"invalid": }"#, &["--quiet"])?;
    assert_eq!(exit_code, 1);
    assert!(stdout.is_empty(), "stdout should be empty in quiet mode");
    // Filter out cargo compilation output (lines starting with "Compiling", "Finished", etc.)
    // Note: cargo may output ANSI color codes, so we strip them before checking prefixes
    let app_stderr: String = stderr
        .lines()
        .filter(|line| {
            let stripped = strip_ansi_codes(line);
            let trimmed = stripped.trim();
            !trimmed.starts_with("Compiling")
                && !trimmed.starts_with("Finished")
                && !trimmed.starts_with("Running")
                && !trimmed.starts_with("Blocking")
                && !trimmed.starts_with("warning:")
                && !trimmed.starts_with("Downloading")
                && !trimmed.starts_with("Downloaded")
        })
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        app_stderr.is_empty(),
        "stderr should be empty in quiet mode, got: {}",
        app_stderr
    );
    Ok(())
}

// ============================================================================
// Valid JSON acceptance tests
// ============================================================================

#[test]
fn test_valid_empty_object() -> Result<()> {
    let (_, _, exit_code) = run_validate_stdin("{}", &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

#[test]
fn test_valid_empty_array() -> Result<()> {
    let (_, _, exit_code) = run_validate_stdin("[]", &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

#[test]
fn test_valid_null() -> Result<()> {
    let (_, _, exit_code) = run_validate_stdin("null", &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

#[test]
fn test_valid_true() -> Result<()> {
    let (_, _, exit_code) = run_validate_stdin("true", &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

#[test]
fn test_valid_false() -> Result<()> {
    let (_, _, exit_code) = run_validate_stdin("false", &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

#[test]
fn test_valid_nested_structure() -> Result<()> {
    let json =
        r#"{"users": [{"name": "Alice", "active": true}, {"name": "Bob", "active": false}]}"#;
    let (_, _, exit_code) = run_validate_stdin(json, &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

#[test]
fn test_valid_string_escapes() -> Result<()> {
    let json = r#"{"escapes": "quote\" backslash\\ slash\/ newline\n tab\t"}"#;
    let (_, _, exit_code) = run_validate_stdin(json, &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

#[test]
fn test_valid_unicode_escape() -> Result<()> {
    let json = r#"{"unicode": "\u0041\u0042\u0043"}"#;
    let (_, _, exit_code) = run_validate_stdin(json, &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

#[test]
fn test_valid_surrogate_pair() -> Result<()> {
    // U+1F600 (grinning face emoji) as surrogate pair
    let json = r#"{"emoji": "\uD83D\uDE00"}"#;
    let (_, _, exit_code) = run_validate_stdin(json, &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

#[test]
fn test_valid_numbers() -> Result<()> {
    let json = r#"{"int": 42, "neg": -17, "float": 3.14, "exp": 1e10, "neg_exp": 2.5e-3}"#;
    let (_, _, exit_code) = run_validate_stdin(json, &[])?;
    assert_eq!(exit_code, 0);
    Ok(())
}

// ============================================================================
// Invalid JSON rejection tests
// ============================================================================

#[test]
fn test_invalid_trailing_comma_object() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_stdin(r#"{"key": "value",}"#, &["--no-color"])?;
    assert_eq!(exit_code, 1);
    assert!(stderr.contains("error:"));
    Ok(())
}

#[test]
fn test_invalid_trailing_comma_array() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_stdin("[1, 2, 3,]", &["--no-color"])?;
    assert_eq!(exit_code, 1);
    assert!(stderr.contains("error:"));
    Ok(())
}

#[test]
fn test_invalid_leading_zero() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_stdin(r#"{"count": 007}"#, &["--no-color"])?;
    assert_eq!(exit_code, 1);
    assert!(stderr.contains("leading zero"));
    Ok(())
}

#[test]
fn test_invalid_leading_plus() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_stdin("+42", &["--no-color"])?;
    assert_eq!(exit_code, 1);
    assert!(stderr.contains("leading plus"));
    Ok(())
}

#[test]
fn test_invalid_escape_sequence() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_stdin(r#"{"msg": "hello\qworld"}"#, &["--no-color"])?;
    assert_eq!(exit_code, 1);
    assert!(stderr.contains("escape"));
    Ok(())
}

#[test]
fn test_invalid_control_character() -> Result<()> {
    // Tab character directly in string (should be escaped as \t)
    let (_, stderr, exit_code) =
        run_validate_stdin("{\"msg\": \"hello\tworld\"}", &["--no-color"])?;
    // Note: tab is valid whitespace in JSON strings per spec, so this should pass
    // Let me check - actually raw tab in a string requires escaping per RFC 8259
    // "All Unicode characters may be placed within the quotation marks, except for
    // the characters that MUST be escaped: quotation mark, reverse solidus, and
    // the control characters (U+0000 through U+001F)."
    // Tab is U+0009, so it must be escaped.
    assert_eq!(exit_code, 1);
    assert!(stderr.contains("control character"));
    Ok(())
}

#[test]
fn test_invalid_lone_surrogate() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_stdin(r#"{"bad": "\uD83D"}"#, &["--no-color"])?;
    assert_eq!(exit_code, 1);
    assert!(stderr.contains("surrogate"));
    Ok(())
}

#[test]
fn test_invalid_unclosed_string() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_stdin(r#"{"key": "unclosed"#, &["--no-color"])?;
    assert_eq!(exit_code, 1);
    assert!(stderr.contains("unclosed") || stderr.contains("end of input"));
    Ok(())
}

#[test]
fn test_invalid_trailing_content() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_stdin("null extra", &["--no-color"])?;
    assert_eq!(exit_code, 1);
    assert!(stderr.contains("trailing"));
    Ok(())
}

// ============================================================================
// Error position accuracy tests
// ============================================================================

#[test]
fn test_error_position_line_column() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_stdin(r#"{"key": "value",}"#, &["--no-color"])?;
    assert_eq!(exit_code, 1);
    // Error should be at column 17 (the closing brace after the comma)
    assert!(stderr.contains(":1:17") || stderr.contains("column 17"));
    Ok(())
}

#[test]
fn test_error_position_multiline() -> Result<()> {
    let json = "{\n  \"key\": \"value\",\n}";
    let (_, stderr, exit_code) = run_validate_stdin(json, &["--no-color"])?;
    assert_eq!(exit_code, 1);
    // Error should be on line 3
    assert!(stderr.contains(":3:") || stderr.contains("line 3"));
    Ok(())
}

// ============================================================================
// File input tests
// ============================================================================

#[test]
fn test_file_input_valid() -> Result<()> {
    let mut file = NamedTempFile::new()?;
    writeln!(file, r#"{{"name": "Alice"}}"#)?;
    file.flush()?;

    let (stdout, stderr, exit_code) = run_validate_file(file.path().to_str().unwrap(), &[])?;
    assert_eq!(exit_code, 0, "stdout: {}, stderr: {}", stdout, stderr);
    Ok(())
}

#[test]
fn test_file_input_invalid() -> Result<()> {
    let mut file = NamedTempFile::new()?;
    writeln!(file, r#"{{"name": "Alice",}}"#)?;
    file.flush()?;

    let (_, stderr, exit_code) = run_validate_file(file.path().to_str().unwrap(), &["--no-color"])?;
    assert_eq!(exit_code, 1);
    // Error should include the filename
    assert!(stderr.contains(file.path().file_name().unwrap().to_str().unwrap()));
    Ok(())
}

#[test]
fn test_file_not_found() -> Result<()> {
    let (_, stderr, exit_code) = run_validate_file("/nonexistent/path.json", &["--no-color"])?;
    assert_eq!(exit_code, 2); // I/O error
    assert!(stderr.contains("error:"));
    Ok(())
}

// ============================================================================
// Multiple files tests
// ============================================================================

#[test]
fn test_multiple_files_all_valid() -> Result<()> {
    let mut file1 = NamedTempFile::new()?;
    writeln!(file1, r#"{{"a": 1}}"#)?;
    file1.flush()?;

    let mut file2 = NamedTempFile::new()?;
    writeln!(file2, r#"{{"b": 2}}"#)?;
    file2.flush()?;

    let output = Command::new("cargo")
        .args([
            "run",
            "--features",
            "cli",
            "--bin",
            "succinctly",
            "--",
            "json",
            "validate",
        ])
        .arg(file1.path())
        .arg(file2.path())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()?;

    assert_eq!(output.status.code().unwrap_or(-1), 0);
    Ok(())
}

#[test]
fn test_multiple_files_one_invalid() -> Result<()> {
    let mut file1 = NamedTempFile::new()?;
    writeln!(file1, r#"{{"a": 1}}"#)?;
    file1.flush()?;

    let mut file2 = NamedTempFile::new()?;
    writeln!(file2, r#"{{"b": }}"#)?; // invalid
    file2.flush()?;

    let output = Command::new("cargo")
        .args([
            "run",
            "--features",
            "cli",
            "--bin",
            "succinctly",
            "--",
            "json",
            "validate",
        ])
        .arg(file1.path())
        .arg(file2.path())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()?;

    assert_eq!(output.status.code().unwrap_or(-1), 1);
    Ok(())
}

// ============================================================================
// Line number alignment tests
// ============================================================================

/// Helper to verify pipe alignment in error output.
/// Returns the column position of the '|' character on each line, or None if not found.
fn find_pipe_columns(stderr: &str) -> Vec<usize> {
    stderr.lines().filter_map(|line| line.find('|')).collect()
}

/// Creates a JSON object with an error at a specific line number.
/// The JSON structure is an array with one element per line (each on its own line).
fn create_json_with_error_at_line(target_line: usize) -> String {
    let mut json = String::new();
    json.push_str("[\n"); // Line 1

    // Add valid elements up to target_line - 1
    // Line 2 through target_line-1 have valid elements
    for i in 2..target_line {
        if i == target_line - 1 {
            // Last valid line before error - no trailing comma needed since error line follows
            json.push_str(&format!("  {}\n", i - 1));
        } else {
            json.push_str(&format!("  {},\n", i - 1));
        }
    }

    // Add invalid element at target_line (missing value after colon)
    json.push_str("  {\"bad\": }\n"); // This is the error line
    json.push_str("]\n");

    json
}

#[test]
fn test_alignment_single_digit_line() -> Result<()> {
    // Create JSON with error on line 9 (single digit)
    let json = create_json_with_error_at_line(9);

    let (_, stderr, exit_code) = run_validate_stdin(&json, &["--no-color"])?;
    assert_eq!(exit_code, 1);

    // Verify the error is on line 9
    assert!(
        stderr.contains(":9:"),
        "Error should be on line 9, got:\n{}",
        stderr
    );

    // Verify pipe alignment: all '|' should be at the same column
    let pipe_cols = find_pipe_columns(&stderr);
    assert!(
        pipe_cols.len() >= 2,
        "Should have at least 2 lines with pipes"
    );
    let first_col = pipe_cols[0];
    for col in &pipe_cols {
        assert_eq!(
            *col, first_col,
            "All pipes should be at the same column, got {:?}",
            pipe_cols
        );
    }
    Ok(())
}

#[test]
fn test_alignment_double_digit_line() -> Result<()> {
    // Create JSON with error on line 10 (double digit - transition point)
    let json = create_json_with_error_at_line(10);

    let (_, stderr, exit_code) = run_validate_stdin(&json, &["--no-color"])?;
    assert_eq!(exit_code, 1);

    // Verify the error is on line 10
    assert!(
        stderr.contains(":10:"),
        "Error should be on line 10, got:\n{}",
        stderr
    );

    // Verify pipe alignment
    let pipe_cols = find_pipe_columns(&stderr);
    assert!(
        pipe_cols.len() >= 2,
        "Should have at least 2 lines with pipes"
    );
    let first_col = pipe_cols[0];
    for col in &pipe_cols {
        assert_eq!(
            *col, first_col,
            "All pipes should be at the same column, got {:?}",
            pipe_cols
        );
    }
    Ok(())
}

#[test]
fn test_alignment_triple_digit_line() -> Result<()> {
    // Create JSON with error on line 999 (triple digit)
    let json = create_json_with_error_at_line(999);

    let (_, stderr, exit_code) = run_validate_stdin(&json, &["--no-color"])?;
    assert_eq!(exit_code, 1);

    // Verify the error is on line 999
    assert!(
        stderr.contains(":999:"),
        "Error should be on line 999, got:\n{}",
        stderr
    );

    // Verify pipe alignment
    let pipe_cols = find_pipe_columns(&stderr);
    assert!(
        pipe_cols.len() >= 2,
        "Should have at least 2 lines with pipes"
    );
    let first_col = pipe_cols[0];
    for col in &pipe_cols {
        assert_eq!(
            *col, first_col,
            "All pipes should be at the same column, got {:?}",
            pipe_cols
        );
    }
    Ok(())
}

#[test]
fn test_alignment_four_digit_line() -> Result<()> {
    // Create JSON with error on line 1000 (four digit - transition point)
    let json = create_json_with_error_at_line(1000);

    let (_, stderr, exit_code) = run_validate_stdin(&json, &["--no-color"])?;
    assert_eq!(exit_code, 1);

    // Verify the error is on line 1000
    assert!(
        stderr.contains(":1000:"),
        "Error should be on line 1000, got:\n{}",
        stderr
    );

    // Verify pipe alignment
    let pipe_cols = find_pipe_columns(&stderr);
    assert!(
        pipe_cols.len() >= 2,
        "Should have at least 2 lines with pipes"
    );
    let first_col = pipe_cols[0];
    for col in &pipe_cols {
        assert_eq!(
            *col, first_col,
            "All pipes should be at the same column, got {:?}",
            pipe_cols
        );
    }
    Ok(())
}