soft-canonicalize 0.5.6

Path canonicalization that works with non-existing paths.
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! Exotic edge cases specific to Windows
//!
//! Covers rare Windows-specific edge cases discovered during comparison with:
//! - dunce crate (https://gitlab.com/kornelski/dunce)
//! - Microsoft MSDN documentation (https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file)
//!
//! See: docs/dunce_msdn_analysis.md for detailed analysis

#[cfg(windows)]
use crate::soft_canonicalize;

#[cfg(all(windows, feature = "anchored"))]
use crate::anchored_canonicalize;

/// Test superscript digit reserved names (ISO-8859-1 characters)
///
/// Microsoft MSDN states:
/// "Windows recognizes the 8-bit ISO/IEC 8859-1 superscript digits ¹, ², and ³ as digits
/// and treats them as valid parts of COM# and LPT# device names, making them reserved
/// in every directory."
///
/// Current behavior: We do NOT special-case these, allowing them to be treated as regular
/// filenames. This is a conscious decision as:
/// 1. These are extremely rare in practice
/// 2. Windows itself has inconsistent handling across different APIs
/// 3. Our primary goal is matching std::fs::canonicalize for existing paths
#[cfg(windows)]
#[test]
fn test_superscript_reserved_names_documentation() {
    use tempfile::TempDir;

    // Superscript digits: ¹ (U+00B9), ² (U+00B2), ³ (U+00B3)
    let exotic_names = [
        ("COM¹", "COM with superscript 1"),
        ("COM²", "COM with superscript 2"),
        ("COM³", "COM with superscript 3"),
        ("LPT¹", "LPT with superscript 1"),
        ("LPT²", "LPT with superscript 2"),
        ("LPT³", "LPT with superscript 3"),
    ];

    let tmp = TempDir::new().expect("create tempdir");
    let _base = soft_canonicalize(tmp.path()).expect("canonicalize tempdir");

    for (name, desc) in exotic_names {
        let path = tmp.path().join(name).join("file.txt");
        let result = soft_canonicalize(&path);

        // Document current behavior: we allow these (don't reject as reserved)
        // They're treated as regular non-existing paths
        assert!(
            result.is_ok(),
            "Currently allowing {} ({}): path = {:?}",
            desc,
            name,
            path
        );

        if let Ok(resolved) = result {
            let resolved_str = resolved.to_string_lossy();
            assert!(
                resolved_str.contains(name),
                "Path should contain exotic name {}: {}",
                name,
                resolved_str
            );
        }
    }

    // Also test with extensions (dunce pattern)
    let exotic_with_ext = ["COM¹.txt", "LPT².exe", "COM³.tar.gz"];

    for name in exotic_with_ext {
        let path = tmp.path().join(name);
        let result = soft_canonicalize(&path);
        assert!(
            result.is_ok(),
            "Currently allowing exotic name with extension: {}",
            name
        );
    }
}

/// Test UTF-16 code unit counting for long paths
///
/// Windows measures path lengths in UTF-16 code units, not bytes:
/// - Emoji 🧐 = 4 bytes UTF-8, 2 UTF-16 code units
/// - Character ® = 2 bytes UTF-8, 1 UTF-16 code unit
///
/// Our implementation uses extended-length UNC format (\\?\) which bypasses
/// the 260-character MAX_PATH limit entirely, so this is primarily verification.
#[cfg(windows)]
#[test]
fn test_long_paths_with_multibyte_characters() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    // Create path with emoji (each 🧐 is 4 bytes UTF-8, 2 UTF-16 code units)
    let emoji_component = "🧐".repeat(50); // 200 bytes UTF-8, 100 UTF-16 code units
    let emoji_path = tmp.path().join(emoji_component).join("file.txt");

    let result = soft_canonicalize(&emoji_path);
    assert!(
        result.is_ok(),
        "Extended-length format should handle emoji paths: {:?}",
        emoji_path
    );

    if let Ok(resolved) = result {
        // With dunce: May be simplified if safe; without dunce: always UNC
        #[cfg(not(feature = "dunce"))]
        {
            let resolved_str = resolved.to_string_lossy();
            assert!(
                resolved_str.starts_with(r"\\?\"),
                "Should use extended-length format for absolute result: {}",
                resolved_str
            );
        }
        #[cfg(feature = "dunce")]
        {
            // With dunce, accept either format (dunce decides based on safety)
            // Just verify it's an absolute path
            assert!(resolved.is_absolute(), "Result should be absolute");
        }
    }

    // Create path with CJK characters
    let cjk_component = "日本語".repeat(50); // Each char is 3 bytes UTF-8, 1 UTF-16 code unit
    let cjk_path = tmp.path().join(cjk_component).join("测试.txt");

    let result = soft_canonicalize(&cjk_path);
    assert!(
        result.is_ok(),
        "Extended-length format should handle CJK paths: {:?}",
        cjk_path
    );

    // Create path with mixed multibyte characters
    let mixed = format!(
        "{}_{}_{}_{}",
        "🎃".repeat(20),
        "®".repeat(30),
        "".repeat(40),
        "test"
    );
    let mixed_path = tmp.path().join(mixed).join("file.exe");

    let result = soft_canonicalize(&mixed_path);
    assert!(
        result.is_ok(),
        "Extended-length format should handle mixed multibyte chars: {:?}",
        mixed_path
    );
}

/// Test very long component names (approaching 255 character limit)
///
/// Windows has a 255-character limit per component (not total path).
/// With extended-length format, this limit is less strict, but we verify behavior.
#[cfg(windows)]
#[test]
fn test_long_component_names() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    // Test component near but under 255 characters
    let component_250 = "a".repeat(250);
    let path_250 = tmp.path().join(component_250).join("file.txt");

    let result = soft_canonicalize(path_250);
    assert!(result.is_ok(), "Should handle 250-char component");

    // Test component at exactly 255 characters
    let component_255 = "b".repeat(255);
    let path_255 = tmp.path().join(component_255).join("file.txt");

    let result = soft_canonicalize(path_255);
    assert!(result.is_ok(), "Should handle 255-char component");

    // Test component over 255 characters (behavior may vary)
    let component_300 = "c".repeat(300);
    let path_300 = tmp.path().join(component_300).join("file.txt");

    let result = soft_canonicalize(path_300);
    // Extended-length format may allow this, or filesystem may reject
    // Either way, we document behavior
    match result {
        Ok(_) => {
            // Extended-length format allowed it
        }
        Err(e) => {
            // Filesystem rejected it - this is acceptable
            assert!(
                e.kind() == std::io::ErrorKind::InvalidInput
                    || e.kind() == std::io::ErrorKind::NotFound,
                "Expected InvalidInput or NotFound, got: {:?}",
                e.kind()
            );
        }
    }
}

/// Test reserved names with various extensions (dunce pattern)
///
/// Reserved names remain reserved regardless of extension:
/// - CON.txt is reserved
/// - NUL.tar.gz is reserved
/// - PRN.anything is reserved
#[cfg(windows)]
#[test]
fn test_reserved_names_with_extensions() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    let reserved_with_ext = [
        "CON.txt",
        "PRN.exe",
        "AUX.dll",
        "NUL.tar.gz",
        "COM1.log",
        "COM9.dat",
        "LPT1.cfg",
        "LPT9.ini",
    ];

    for name in reserved_with_ext {
        let path = tmp.path().join(name);
        let result = soft_canonicalize(&path);

        // These paths should canonicalize (to non-existing path)
        // Windows will handle the reserved name semantics at access time
        assert!(
            result.is_ok(),
            "Should canonicalize reserved name with extension: {}",
            name
        );
    }
}

/// Test reserved names with trailing spaces and dots (dunce pattern)
///
/// Windows has complex rules for trailing spaces and dots:
/// - "con " (with space) is still CON
/// - "con." is still CON
/// - "con  " (multiple spaces) is still CON
/// - "con....." is still CON
/// - "con . .txt" has stem "con . " which trims to "con" -> CON
#[cfg(windows)]
#[test]
fn test_reserved_names_with_trailing_chars() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    let reserved_variants = [
        "CON ",     // trailing space
        "PRN.",     // trailing dot
        "AUX  ",    // multiple trailing spaces
        "NUL.....", // multiple trailing dots
        "COM1 .",   // space then dot
        "LPT1. ",   // dot then space
        "COM9 . ",  // space dot space
    ];

    for name in reserved_variants {
        let path = tmp.path().join(name);
        let result = soft_canonicalize(&path);

        // Should handle these (behavior depends on how Windows treats them)
        // Our job is to not crash and provide reasonable output
        assert!(
            result.is_ok() || result.is_err(),
            "Should not panic on reserved name variant: '{}'",
            name
        );
    }
}

/// Test that leading space makes names NOT reserved (dunce insight)
///
/// " CON" (with leading space) is NOT the same as "CON"
#[cfg(windows)]
#[test]
fn test_leading_space_not_reserved() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    let non_reserved = [
        " CON", // leading space
        " PRN", " AUX", " NUL", " COM1", " LPT1", "  CON", // multiple leading spaces
    ];

    for name in non_reserved {
        let path = tmp.path().join(name).join("file.txt");
        let result = soft_canonicalize(&path);

        // These should NOT be treated as reserved device names
        assert!(
            result.is_ok(),
            "Leading space should make non-reserved: '{}'",
            name
        );

        if let Ok(resolved) = result {
            let resolved_str = resolved.to_string_lossy();
            // The space should be preserved in the path
            assert!(
                resolved_str.contains(name),
                "Leading space should be preserved: expected '{}' in '{}'",
                name,
                resolved_str
            );
        }
    }
}

/// Test that dot prefix makes names NOT reserved (dunce insight)
///
/// ".CON" is NOT the same as "CON"
#[cfg(windows)]
#[test]
fn test_dot_prefix_not_reserved() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    let non_reserved = [".CON", ".PRN", ".AUX", ".NUL", ".COM1", ".LPT1"];

    for name in non_reserved {
        let path = tmp.path().join(name).join("file.txt");
        let result = soft_canonicalize(&path);

        // These should NOT be treated as reserved device names
        assert!(
            result.is_ok(),
            "Dot prefix should make non-reserved: '{}'",
            name
        );

        if let Ok(resolved) = result {
            let resolved_str = resolved.to_string_lossy();
            assert!(
                resolved_str.contains(name),
                "Dot prefix should be preserved: expected '{}' in '{}'",
                name,
                resolved_str
            );
        }
    }
}

/// Test invalid COM/LPT numbers are NOT reserved (dunce insight)
///
/// - COM0 is NOT reserved (only COM1-9)
/// - COM10, COM77, etc. are NOT reserved
/// - LPT0 is NOT reserved (only LPT1-9)
#[cfg(windows)]
#[test]
fn test_invalid_device_numbers_not_reserved() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    let non_reserved = [
        "COM0",  // 0 is not valid
        "COM10", // only 1-9 are reserved
        "COM77", "LPT0", "LPT10", "LPT99",
    ];

    for name in non_reserved {
        let path = tmp.path().join(name).join("file.txt");
        let result = soft_canonicalize(&path);

        // These should NOT be treated as reserved device names
        assert!(
            result.is_ok(),
            "Invalid device number should not be reserved: '{}'",
            name
        );

        if let Ok(resolved) = result {
            let resolved_str = resolved.to_string_lossy();
            assert!(
                resolved_str.contains(name),
                "Non-reserved name should be preserved: expected '{}' in '{}'",
                name,
                resolved_str
            );
        }
    }
}

/// Test filename component edge cases (dunce validation patterns)
#[cfg(windows)]
#[test]
fn test_filename_component_validation() {
    // Test that we handle (or reject) various problematic filenames
    let invalid_components = [
        "file<name.txt",    // < is invalid
        "file>name.txt",    // > is invalid
        "file:name.txt",    // : is invalid (except in ADS)
        "file\"name.txt",   // " is invalid
        "file|name.txt",    // | is invalid
        "file?name.txt",    // ? is invalid
        "file*name.txt",    // * is invalid
        "file\0name.txt",   // NUL byte is invalid
        "file\x1Fname.txt", // control char is invalid
    ];

    for component in invalid_components {
        let result = soft_canonicalize(component);

        // These should either be rejected or handled safely
        // We document behavior rather than prescribing it
        match result {
            Ok(p) => {
                // Some invalid chars may be accepted as non-existing paths
                // This is okay as long as we don't create security issues
                let _ = p;
            }
            Err(e) => {
                // Rejection is also acceptable
                assert!(
                    e.kind() == std::io::ErrorKind::InvalidInput
                        || e.kind() == std::io::ErrorKind::NotFound,
                    "Expected InvalidInput or NotFound for '{}', got: {:?}",
                    component,
                    e.kind()
                );
            }
        }
    }
}

/// Test that anchored_canonicalize properly handles exotic cases
#[cfg(all(windows, feature = "anchored"))]
#[test]
fn test_anchored_exotic_cases() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");
    let base = soft_canonicalize(tmp.path()).expect("canonicalize tempdir");

    // Test with emoji in anchored context
    let emoji_path = "🧐/file.txt";
    let result = anchored_canonicalize(&base, emoji_path);
    assert!(
        result.is_ok(),
        "Anchored should handle emoji: {}",
        emoji_path
    );

    if let Ok(resolved) = result {
        assert_eq!(
            resolved,
            base.join("🧐").join("file.txt"),
            "Anchored emoji path should resolve correctly"
        );
    }

    // Test with reserved name in anchored context
    let reserved_path = "subdir/CON.txt";
    let result = anchored_canonicalize(&base, reserved_path);
    assert!(
        result.is_ok(),
        "Anchored should handle reserved names: {}",
        reserved_path
    );

    // Test with long component in anchored context
    let long_component = "a".repeat(200);
    let long_path = format!("{}/file.txt", long_component);
    let result = anchored_canonicalize(&base, long_path);
    assert!(
        result.is_ok(),
        "Anchored should handle long components: {} chars",
        long_component.len()
    );
}

/// Test control characters in different contexts
///
/// Microsoft MSDN states control characters (1-31) are:
/// - Forbidden in regular filenames
/// - Allowed in alternate data streams (ADS)
#[cfg(windows)]
#[test]
fn test_control_characters_context_sensitive() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    // Control character in regular filename (should be rejected or handled)
    let control_in_name = "file\x01name.txt".to_string();
    let result = soft_canonicalize(tmp.path().join(control_in_name));

    match result {
        Ok(_) => {
            // If accepted, it's as non-existing path (Windows will reject at access time)
        }
        Err(e) => {
            // Rejection is acceptable for control chars in regular names
            assert!(
                e.kind() == std::io::ErrorKind::InvalidInput
                    || e.kind() == std::io::ErrorKind::NotFound,
                "Control char in filename: expected InvalidInput or NotFound, got: {:?}",
                e.kind()
            );
        }
    }

    // Control character in ADS context is explicitly tested in ADS test modules
    // This test documents the distinction
}

/// Test Unicode normalization edge cases
///
/// Unicode has multiple representations for some characters:
/// - Composed: é (single code point U+00E9)
/// - Decomposed: é (e + combining acute U+0065 U+0301)
///
/// Windows NTFS uses Unicode normalization, we verify we handle both forms
#[cfg(windows)]
#[test]
fn test_unicode_normalization() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    // Composed form (NFC)
    let composed = "café"; // é is U+00E9
    let path_composed = tmp.path().join(composed).join("file.txt");
    let result_composed = soft_canonicalize(path_composed);
    assert!(
        result_composed.is_ok(),
        "Should handle composed Unicode: {}",
        composed
    );

    // Decomposed form (NFD) - é as e + combining acute
    let decomposed = "café"; // é is U+0065 U+0301 (if your editor supports it)
    let path_decomposed = tmp.path().join(decomposed).join("file.txt");
    let result_decomposed = soft_canonicalize(path_decomposed);
    assert!(
        result_decomposed.is_ok(),
        "Should handle decomposed Unicode: {}",
        decomposed
    );

    // Both should produce paths (they may or may not be equal depending on NTFS normalization)
    // Our job is to handle both without crashing
}

/// Test maximum path depth (many nested directories)
#[cfg(windows)]
#[test]
fn test_maximum_path_depth() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");
    let mut current = tmp.path().to_path_buf();

    // Create a deeply nested path (100 levels)
    for i in 0..100 {
        current = current.join(format!("dir{}", i));
    }
    current = current.join("file.txt");

    let result = soft_canonicalize(&current);
    assert!(
        result.is_ok(),
        "Extended-length format should handle deeply nested paths"
    );

    if let Ok(resolved) = result {
        let resolved_str = resolved.to_string_lossy();
        assert!(
            resolved_str.starts_with(r"\\?\"),
            "Deep path should use extended-length format: {}",
            resolved_str
        );
    }
}

/// Test that we handle all Rust special characters correctly
///
/// Rust's OsStr can contain:
/// - Valid Unicode (most common)
/// - Invalid UTF-8 sequences (on Unix)
/// - Unpaired surrogates (on Windows)
///
/// We verify graceful handling of edge cases
#[cfg(windows)]
#[test]
fn test_rust_string_edge_cases() {
    // Test empty path component handling
    let result = soft_canonicalize("");
    assert!(result.is_err(), "Empty path should be rejected");

    // Test path with only whitespace
    let result = soft_canonicalize("   ");
    // May succeed as relative path or be rejected
    let _ = result;

    // Test path with null bytes (should be rejected)
    let null_path = "test\0file.txt";
    let result = soft_canonicalize(null_path);
    assert!(result.is_err(), "Null bytes should be rejected");
}

/// Regression test: ensure dunce test patterns don't reveal bugs
///
/// This test runs several patterns from dunce's test suite to ensure
/// our implementation handles them correctly
#[cfg(windows)]
#[test]
fn test_dunce_regression_patterns() {
    use tempfile::TempDir;

    let tmp = TempDir::new().expect("create tempdir");

    // Pattern: multiple dots with spaces
    let patterns = [
        ("con . .txt", "reserved with spaces and dots"),
        ("con.....txt", "reserved with many dots"),
        ("PRN.....", "reserved with trailing dots"),
        ("COM4 .txt", "reserved with space before extension"),
        ("a........a", "valid filename with many dots"),
        ("       b", "valid filename with leading spaces"),
    ];

    for (pattern, desc) in patterns {
        let path = tmp.path().join(pattern);
        let result = soft_canonicalize(&path);

        // Document that we handle all these patterns without panicking
        assert!(
            result.is_ok() || result.is_err(),
            "Should not panic on {}: {}",
            desc,
            pattern
        );
    }
}