strict-path 0.1.0-beta.1

More than path comparisons: full, cross-platform path security with type-level guarantees
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
// Content copied from original src/validator/virtual_root.rs
use crate::path::virtual_path::VirtualPath;
use crate::validator::path_history::PathHistory;
use crate::PathBoundary;
use crate::Result;
use std::marker::PhantomData;
use std::path::Path;
#[cfg(feature = "tempfile")]
use std::sync::Arc;

// keep feature-gated TempDir RAII field using Arc from std::sync
#[cfg(feature = "tempfile")]
use tempfile::TempDir;

/// SUMMARY:
/// Provide a user‑facing virtual root that produces `VirtualPath` values clamped to a boundary.
#[derive(Clone)]
pub struct VirtualRoot<Marker = ()> {
    pub(crate) root: PathBoundary<Marker>,
    // Held only to tie RAII of temp directories to the VirtualRoot lifetime
    #[cfg(feature = "tempfile")]
    pub(crate) _temp_dir: Option<Arc<TempDir>>, // mirrors RAII when constructed from temp
    pub(crate) _marker: PhantomData<Marker>,
}

impl<Marker> VirtualRoot<Marker> {
    // no extra constructors; use PathBoundary::virtualize() or VirtualRoot::try_new
    /// SUMMARY:
    /// Create a `VirtualRoot` from an existing directory.
    ///
    /// PARAMETERS:
    /// - `root_path` (`AsRef<Path>`): Existing directory to anchor the virtual root.
    ///
    /// RETURNS:
    /// - `Result<VirtualRoot<Marker>>`: New virtual root with clamped operations.
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: Root invalid or cannot be canonicalized.
    ///
    /// EXAMPLE:
    /// Uses `AsRef<Path>` for maximum ergonomics, including direct `TempDir` support for clean shadowing patterns:
    /// ```rust
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use strict_path::VirtualRoot;
    /// let tmp_dir = tempfile::tempdir()?;
    /// let tmp_dir = VirtualRoot::<()>::try_new(tmp_dir)?; // Clean variable shadowing
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn try_new<P: AsRef<Path>>(root_path: P) -> Result<Self> {
        let root = PathBoundary::try_new(root_path)?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// SUMMARY:
    /// Create a `VirtualRoot` backed by a unique temporary directory with RAII cleanup.
    ///
    /// # Example
    /// ```
    /// # #[cfg(feature = "tempfile")] {
    /// use strict_path::VirtualRoot;
    ///
    /// let uploads_root = VirtualRoot::<()>::try_new_temp()?;
    /// let tenant_file = uploads_root.virtual_join("tenant/document.pdf")?;
    /// let display = tenant_file.virtualpath_display().to_string();
    /// assert!(display.starts_with("/"));
    /// # }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "tempfile")]
    #[inline]
    pub fn try_new_temp() -> Result<Self> {
        let root = PathBoundary::try_new_temp()?;
        let temp_dir = root.temp_dir_arc();
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: temp_dir,
            _marker: PhantomData,
        })
    }

    /// SUMMARY:
    /// Create a `VirtualRoot` in a temporary directory with a custom prefix and RAII cleanup.
    ///
    /// # Example
    /// ```
    /// # #[cfg(feature = "tempfile")] {
    /// use strict_path::VirtualRoot;
    ///
    /// let session_root = VirtualRoot::<()>::try_new_temp_with_prefix("session")?;
    /// let export_path = session_root.virtual_join("exports/report.txt")?;
    /// let display = export_path.virtualpath_display().to_string();
    /// assert!(display.starts_with("/exports"));
    /// # }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "tempfile")]
    #[inline]
    pub fn try_new_temp_with_prefix(prefix: &str) -> Result<Self> {
        let root = PathBoundary::try_new_temp_with_prefix(prefix)?;
        let temp_dir = root.temp_dir_arc();
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: temp_dir,
            _marker: PhantomData,
        })
    }

    /// SUMMARY:
    /// Return filesystem metadata for the underlying root directory.
    #[inline]
    pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
        self.root.metadata()
    }

    /// SUMMARY:
    /// Create a symbolic link at `link_path` pointing to this root's underlying directory.
    pub fn virtual_symlink(
        &self,
        link_path: &crate::path::virtual_path::VirtualPath<Marker>,
    ) -> std::io::Result<()> {
        let root = self
            .virtual_join("")
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        root.as_unvirtual().strict_symlink(link_path.as_unvirtual())
    }

    /// SUMMARY:
    /// Create a hard link at `link_path` pointing to this root's underlying directory.
    pub fn virtual_hard_link(
        &self,
        link_path: &crate::path::virtual_path::VirtualPath<Marker>,
    ) -> std::io::Result<()> {
        let root = self
            .virtual_join("")
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        root.as_unvirtual()
            .strict_hard_link(link_path.as_unvirtual())
    }

    /// SUMMARY:
    /// Read directory entries at the virtual root (discovery). Re‑join names through virtual/strict APIs before I/O.
    #[inline]
    pub fn read_dir(&self) -> std::io::Result<std::fs::ReadDir> {
        self.root.read_dir()
    }

    /// SUMMARY:
    /// Remove the underlying root directory (non‑recursive); fails if not empty.
    #[inline]
    pub fn remove_dir(&self) -> std::io::Result<()> {
        self.root.remove_dir()
    }

    /// SUMMARY:
    /// Recursively remove the underlying root directory and all its contents.
    #[inline]
    pub fn remove_dir_all(&self) -> std::io::Result<()> {
        self.root.remove_dir_all()
    }

    /// SUMMARY:
    /// Ensure the directory exists (create if missing), then return a `VirtualRoot`.
    ///
    /// EXAMPLE:
    /// Uses `AsRef<Path>` for maximum ergonomics, including direct `TempDir` support for clean shadowing patterns:
    /// ```rust
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use strict_path::VirtualRoot;
    /// let tmp_dir = tempfile::tempdir()?;
    /// let tmp_dir = VirtualRoot::<()>::try_new_create(tmp_dir)?; // Clean variable shadowing
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn try_new_create<P: AsRef<Path>>(root_path: P) -> Result<Self> {
        let root = PathBoundary::try_new_create(root_path)?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// SUMMARY:
    /// Join a candidate path to this virtual root, producing a clamped `VirtualPath`.
    ///
    /// PARAMETERS:
    /// - `candidate_path` (`AsRef<Path>`): Virtual path to resolve and clamp.
    ///
    /// RETURNS:
    /// - `Result<VirtualPath<Marker>>`: Clamped, validated path within the virtual root.
    ///
    /// ERRORS:
    /// - `StrictPathError::PathResolutionError`, `StrictPathError::PathEscapesBoundary`.
    #[inline]
    pub fn virtual_join<P: AsRef<Path>>(&self, candidate_path: P) -> Result<VirtualPath<Marker>> {
        // 1) Anchor in virtual space (clamps virtual root and resolves relative parts)
        let user_candidate = candidate_path.as_ref().to_path_buf();
        let anchored = PathHistory::new(user_candidate).canonicalize_anchored(&self.root)?;

        // 2) Boundary-check once against the PathBoundary's canonicalized root (no re-canonicalization)
        let validated = anchored.boundary_check(self.root.stated_path())?;

        // 3) Construct a StrictPath directly and then virtualize
        let jp = crate::path::strict_path::StrictPath::new(
            std::sync::Arc::new(self.root.clone()),
            validated,
        );
        Ok(jp.virtualize())
    }

    /// Returns the underlying path boundary root as a system path.
    #[inline]
    pub(crate) fn path(&self) -> &Path {
        self.root.path()
    }

    /// SUMMARY:
    /// Return the virtual root path as `&OsStr` for allocation‑free `AsRef<Path>` interop.
    #[inline]
    pub fn interop_path(&self) -> &std::ffi::OsStr {
        self.root.interop_path()
    }

    /// Returns true if the underlying path boundary root exists.
    #[inline]
    pub fn exists(&self) -> bool {
        self.root.exists()
    }

    /// SUMMARY:
    /// Borrow the underlying `PathBoundary`.
    #[inline]
    pub fn as_unvirtual(&self) -> &PathBoundary<Marker> {
        &self.root
    }

    /// SUMMARY:
    /// Consume this `VirtualRoot` and return the underlying `PathBoundary` (symmetry with `virtualize`).
    #[inline]
    pub fn unvirtual(self) -> PathBoundary<Marker> {
        self.root
    }

    // OS Standard Directory Constructors
    //
    // Creates virtual roots in OS standard directories following platform conventions.
    // Applications see clean virtual paths ("/config.toml") while the system manages
    // the actual location (e.g., "~/.config/myapp/config.toml").

    /// Creates a virtual root in the OS standard config directory.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `~/.config/{app_name}` (XDG Base Directory Specification)
    /// - **Windows**: `%APPDATA%\{app_name}` (Known Folder API - Roaming AppData)
    /// - **macOS**: `~/Library/Application Support/{app_name}` (Apple Standard Directories)
    #[cfg(feature = "dirs")]
    pub fn try_new_os_config(app_name: &str) -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_config(app_name)?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the OS standard data directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_data(app_name: &str) -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_data(app_name)?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the OS standard cache directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_cache(app_name: &str) -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_cache(app_name)?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the OS local config directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_config_local(app_name: &str) -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_config_local(app_name)?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the OS local data directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_data_local(app_name: &str) -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_data_local(app_name)?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the user's home directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_home() -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_home()?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the user's desktop directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_desktop() -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_desktop()?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the user's documents directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_documents() -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_documents()?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the user's downloads directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_downloads() -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_downloads()?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the user's pictures directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_pictures() -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_pictures()?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the user's music/audio directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_audio() -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_audio()?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the user's videos directory.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_videos() -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_videos()?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the OS executable directory (Linux only).
    #[cfg(feature = "dirs")]
    pub fn try_new_os_executables() -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_executables()?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the OS runtime directory (Linux only).
    #[cfg(feature = "dirs")]
    pub fn try_new_os_runtime() -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_runtime()?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// Creates a virtual root in the OS state directory (Linux only).
    #[cfg(feature = "dirs")]
    pub fn try_new_os_state(app_name: &str) -> Result<Self> {
        let root = crate::PathBoundary::try_new_os_state(app_name)?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// SUMMARY:
    /// Create a virtual root using the `app-path` strategy (portable app‑relative directory),
    /// optionally honoring an environment variable override.
    ///
    /// PARAMETERS:
    /// - `subdir` (`AsRef<Path>`): Subdirectory path relative to the executable location (or to the
    ///   directory specified by the environment override). Accepts any path‑like value via `AsRef<Path>`.
    /// - `env_override` (Option<&str>): Optional environment variable name to check first; when set
    ///   and the variable is present, its value is used as the root base instead of the executable directory.
    ///
    /// RETURNS:
    /// - `Result<VirtualRoot<Marker>>`: Virtual root whose underlying `PathBoundary` is created if missing
    ///   and proven safe; all subsequent `virtual_join` operations are clamped to this root.
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: If `app-path` resolution fails or the directory cannot be created/validated.
    ///
    /// EXAMPLE:
    /// ```rust
    /// # #[cfg(feature = "app-path")] {
    /// use strict_path::VirtualRoot;
    ///
    /// // Create ./data relative to the executable (portable layout)
    /// let vroot = VirtualRoot::<()>::try_new_app_path("data", None)?;
    /// let vp = vroot.virtual_join("docs/report.txt")?;
    /// assert_eq!(vp.virtualpath_display().to_string(), "/docs/report.txt");
    ///
    /// // With environment override: respects MYAPP_DATA_DIR when set
    /// let _vroot = VirtualRoot::<()>::try_new_app_path("data", Some("MYAPP_DATA_DIR"))?;
    /// # }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "app-path")]
    pub fn try_new_app_path<P: AsRef<Path>>(subdir: P, env_override: Option<&str>) -> Result<Self> {
        let root = crate::PathBoundary::try_new_app_path(subdir, env_override)?;
        Ok(Self {
            root,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        })
    }

    /// SUMMARY:
    /// Create a virtual root via `app-path`, always consulting a specific environment variable
    /// before falling back to the executable‑relative directory.
    ///
    /// PARAMETERS:
    /// - `subdir` (`AsRef<Path>`): Subdirectory path used with `app-path` resolution.
    /// - `env_override` (&str): Environment variable name to check first for the root base.
    ///
    /// RETURNS:
    /// - `Result<VirtualRoot<Marker>>`: New virtual root anchored using `app-path` semantics.
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: If resolution fails or the directory can't be created/validated.
    ///
    /// EXAMPLE:
    /// ```rust
    /// # #[cfg(feature = "app-path")] {
    /// use strict_path::VirtualRoot;
    /// let _vroot = VirtualRoot::<()>::try_new_app_path_with_env("cache", "MYAPP_CACHE_DIR")?;
    /// # }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "app-path")]
    pub fn try_new_app_path_with_env<P: AsRef<Path>>(
        subdir: P,
        env_override: &str,
    ) -> Result<Self> {
        Self::try_new_app_path(subdir, Some(env_override))
    }
}

impl<Marker> std::fmt::Display for VirtualRoot<Marker> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.path().display())
    }
}

impl<Marker> AsRef<Path> for VirtualRoot<Marker> {
    fn as_ref(&self) -> &Path {
        self.path()
    }
}

impl<Marker> std::fmt::Debug for VirtualRoot<Marker> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VirtualRoot")
            .field("root", &self.path())
            .field("marker", &std::any::type_name::<Marker>())
            .finish()
    }
}

impl<Marker> PartialEq for VirtualRoot<Marker> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.path() == other.path()
    }
}

impl<Marker> Eq for VirtualRoot<Marker> {}

impl<Marker> std::hash::Hash for VirtualRoot<Marker> {
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.path().hash(state);
    }
}

impl<Marker> PartialOrd for VirtualRoot<Marker> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<Marker> Ord for VirtualRoot<Marker> {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.path().cmp(other.path())
    }
}

impl<Marker> PartialEq<crate::PathBoundary<Marker>> for VirtualRoot<Marker> {
    #[inline]
    fn eq(&self, other: &crate::PathBoundary<Marker>) -> bool {
        self.path() == other.path()
    }
}

impl<Marker> PartialEq<std::path::Path> for VirtualRoot<Marker> {
    #[inline]
    fn eq(&self, other: &std::path::Path) -> bool {
        // Compare as virtual root path (always "/")
        // VirtualRoot represents the virtual "/" regardless of underlying system path
        let other_str = other.to_string_lossy();

        #[cfg(windows)]
        let other_normalized = other_str.replace('\\', "/");
        #[cfg(not(windows))]
        let other_normalized = other_str.to_string();

        let normalized_other = if other_normalized.starts_with('/') {
            other_normalized
        } else {
            format!("/{}", other_normalized)
        };

        "/" == normalized_other
    }
}

impl<Marker> PartialEq<std::path::PathBuf> for VirtualRoot<Marker> {
    #[inline]
    fn eq(&self, other: &std::path::PathBuf) -> bool {
        self.eq(other.as_path())
    }
}

impl<Marker> PartialEq<&std::path::Path> for VirtualRoot<Marker> {
    #[inline]
    fn eq(&self, other: &&std::path::Path) -> bool {
        self.eq(*other)
    }
}

impl<Marker> PartialOrd<std::path::Path> for VirtualRoot<Marker> {
    #[inline]
    fn partial_cmp(&self, other: &std::path::Path) -> Option<std::cmp::Ordering> {
        // Compare as virtual root path (always "/")
        let other_str = other.to_string_lossy();

        // Handle empty path specially - "/" is greater than ""
        if other_str.is_empty() {
            return Some(std::cmp::Ordering::Greater);
        }

        #[cfg(windows)]
        let other_normalized = other_str.replace('\\', "/");
        #[cfg(not(windows))]
        let other_normalized = other_str.to_string();

        let normalized_other = if other_normalized.starts_with('/') {
            other_normalized
        } else {
            format!("/{}", other_normalized)
        };

        Some("/".cmp(&normalized_other))
    }
}

impl<Marker> PartialOrd<&std::path::Path> for VirtualRoot<Marker> {
    #[inline]
    fn partial_cmp(&self, other: &&std::path::Path) -> Option<std::cmp::Ordering> {
        self.partial_cmp(*other)
    }
}

impl<Marker> PartialOrd<std::path::PathBuf> for VirtualRoot<Marker> {
    #[inline]
    fn partial_cmp(&self, other: &std::path::PathBuf) -> Option<std::cmp::Ordering> {
        self.partial_cmp(other.as_path())
    }
}

impl<Marker: Default> std::str::FromStr for VirtualRoot<Marker> {
    type Err = crate::StrictPathError;

    /// Parse a VirtualRoot from a string path for universal ergonomics.
    ///
    /// Creates the directory if it doesn't exist, enabling seamless integration
    /// with any string-parsing context (clap, config files, environment variables, etc.):
    /// ```rust
    /// # use strict_path::VirtualRoot;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let temp_dir = tempfile::tempdir()?;
    /// let virtual_path = temp_dir.path().join("virtual_dir");
    /// let vroot: VirtualRoot<()> = virtual_path.to_string_lossy().parse()?;
    /// assert!(virtual_path.exists());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    fn from_str(path: &str) -> std::result::Result<Self, Self::Err> {
        Self::try_new_create(path)
    }
}