ruff_db 0.0.8

This is an internal component crate of Ruff
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
use camino::{Utf8Path, Utf8PathBuf};
use std::borrow::Borrow;
use std::fmt::Formatter;
use std::ops::Deref;
use std::path::{Path, PathBuf, StripPrefixError};

/// A slice of a path on [`System`](super::System) (akin to [`str`]).
///
/// The path is guaranteed to be valid UTF-8.
#[repr(transparent)]
#[derive(Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct SystemPath(Utf8Path);

impl SystemPath {
    pub fn new(path: &(impl AsRef<Utf8Path> + ?Sized)) -> &Self {
        let path = path.as_ref();
        // SAFETY: FsPath is marked as #[repr(transparent)] so the conversion from a
        // *const Utf8Path to a *const FsPath is valid.
        unsafe { &*(path as *const Utf8Path as *const SystemPath) }
    }

    /// Takes any path, and when possible, converts Windows UNC paths to regular paths.
    /// If the path can't be converted, it's returned unmodified.
    ///
    /// On non-Windows this is no-op.
    ///
    /// `\\?\C:\Windows` will be converted to `C:\Windows`,
    /// but `\\?\C:\COM` will be left as-is (due to a reserved filename).
    ///
    /// Use this to pass arbitrary paths to programs that may not be UNC-aware.
    ///
    /// It's generally safe to pass UNC paths to legacy programs, because
    /// these paths contain a reserved prefix, so will gracefully fail
    /// if used with legacy APIs that don't support UNC.
    ///
    /// This function does not perform any I/O.
    ///
    /// Currently paths with unpaired surrogates aren't converted even if they
    /// could be, due to limitations of Rust's `OsStr` API.
    ///
    /// To check if a path remained as UNC, use `path.as_os_str().as_encoded_bytes().starts_with(b"\\\\")`.
    #[inline]
    pub fn simplified(&self) -> &SystemPath {
        // SAFETY: simplified only trims the path, that means the returned path must be a valid UTF-8 path.
        SystemPath::from_std_path(dunce::simplified(self.as_std_path())).unwrap()
    }

    /// Returns `true` if the `SystemPath` is absolute, i.e., if it is independent of
    /// the current directory.
    ///
    /// * On Unix, a path is absolute if it starts with the root, so
    ///   `is_absolute` and [`has_root`] are equivalent.
    ///
    /// * On Windows, a path is absolute if it has a prefix and starts with the
    ///   root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::SystemPath;
    ///
    /// assert!(!SystemPath::new("foo.txt").is_absolute());
    /// ```
    ///
    /// [`has_root`]: Utf8Path::has_root
    #[inline]
    #[must_use]
    pub fn is_absolute(&self) -> bool {
        self.0.is_absolute()
    }

    /// Extracts the file extension, if possible.
    ///
    /// The extension is:
    ///
    /// * [`None`], if there is no file name;
    /// * [`None`], if there is no embedded `.`;
    /// * [`None`], if the file name begins with `.` and has no other `.`s within;
    /// * Otherwise, the portion of the file name after the final `.`
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::SystemPath;
    ///
    /// assert_eq!("rs", SystemPath::new("foo.rs").extension().unwrap());
    /// assert_eq!("gz", SystemPath::new("foo.tar.gz").extension().unwrap());
    /// ```
    ///
    /// See [`Path::extension`] for more details.
    #[inline]
    #[must_use]
    pub fn extension(&self) -> Option<&str> {
        self.0.extension()
    }

    /// Determines whether `base` is a prefix of `self`.
    ///
    /// Only considers whole path components to match.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::SystemPath;
    ///
    /// let path = SystemPath::new("/etc/passwd");
    ///
    /// assert!(path.starts_with("/etc"));
    /// assert!(path.starts_with("/etc/"));
    /// assert!(path.starts_with("/etc/passwd"));
    /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
    /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
    ///
    /// assert!(!path.starts_with("/e"));
    /// assert!(!path.starts_with("/etc/passwd.txt"));
    ///
    /// assert!(!SystemPath::new("/etc/foo.rs").starts_with("/etc/foo"));
    /// ```
    #[inline]
    #[must_use]
    pub fn starts_with(&self, base: impl AsRef<SystemPath>) -> bool {
        self.0.starts_with(base.as_ref())
    }

    /// Determines whether `child` is a suffix of `self`.
    ///
    /// Only considers whole path components to match.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::SystemPath;
    ///
    /// let path = SystemPath::new("/etc/resolv.conf");
    ///
    /// assert!(path.ends_with("resolv.conf"));
    /// assert!(path.ends_with("etc/resolv.conf"));
    /// assert!(path.ends_with("/etc/resolv.conf"));
    ///
    /// assert!(!path.ends_with("/resolv.conf"));
    /// assert!(!path.ends_with("conf")); // use .extension() instead
    /// ```
    #[inline]
    #[must_use]
    pub fn ends_with(&self, child: impl AsRef<SystemPath>) -> bool {
        self.0.ends_with(child.as_ref())
    }

    /// Returns the `FileSystemPath` without its final component, if there is one.
    ///
    /// Returns [`None`] if the path terminates in a root or prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::SystemPath;
    ///
    /// let path = SystemPath::new("/foo/bar");
    /// let parent = path.parent().unwrap();
    /// assert_eq!(parent, SystemPath::new("/foo"));
    ///
    /// let grand_parent = parent.parent().unwrap();
    /// assert_eq!(grand_parent, SystemPath::new("/"));
    /// assert_eq!(grand_parent.parent(), None);
    /// ```
    #[inline]
    #[must_use]
    pub fn parent(&self) -> Option<&SystemPath> {
        self.0.parent().map(SystemPath::new)
    }

    /// Produces an iterator over `SystemPath` and its ancestors.
    ///
    /// The iterator will yield the `SystemPath` that is returned if the [`parent`] method is used zero
    /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
    /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
    /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
    /// namely `&self`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::SystemPath;
    ///
    /// let mut ancestors = SystemPath::new("/foo/bar").ancestors();
    /// assert_eq!(ancestors.next(), Some(SystemPath::new("/foo/bar")));
    /// assert_eq!(ancestors.next(), Some(SystemPath::new("/foo")));
    /// assert_eq!(ancestors.next(), Some(SystemPath::new("/")));
    /// assert_eq!(ancestors.next(), None);
    ///
    /// let mut ancestors = SystemPath::new("../foo/bar").ancestors();
    /// assert_eq!(ancestors.next(), Some(SystemPath::new("../foo/bar")));
    /// assert_eq!(ancestors.next(), Some(SystemPath::new("../foo")));
    /// assert_eq!(ancestors.next(), Some(SystemPath::new("..")));
    /// assert_eq!(ancestors.next(), Some(SystemPath::new("")));
    /// assert_eq!(ancestors.next(), None);
    /// ```
    ///
    /// [`parent`]: SystemPath::parent
    #[inline]
    pub fn ancestors(&self) -> impl Iterator<Item = &SystemPath> {
        self.0.ancestors().map(SystemPath::new)
    }

    /// Produces an iterator over the [`camino::Utf8Component`]s of the path.
    ///
    /// When parsing the path, there is a small amount of normalization:
    ///
    /// * Repeated separators are ignored, so `a/b` and `a//b` both have
    ///   `a` and `b` as components.
    ///
    /// * Occurrences of `.` are normalized away, except if they are at the
    ///   beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
    ///   `a/b` all have `a` and `b` as components, but `./a/b` starts with
    ///   an additional [`CurDir`] component.
    ///
    /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
    ///
    /// Note that no other normalization takes place; in particular, `a/c`
    /// and `a/b/../c` are distinct, to account for the possibility that `b`
    /// is a symbolic link (so its parent isn't `a`).
    ///
    /// # Examples
    ///
    /// ```
    /// use camino::{Utf8Component};
    /// use ruff_db::system::SystemPath;
    ///
    /// let mut components = SystemPath::new("/tmp/foo.txt").components();
    ///
    /// assert_eq!(components.next(), Some(Utf8Component::RootDir));
    /// assert_eq!(components.next(), Some(Utf8Component::Normal("tmp")));
    /// assert_eq!(components.next(), Some(Utf8Component::Normal("foo.txt")));
    /// assert_eq!(components.next(), None)
    /// ```
    ///
    /// [`CurDir`]: camino::Utf8Component::CurDir
    #[inline]
    pub fn components(&self) -> camino::Utf8Components<'_> {
        self.0.components()
    }

    /// Returns the final component of the `FileSystemPath`, if there is one.
    ///
    /// If the path is a normal file, this is the file name. If it's the path of a directory, this
    /// is the directory name.
    ///
    /// Returns [`None`] if the path terminates in `..`.
    ///
    /// # Examples
    ///
    /// ```
    /// use camino::Utf8Path;
    /// use ruff_db::system::SystemPath;
    ///
    /// assert_eq!(Some("bin"), SystemPath::new("/usr/bin/").file_name());
    /// assert_eq!(Some("foo.txt"), SystemPath::new("tmp/foo.txt").file_name());
    /// assert_eq!(Some("foo.txt"), SystemPath::new("foo.txt/.").file_name());
    /// assert_eq!(Some("foo.txt"), SystemPath::new("foo.txt/.//").file_name());
    /// assert_eq!(None, SystemPath::new("foo.txt/..").file_name());
    /// assert_eq!(None, SystemPath::new("/").file_name());
    /// ```
    #[inline]
    #[must_use]
    pub fn file_name(&self) -> Option<&str> {
        self.0.file_name()
    }

    /// Extracts the stem (non-extension) portion of [`self.file_name`].
    ///
    /// [`self.file_name`]: SystemPath::file_name
    ///
    /// The stem is:
    ///
    /// * [`None`], if there is no file name;
    /// * The entire file name if there is no embedded `.`;
    /// * The entire file name if the file name begins with `.` and has no other `.`s within;
    /// * Otherwise, the portion of the file name before the final `.`
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::SystemPath;
    ///
    /// assert_eq!("foo", SystemPath::new("foo.rs").file_stem().unwrap());
    /// assert_eq!("foo.tar", SystemPath::new("foo.tar.gz").file_stem().unwrap());
    /// ```
    #[inline]
    #[must_use]
    pub fn file_stem(&self) -> Option<&str> {
        self.0.file_stem()
    }

    /// Returns a path that, when joined onto `base`, yields `self`.
    ///
    /// # Errors
    ///
    /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
    /// returns `false`), returns [`Err`].
    ///
    /// [`starts_with`]: SystemPath::starts_with
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::{SystemPath, SystemPathBuf};
    ///
    /// let path = SystemPath::new("/test/haha/foo.txt");
    ///
    /// assert_eq!(path.strip_prefix("/"), Ok(SystemPath::new("test/haha/foo.txt")));
    /// assert_eq!(path.strip_prefix("/test"), Ok(SystemPath::new("haha/foo.txt")));
    /// assert_eq!(path.strip_prefix("/test/"), Ok(SystemPath::new("haha/foo.txt")));
    /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(SystemPath::new("")));
    /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(SystemPath::new("")));
    ///
    /// assert!(path.strip_prefix("test").is_err());
    /// assert!(path.strip_prefix("/haha").is_err());
    ///
    /// let prefix = SystemPathBuf::from("/test/");
    /// assert_eq!(path.strip_prefix(prefix), Ok(SystemPath::new("haha/foo.txt")));
    /// ```
    #[inline]
    pub fn strip_prefix(
        &self,
        base: impl AsRef<SystemPath>,
    ) -> std::result::Result<&SystemPath, StripPrefixError> {
        self.0.strip_prefix(base.as_ref()).map(SystemPath::new)
    }

    /// Creates an owned [`SystemPathBuf`] with `path` adjoined to `self`.
    ///
    /// See [`std::path::PathBuf::push`] for more details on what it means to adjoin a path.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::{SystemPath, SystemPathBuf};
    ///
    /// assert_eq!(SystemPath::new("/etc").join("passwd"), SystemPathBuf::from("/etc/passwd"));
    /// ```
    #[inline]
    #[must_use]
    pub fn join(&self, path: impl AsRef<SystemPath>) -> SystemPathBuf {
        SystemPathBuf::from_utf8_path_buf(self.0.join(&path.as_ref().0))
    }

    /// Creates an owned [`SystemPathBuf`] like `self` but with the given extension.
    ///
    /// See [`std::path::PathBuf::set_extension`] for more details.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::{SystemPath, SystemPathBuf};
    ///
    /// let path = SystemPath::new("foo.rs");
    /// assert_eq!(path.with_extension("txt"), SystemPathBuf::from("foo.txt"));
    ///
    /// let path = SystemPath::new("foo.tar.gz");
    /// assert_eq!(path.with_extension(""), SystemPathBuf::from("foo.tar"));
    /// assert_eq!(path.with_extension("xz"), SystemPathBuf::from("foo.tar.xz"));
    /// assert_eq!(path.with_extension("").with_extension("txt"), SystemPathBuf::from("foo.txt"));
    /// ```
    #[inline]
    pub fn with_extension(&self, extension: &str) -> SystemPathBuf {
        SystemPathBuf::from_utf8_path_buf(self.0.with_extension(extension))
    }

    /// Converts the path to an owned [`SystemPathBuf`].
    pub fn to_path_buf(&self) -> SystemPathBuf {
        SystemPathBuf(self.0.to_path_buf())
    }

    /// Returns the path as a string slice.
    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Returns the std path for the file.
    #[inline]
    pub fn as_std_path(&self) -> &Path {
        self.0.as_std_path()
    }

    /// Returns the [`Utf8Path`] for the file.
    #[inline]
    pub fn as_utf8_path(&self) -> &Utf8Path {
        &self.0
    }

    pub fn from_std_path(path: &Path) -> Option<&SystemPath> {
        Some(SystemPath::new(Utf8Path::from_path(path)?))
    }

    /// Makes a path absolute and normalizes it without accessing the file system.
    ///
    /// Adapted from [cargo](https://github.com/rust-lang/cargo/blob/fede83ccf973457de319ba6fa0e36ead454d2e20/src/cargo/util/paths.rs#L61)
    ///
    /// # Examples
    ///
    /// ## Posix paths
    ///
    /// ```
    /// # #[cfg(unix)]
    /// # fn main() {
    ///   use ruff_db::system::{SystemPath, SystemPathBuf};
    ///
    ///   // Relative to absolute
    ///   let absolute = SystemPath::absolute("foo/./bar", "/tmp");
    ///   assert_eq!(absolute, SystemPathBuf::from("/tmp/foo/bar"));
    ///
    ///   // Path's going past the root are normalized to the root
    ///   let absolute = SystemPath::absolute("../../../", "/tmp");
    ///   assert_eq!(absolute, SystemPathBuf::from("/"));
    ///
    ///   // Absolute to absolute
    ///   let absolute = SystemPath::absolute("/foo//test/.././bar.rs", "/tmp");
    ///   assert_eq!(absolute, SystemPathBuf::from("/foo/bar.rs"));
    /// # }
    /// # #[cfg(not(unix))]
    /// # fn main() {}
    /// ```
    ///
    /// ## Windows paths
    ///
    /// ```
    /// # #[cfg(windows)]
    /// # fn main() {
    ///   use ruff_db::system::{SystemPath, SystemPathBuf};
    ///
    ///   // Relative to absolute
    ///   let absolute = SystemPath::absolute(r"foo\.\bar", r"C:\tmp");
    ///   assert_eq!(absolute, SystemPathBuf::from(r"C:\tmp\foo\bar"));
    ///
    ///   // Path's going past the root are normalized to the root
    ///   let absolute = SystemPath::absolute(r"..\..\..\", r"C:\tmp");
    ///   assert_eq!(absolute, SystemPathBuf::from(r"C:\"));
    ///
    ///   // Absolute to absolute
    ///   let absolute = SystemPath::absolute(r"C:\foo//test\..\./bar.rs", r"C:\tmp");
    ///   assert_eq!(absolute, SystemPathBuf::from(r"C:\foo\bar.rs"));
    /// # }
    /// # #[cfg(not(windows))]
    /// # fn main() {}
    /// ```
    pub fn absolute(path: impl AsRef<SystemPath>, cwd: impl AsRef<SystemPath>) -> SystemPathBuf {
        fn absolute(path: &SystemPath, cwd: &SystemPath) -> SystemPathBuf {
            let path = &path.0;

            let mut components = path.components().peekable();
            let mut ret = if let Some(
                c @ (camino::Utf8Component::Prefix(..) | camino::Utf8Component::RootDir),
            ) = components.peek().cloned()
            {
                components.next();
                Utf8PathBuf::from(c.as_str())
            } else {
                cwd.0.to_path_buf()
            };

            for component in components {
                match component {
                    camino::Utf8Component::Prefix(..) => unreachable!(),
                    camino::Utf8Component::RootDir => {
                        ret.push(component);
                    }
                    camino::Utf8Component::CurDir => {}
                    camino::Utf8Component::ParentDir => {
                        ret.pop();
                    }
                    camino::Utf8Component::Normal(c) => {
                        ret.push(c);
                    }
                }
            }

            SystemPathBuf::from_utf8_path_buf(ret)
        }

        absolute(path.as_ref(), cwd.as_ref())
    }
}

impl ToOwned for SystemPath {
    type Owned = SystemPathBuf;

    fn to_owned(&self) -> Self::Owned {
        self.to_path_buf()
    }
}

/// An owned, mutable path on [`System`](`super::System`) (akin to [`String`]).
///
/// The path is guaranteed to be valid UTF-8.
#[repr(transparent)]
#[derive(Eq, PartialEq, Clone, Hash, PartialOrd, Ord)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(transparent)
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SystemPathBuf(#[cfg_attr(feature = "schemars", schemars(with = "String"))] Utf8PathBuf);

impl get_size2::GetSize for SystemPathBuf {
    fn get_heap_size_with_tracker<T: get_size2::GetSizeTracker>(&self, tracker: T) -> (usize, T) {
        (self.0.capacity(), tracker)
    }
}

impl SystemPathBuf {
    pub fn new() -> Self {
        Self(Utf8PathBuf::new())
    }

    pub fn from_utf8_path_buf(path: Utf8PathBuf) -> Self {
        Self(path)
    }

    pub fn from_path_buf(
        path: std::path::PathBuf,
    ) -> std::result::Result<Self, std::path::PathBuf> {
        Utf8PathBuf::from_path_buf(path).map(Self)
    }

    /// Try to convert from `path` directly, falling back to the lossy string representation on
    /// error.
    pub fn from_path_buf_lossy(path: std::path::PathBuf) -> Self {
        Self::from_path_buf(path)
            .unwrap_or_else(|path| Self::from(path.to_string_lossy().to_string()))
    }

    /// Extends `self` with `path`.
    ///
    /// If `path` is absolute, it replaces the current path.
    ///
    /// On Windows:
    ///
    /// * if `path` has a root but no prefix (e.g., `\windows`), it
    ///   replaces everything except for the prefix (if any) of `self`.
    /// * if `path` has a prefix but no root, it replaces `self`.
    ///
    /// # Examples
    ///
    /// Pushing a relative path extends the existing path:
    ///
    /// ```
    /// use ruff_db::system::SystemPathBuf;
    ///
    /// let mut path = SystemPathBuf::from("/tmp");
    /// path.push("file.bk");
    /// assert_eq!(path, SystemPathBuf::from("/tmp/file.bk"));
    /// ```
    ///
    /// Pushing an absolute path replaces the existing path:
    ///
    /// ```
    ///
    /// use ruff_db::system::SystemPathBuf;
    ///
    /// let mut path = SystemPathBuf::from("/tmp");
    /// path.push("/etc");
    /// assert_eq!(path, SystemPathBuf::from("/etc"));
    /// ```
    pub fn push(&mut self, path: impl AsRef<SystemPath>) {
        self.0.push(&path.as_ref().0);
    }

    pub fn into_utf8_path_buf(self) -> Utf8PathBuf {
        self.0
    }

    pub fn into_std_path_buf(self) -> PathBuf {
        self.0.into_std_path_buf()
    }

    pub fn into_string(self) -> String {
        self.0.into_string()
    }

    #[inline]
    pub fn as_path(&self) -> &SystemPath {
        SystemPath::new(&self.0)
    }
}

impl From<&SystemPath> for Box<SystemPath> {
    fn from(path: &SystemPath) -> Self {
        Box::from(path.to_path_buf())
    }
}

impl From<SystemPathBuf> for Box<SystemPath> {
    fn from(path: SystemPathBuf) -> Self {
        let path = Box::into_raw(path.0.into_boxed_path()) as *mut SystemPath;
        // SAFETY: SystemPath is marked as #[repr(transparent)] so the conversion from a
        // *mut Utf8Path to a *mut SystemPath is valid.
        unsafe { Box::from_raw(path) }
    }
}

impl Clone for Box<SystemPath> {
    fn clone(&self) -> Self {
        Box::from(&**self)
    }
}

impl get_size2::GetSize for Box<SystemPath> {
    fn get_heap_size_with_tracker<T: get_size2::GetSizeTracker>(&self, tracker: T) -> (usize, T) {
        (std::mem::size_of_val(&**self), tracker)
    }
}

impl Borrow<SystemPath> for SystemPathBuf {
    fn borrow(&self) -> &SystemPath {
        self.as_path()
    }
}

impl From<&str> for SystemPathBuf {
    fn from(value: &str) -> Self {
        SystemPathBuf::from_utf8_path_buf(Utf8PathBuf::from(value))
    }
}

impl From<String> for SystemPathBuf {
    fn from(value: String) -> Self {
        SystemPathBuf::from_utf8_path_buf(Utf8PathBuf::from(value))
    }
}

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

impl AsRef<SystemPath> for SystemPathBuf {
    #[inline]
    fn as_ref(&self) -> &SystemPath {
        self.as_path()
    }
}

impl AsRef<SystemPath> for SystemPath {
    #[inline]
    fn as_ref(&self) -> &SystemPath {
        self
    }
}

impl AsRef<SystemPath> for Utf8Path {
    #[inline]
    fn as_ref(&self) -> &SystemPath {
        SystemPath::new(self)
    }
}

impl AsRef<SystemPath> for Utf8PathBuf {
    #[inline]
    fn as_ref(&self) -> &SystemPath {
        SystemPath::new(self.as_path())
    }
}

impl AsRef<SystemPath> for camino::Utf8Component<'_> {
    #[inline]
    fn as_ref(&self) -> &SystemPath {
        SystemPath::new(self.as_str())
    }
}

impl AsRef<SystemPath> for str {
    #[inline]
    fn as_ref(&self) -> &SystemPath {
        SystemPath::new(self)
    }
}

impl AsRef<SystemPath> for String {
    #[inline]
    fn as_ref(&self) -> &SystemPath {
        SystemPath::new(self)
    }
}

impl AsRef<Path> for SystemPath {
    #[inline]
    fn as_ref(&self) -> &Path {
        self.0.as_std_path()
    }
}

impl Deref for SystemPathBuf {
    type Target = SystemPath;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_path()
    }
}

impl AsRef<Path> for SystemPathBuf {
    #[inline]
    fn as_ref(&self) -> &Path {
        self.0.as_std_path()
    }
}

impl<P: AsRef<SystemPath>> FromIterator<P> for SystemPathBuf {
    fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> Self {
        let mut buf = SystemPathBuf::new();
        buf.extend(iter);
        buf
    }
}

impl<P: AsRef<SystemPath>> Extend<P> for SystemPathBuf {
    fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
        for path in iter {
            self.push(path);
        }
    }
}

impl std::fmt::Debug for SystemPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl std::fmt::Display for SystemPath {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl std::fmt::Debug for SystemPathBuf {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl std::fmt::Display for SystemPathBuf {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(feature = "cache")]
impl ruff_cache::CacheKey for SystemPath {
    fn cache_key(&self, hasher: &mut ruff_cache::CacheKeyHasher) {
        self.0.as_str().cache_key(hasher);
    }
}

#[cfg(feature = "cache")]
impl ruff_cache::CacheKey for SystemPathBuf {
    fn cache_key(&self, hasher: &mut ruff_cache::CacheKeyHasher) {
        self.as_path().cache_key(hasher);
    }
}

/// A slice of a virtual path on [`System`](super::System) (akin to [`str`]).
#[repr(transparent)]
#[derive(Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct SystemVirtualPath(str);

impl SystemVirtualPath {
    pub const fn new(path: &str) -> &SystemVirtualPath {
        // SAFETY: SystemVirtualPath is marked as #[repr(transparent)] so the conversion from a
        // *const str to a *const SystemVirtualPath is valid.
        unsafe { &*(path as *const str as *const SystemVirtualPath) }
    }

    /// Converts the path to an owned [`SystemVirtualPathBuf`].
    pub fn to_path_buf(&self) -> SystemVirtualPathBuf {
        SystemVirtualPathBuf(self.0.to_string())
    }

    /// Extracts the file extension, if possible.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruff_db::system::SystemVirtualPath;
    ///
    /// assert_eq!(None, SystemVirtualPath::new("untitled:Untitled-1").extension());
    /// assert_eq!("ipynb", SystemVirtualPath::new("untitled:Untitled-1.ipynb").extension().unwrap());
    /// assert_eq!("ipynb", SystemVirtualPath::new("vscode-notebook-cell:Untitled-1.ipynb").extension().unwrap());
    /// ```
    ///
    /// See [`Path::extension`] for more details.
    pub fn extension(&self) -> Option<&str> {
        Path::new(&self.0).extension().and_then(|ext| ext.to_str())
    }

    /// Returns the path as a string slice.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// An owned, virtual path on [`System`](`super::System`) (akin to [`String`]).
#[derive(Eq, PartialEq, Clone, Hash, PartialOrd, Ord, get_size2::GetSize)]
pub struct SystemVirtualPathBuf(String);

impl SystemVirtualPathBuf {
    #[inline]
    pub const fn as_path(&self) -> &SystemVirtualPath {
        SystemVirtualPath::new(self.0.as_str())
    }
}

impl From<&SystemVirtualPath> for Box<SystemVirtualPath> {
    fn from(path: &SystemVirtualPath) -> Self {
        Box::from(path.to_path_buf())
    }
}

impl From<SystemVirtualPathBuf> for Box<SystemVirtualPath> {
    fn from(path: SystemVirtualPathBuf) -> Self {
        let path = Box::into_raw(path.0.into_boxed_str()) as *mut SystemVirtualPath;
        // SAFETY: SystemVirtualPath is marked as #[repr(transparent)] so the conversion from a
        // *mut str to a *mut SystemVirtualPath is valid.
        unsafe { Box::from_raw(path) }
    }
}

impl Clone for Box<SystemVirtualPath> {
    fn clone(&self) -> Self {
        Box::from(&**self)
    }
}

impl get_size2::GetSize for Box<SystemVirtualPath> {
    fn get_heap_size_with_tracker<T: get_size2::GetSizeTracker>(&self, tracker: T) -> (usize, T) {
        (std::mem::size_of_val(&**self), tracker)
    }
}

impl From<String> for SystemVirtualPathBuf {
    fn from(value: String) -> Self {
        SystemVirtualPathBuf(value)
    }
}

impl AsRef<SystemVirtualPath> for SystemVirtualPathBuf {
    #[inline]
    fn as_ref(&self) -> &SystemVirtualPath {
        self.as_path()
    }
}

impl AsRef<SystemVirtualPath> for SystemVirtualPath {
    #[inline]
    fn as_ref(&self) -> &SystemVirtualPath {
        self
    }
}

impl AsRef<SystemVirtualPath> for str {
    #[inline]
    fn as_ref(&self) -> &SystemVirtualPath {
        SystemVirtualPath::new(self)
    }
}

impl AsRef<SystemVirtualPath> for String {
    #[inline]
    fn as_ref(&self) -> &SystemVirtualPath {
        SystemVirtualPath::new(self)
    }
}

impl Deref for SystemVirtualPathBuf {
    type Target = SystemVirtualPath;

    fn deref(&self) -> &Self::Target {
        self.as_path()
    }
}

impl std::fmt::Debug for SystemVirtualPath {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl std::fmt::Display for SystemVirtualPath {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl std::fmt::Debug for SystemVirtualPathBuf {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl std::fmt::Display for SystemVirtualPathBuf {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(feature = "cache")]
impl ruff_cache::CacheKey for SystemVirtualPath {
    fn cache_key(&self, hasher: &mut ruff_cache::CacheKeyHasher) {
        self.as_str().cache_key(hasher);
    }
}

#[cfg(feature = "cache")]
impl ruff_cache::CacheKey for SystemVirtualPathBuf {
    fn cache_key(&self, hasher: &mut ruff_cache::CacheKeyHasher) {
        self.as_path().cache_key(hasher);
    }
}

impl Borrow<SystemVirtualPath> for SystemVirtualPathBuf {
    fn borrow(&self) -> &SystemVirtualPath {
        self.as_path()
    }
}

/// Deduplicates identical paths and removes nested paths.
///
/// # Examples
/// ```rust
/// use ruff_db::system::{SystemPath, deduplicate_nested_paths};///
///
/// let paths = vec![SystemPath::new("/a/b/c"), SystemPath::new("/a/b"), SystemPath::new("/a/beta"), SystemPath::new("/a/b/c")];
/// assert_eq!(deduplicate_nested_paths(paths).collect::<Vec<_>>(), &[SystemPath::new("/a/b"), SystemPath::new("/a/beta")]);
/// ```
pub fn deduplicate_nested_paths<P, I>(paths: I) -> DeduplicatedNestedPathsIter<P>
where
    I: IntoIterator<Item = P>,
    P: AsRef<SystemPath>,
{
    DeduplicatedNestedPathsIter::new(paths)
}

pub struct DeduplicatedNestedPathsIter<P> {
    inner: std::vec::IntoIter<P>,
    next: Option<P>,
}

impl<P> DeduplicatedNestedPathsIter<P>
where
    P: AsRef<SystemPath>,
{
    fn new<I>(paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
    {
        let mut paths = paths.into_iter().collect::<Vec<_>>();
        // Sort the path to ensure that e.g. `/a/b/c`, comes right after `/a/b`.
        paths.sort_unstable_by(|left, right| left.as_ref().cmp(right.as_ref()));

        let mut iter = paths.into_iter();

        Self {
            next: iter.next(),
            inner: iter,
        }
    }
}

impl<P> Iterator for DeduplicatedNestedPathsIter<P>
where
    P: AsRef<SystemPath>,
{
    type Item = P;

    fn next(&mut self) -> Option<Self::Item> {
        let current = self.next.take()?;

        for next in self.inner.by_ref() {
            // Skip all paths that have the same prefix as the current path
            if !next.as_ref().starts_with(current.as_ref()) {
                self.next = Some(next);
                break;
            }
        }

        Some(current)
    }
}