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
use std::borrow::Borrow;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs::Metadata;
use std::fs::ReadDir;
use std::io;
use std::mem;
use std::ops::Deref;
use std::path::Component;
use std::path::Components;
use std::path::Path;
use std::path::PathBuf;

use super::error::MissingPrefixBufError;
use super::error::MissingPrefixError;
use super::error::ParentError;
use super::imp;
use super::PathExt;

/// A path that has a [prefix] on Windows.
///
/// Note that comparison traits such as [`PartialEq`] will compare paths
/// literally instead of comparing components. The former is more efficient and
/// easier to use correctly.
///
/// # Safety
///
/// This type should not be used for memory safety, but implementations can
/// panic if this path is missing a prefix on Windows. A safe `new_unchecked`
/// method might be added later that can safely create invalid base paths.
///
/// Although this type is annotated with `#[repr(transparent)]`, the inner
/// representation is not stable. Transmuting between this type and any other
/// causes immediate undefined behavior.
///
/// [prefix]: ::std::path::Prefix
#[derive(Debug, Eq, Hash, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct BasePath(pub(super) OsStr);

impl BasePath {
    fn from_inner(path: &OsStr) -> &Self {
        // SAFETY: This struct has a layout that makes this operation safe.
        #[allow(clippy::transmute_ptr_to_ptr)]
        unsafe {
            mem::transmute(path)
        }
    }

    /// Creates a new base path.
    ///
    /// On Windows, if `path` is missing a [prefix], it will be joined to the
    /// current directory.
    ///
    /// # Errors
    ///
    /// Returns an error if reading the current directory fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::io;
    /// use std::path::Path;
    ///
    /// use normpath::BasePath;
    ///
    /// if cfg!(windows) {
    ///     let path = Path::new(r"X:\foo\bar");
    ///     assert_eq!(path, *BasePath::new(path)?);
    ///
    ///     assert!(BasePath::new(Path::new(r"foo\bar")).is_ok());
    /// }
    /// #
    /// # Ok::<_, io::Error>(())
    /// ```
    ///
    /// [prefix]: ::std::path::Prefix
    #[inline]
    pub fn new<'a, P>(path: P) -> io::Result<Cow<'a, Self>>
    where
        P: Into<Cow<'a, Path>>,
    {
        let path = path.into();
        match path {
            Cow::Borrowed(path) => Self::try_new(path)
                .map(Cow::Borrowed)
                .or_else(|_| imp::to_base(path).map(Cow::Owned)),
            Cow::Owned(path) => BasePathBuf::new(path).map(Cow::Owned),
        }
    }

    /// Creates a new base path.
    ///
    /// # Errors
    ///
    /// On Windows, returns an error if `path` is missing a [prefix].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// # use normpath::error::MissingPrefixError;
    /// use normpath::BasePath;
    ///
    /// if cfg!(windows) {
    ///     let path = r"X:\foo\bar";
    ///     assert_eq!(Path::new(path), BasePath::try_new(path)?);
    ///
    ///     assert!(BasePath::try_new(r"foo\bar").is_err());
    /// }
    /// #
    /// # Ok::<_, MissingPrefixError>(())
    /// ```
    ///
    /// [prefix]: ::std::path::Prefix
    #[inline]
    pub fn try_new<P>(path: &P) -> Result<&Self, MissingPrefixError>
    where
        P: AsRef<Path> + ?Sized,
    {
        let path = path.as_ref();
        if imp::is_base(path) {
            Ok(Self::from_inner(path.as_os_str()))
        } else {
            Err(MissingPrefixError(()))
        }
    }

    /// Returns a reference to the wrapped path as a platform string.
    #[inline]
    #[must_use]
    pub fn as_os_str(&self) -> &OsStr {
        &self.0
    }

    /// Returns a reference to the wrapped path.
    #[inline]
    #[must_use]
    pub fn as_path(&self) -> &Path {
        Path::new(&self.0)
    }

    /// Equivalent to [`Path::canonicalize`].
    #[inline]
    pub fn canonicalize(&self) -> io::Result<BasePathBuf> {
        self.as_path().canonicalize().map(|base| {
            debug_assert!(imp::is_base(&base));
            BasePathBuf(base.into_os_string())
        })
    }

    /// Equivalent to [`Path::components`].
    #[inline]
    #[must_use]
    pub fn components(&self) -> Components<'_> {
        self.as_path().components()
    }

    /// Equivalent to [`Path::ends_with`].
    #[inline]
    #[must_use]
    pub fn ends_with<P>(&self, child: P) -> bool
    where
        P: AsRef<Path>,
    {
        self.as_path().ends_with(child)
    }

    /// Equivalent to [`Path::exists`].
    #[inline]
    #[must_use]
    pub fn exists(&self) -> bool {
        self.as_path().exists()
    }

    /// Equivalent to [`Path::extension`].
    #[inline]
    #[must_use]
    pub fn extension(&self) -> Option<&OsStr> {
        self.as_path().extension()
    }

    /// Equivalent to [`Path::file_name`].
    #[inline]
    #[must_use]
    pub fn file_name(&self) -> Option<&OsStr> {
        self.as_path().file_name()
    }

    /// Equivalent to [`Path::file_stem`].
    #[inline]
    #[must_use]
    pub fn file_stem(&self) -> Option<&OsStr> {
        self.as_path().file_stem()
    }

    /// Equivalent to [`Path::has_root`].
    #[inline]
    #[must_use]
    pub fn has_root(&self) -> bool {
        self.as_path().has_root()
    }

    /// Equivalent to [`Path::is_absolute`].
    #[inline]
    #[must_use]
    pub fn is_absolute(&self) -> bool {
        self.as_path().is_absolute()
    }

    /// Equivalent to [`Path::is_dir`].
    #[inline]
    #[must_use]
    pub fn is_dir(&self) -> bool {
        self.as_path().is_dir()
    }

    /// Equivalent to [`Path::is_file`].
    #[inline]
    #[must_use]
    pub fn is_file(&self) -> bool {
        self.as_path().is_file()
    }

    /// Equivalent to [`Path::is_relative`].
    #[inline]
    #[must_use]
    pub fn is_relative(&self) -> bool {
        self.as_path().is_relative()
    }

    /// An improved version of [`Path::join`] that handles more edge cases.
    ///
    /// For example, on Windows, leading `.` and `..` components of `path` will
    /// be normalized if possible. If `self` is a [verbatim] path, it would be
    /// invalid to normalize them later.
    ///
    /// You should still call [`normalize`] before [`parent`] to normalize some
    /// additional components.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// use normpath::BasePath;
    ///
    /// if cfg!(windows) {
    ///     assert_eq!(
    ///         Path::new(r"\\?\foo\baz\test.rs"),
    ///         BasePath::try_new(r"\\?\foo\bar")
    ///             .unwrap()
    ///             .join("../baz/test.rs"),
    ///     );
    /// }
    /// ```
    ///
    /// [`normalize`]: Self::normalize
    /// [`parent`]: Self::parent
    /// [verbatim]: ::std::path::Prefix::is_verbatim
    #[inline]
    pub fn join<P>(&self, path: P) -> BasePathBuf
    where
        P: AsRef<Path>,
    {
        let mut base = self.to_owned();
        base.push(path);
        base
    }

    /// Equivalent to [`Path::metadata`].
    #[inline]
    pub fn metadata(&self) -> io::Result<Metadata> {
        self.as_path().metadata()
    }

    /// Equivalent to [`PathExt::normalize`].
    #[inline]
    pub fn normalize(&self) -> io::Result<BasePathBuf> {
        self.as_path().normalize()
    }

    /// Equivalent to [`PathExt::normalize_virtually`].
    #[cfg(any(doc, windows))]
    #[cfg_attr(normpath_docs_rs, doc(cfg(windows)))]
    #[inline]
    pub fn normalize_virtually(&self) -> io::Result<BasePathBuf> {
        self.as_path().normalize_virtually()
    }

    fn check_parent(&self) -> Result<(), ParentError> {
        self.components()
            .next_back()
            .filter(|x| matches!(x, Component::Normal(_) | Component::RootDir))
            .map(|_| ())
            .ok_or(ParentError(()))
    }

    /// Returns this path without its last component.
    ///
    /// Returns `Ok(None)` if the last component is [`Component::RootDir`].
    ///
    /// You should usually only call this method on [normalized] paths. They
    /// will prevent an unexpected path from being returned due to symlinks,
    /// and some `.` and `..` components will be normalized.
    ///
    /// # Errors
    ///
    /// Returns an error if the last component is not [`Component::Normal`] or
    /// [`Component::RootDir`]. To ignore this error, use [`parent_unchecked`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// # use normpath::error::ParentError;
    /// use normpath::BasePath;
    ///
    /// if cfg!(windows) {
    ///     assert_eq!(
    ///         Path::new(r"X:\foo"),
    ///         BasePath::try_new(r"X:\foo\bar").unwrap().parent()?.unwrap(),
    ///     );
    /// }
    /// #
    /// # Ok::<_, ParentError>(())
    /// ```
    ///
    /// [normalized]: Self::normalize
    /// [`parent_unchecked`]: Self::parent_unchecked
    #[inline]
    pub fn parent(&self) -> Result<Option<&Self>, ParentError> {
        self.check_parent().map(|()| self.parent_unchecked())
    }

    /// Equivalent to [`Path::parent`].
    ///
    /// It is usually better to use [`parent`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// use normpath::BasePath;
    ///
    /// if cfg!(windows) {
    ///     assert_eq!(
    ///         Path::new(r"X:\foo"),
    ///         BasePath::try_new(r"X:\foo\..")
    ///             .unwrap()
    ///             .parent_unchecked()
    ///             .unwrap(),
    ///     );
    /// }
    /// ```
    ///
    /// [`parent`]: Self::parent
    #[inline]
    #[must_use]
    pub fn parent_unchecked(&self) -> Option<&Self> {
        self.as_path()
            .parent()
            .map(|x| Self::from_inner(x.as_os_str()))
    }

    /// Equivalent to [`Path::read_dir`].
    #[inline]
    pub fn read_dir(&self) -> io::Result<ReadDir> {
        self.as_path().read_dir()
    }

    /// Equivalent to [`Path::read_link`].
    #[inline]
    pub fn read_link(&self) -> io::Result<PathBuf> {
        self.as_path().read_link()
    }

    /// Equivalent to [`Path::starts_with`].
    #[inline]
    #[must_use]
    pub fn starts_with<P>(&self, base: P) -> bool
    where
        P: AsRef<Path>,
    {
        self.as_path().starts_with(base)
    }

    /// Equivalent to [`Path::symlink_metadata`].
    #[inline]
    pub fn symlink_metadata(&self) -> io::Result<Metadata> {
        self.as_path().symlink_metadata()
    }
}

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

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

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

impl<'a> From<&'a BasePath> for Cow<'a, BasePath> {
    #[inline]
    fn from(value: &'a BasePath) -> Self {
        Cow::Borrowed(value)
    }
}

impl PartialEq<Path> for BasePath {
    #[inline]
    fn eq(&self, other: &Path) -> bool {
        &self.0 == other.as_os_str()
    }
}

impl PartialEq<BasePath> for Path {
    #[inline]
    fn eq(&self, other: &BasePath) -> bool {
        other == self
    }
}

impl PartialOrd<Path> for BasePath {
    #[inline]
    fn partial_cmp(&self, other: &Path) -> Option<Ordering> {
        self.0.partial_cmp(other.as_os_str())
    }
}

impl PartialOrd<BasePath> for Path {
    #[inline]
    fn partial_cmp(&self, other: &BasePath) -> Option<Ordering> {
        other.partial_cmp(self)
    }
}

impl ToOwned for BasePath {
    type Owned = BasePathBuf;

    #[inline]
    fn to_owned(&self) -> Self::Owned {
        BasePathBuf(self.0.to_os_string())
    }
}

/// An owned [`BasePath`].
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct BasePathBuf(pub(super) OsString);

impl BasePathBuf {
    /// Equivalent to [`BasePath::new`] but returns an owned path.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::io;
    /// use std::path::Path;
    ///
    /// use normpath::BasePathBuf;
    ///
    /// if cfg!(windows) {
    ///     let path = r"X:\foo\bar";
    ///     assert_eq!(Path::new(path), BasePathBuf::new(path)?);
    ///
    ///     assert!(BasePathBuf::new(r"foo\bar").is_ok());
    /// }
    /// #
    /// # Ok::<_, io::Error>(())
    /// ```
    #[inline]
    pub fn new<P>(path: P) -> io::Result<Self>
    where
        P: Into<PathBuf>,
    {
        Self::try_new(path).or_else(|x| imp::to_base(&x.0))
    }

    /// Equivalent to [`BasePath::try_new`] but returns an owned path.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// # use normpath::error::MissingPrefixBufError;
    /// use normpath::BasePathBuf;
    ///
    /// if cfg!(windows) {
    ///     let path = r"X:\foo\bar";
    ///     assert_eq!(Path::new(path), BasePathBuf::try_new(path)?);
    ///
    ///     assert!(BasePathBuf::try_new(r"foo\bar").is_err());
    /// }
    /// #
    /// # Ok::<_, MissingPrefixBufError>(())
    /// ```
    #[inline]
    pub fn try_new<P>(path: P) -> Result<Self, MissingPrefixBufError>
    where
        P: Into<PathBuf>,
    {
        let path = path.into();
        if imp::is_base(&path) {
            Ok(Self(path.into_os_string()))
        } else {
            Err(MissingPrefixBufError(path))
        }
    }

    /// Returns the wrapped path as a platform string.
    #[inline]
    #[must_use]
    pub fn into_os_string(self) -> OsString {
        self.0
    }

    /// Returns the wrapped path.
    #[inline]
    #[must_use]
    pub fn into_path_buf(self) -> PathBuf {
        self.0.into()
    }

    /// Equivalent to [`BasePath::parent`] but modifies `self` in place.
    ///
    /// Returns `Ok(false)` when [`BasePath::parent`] returns `Ok(None)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// # use normpath::error::ParentError;
    /// use normpath::BasePathBuf;
    ///
    /// if cfg!(windows) {
    ///     let mut path = BasePathBuf::try_new(r"X:\foo\bar").unwrap();
    ///     assert!(path.pop()?);
    ///     assert_eq!(Path::new(r"X:\foo"), path);
    /// }
    /// #
    /// # Ok::<_, ParentError>(())
    /// ```
    #[inline]
    pub fn pop(&mut self) -> Result<bool, ParentError> {
        self.check_parent().map(|()| self.pop_unchecked())
    }

    pub(super) fn replace_with<F>(&mut self, replace_fn: F)
    where
        F: FnOnce(PathBuf) -> PathBuf,
    {
        self.0 = replace_fn(mem::take(&mut self.0).into()).into_os_string();
    }

    /// Equivalent to [`PathBuf::pop`].
    ///
    /// It is usually better to use [`pop`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// use normpath::BasePathBuf;
    ///
    /// if cfg!(windows) {
    ///     let mut path = BasePathBuf::try_new(r"X:\foo\..").unwrap();
    ///     assert!(path.pop_unchecked());
    ///     assert_eq!(Path::new(r"X:\foo"), path);
    /// }
    /// ```
    ///
    /// [`pop`]: Self::pop
    #[inline]
    pub fn pop_unchecked(&mut self) -> bool {
        // This value is never used.
        let mut result = false;
        self.replace_with(|mut base| {
            result = base.pop();
            base
        });
        result
    }

    /// Equivalent to [`BasePath::join`] but modifies `self` in place.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// use normpath::BasePathBuf;
    ///
    /// if cfg!(windows) {
    ///     let mut path = BasePathBuf::try_new(r"\\?\foo\bar").unwrap();
    ///     path.push("../baz/test.rs");
    ///     assert_eq!(Path::new(r"\\?\foo\baz\test.rs"), path);
    /// }
    /// ```
    #[inline]
    pub fn push<P>(&mut self, path: P)
    where
        P: AsRef<Path>,
    {
        imp::push(self, path.as_ref());
    }
}

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

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

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

impl Borrow<BasePath> for BasePathBuf {
    #[inline]
    fn borrow(&self) -> &BasePath {
        self
    }
}

impl Deref for BasePathBuf {
    type Target = BasePath;

    #[inline]
    fn deref(&self) -> &BasePath {
        BasePath::from_inner(&self.0)
    }
}

impl From<BasePathBuf> for Cow<'_, BasePath> {
    #[inline]
    fn from(value: BasePathBuf) -> Self {
        Cow::Owned(value)
    }
}

impl From<BasePathBuf> for OsString {
    #[inline]
    fn from(value: BasePathBuf) -> Self {
        value.0
    }
}

impl From<BasePathBuf> for PathBuf {
    #[inline]
    fn from(value: BasePathBuf) -> Self {
        value.into_path_buf()
    }
}

#[cfg(feature = "print_bytes")]
mod print_bytes {
    use print_bytes::Bytes;
    use print_bytes::ToBytes;

    use super::BasePath;
    use super::BasePathBuf;

    impl ToBytes for BasePath {
        #[inline]
        fn to_bytes(&self) -> Bytes<'_> {
            self.0.to_bytes()
        }
    }

    impl ToBytes for BasePathBuf {
        #[inline]
        fn to_bytes(&self) -> Bytes<'_> {
            (**self).to_bytes()
        }
    }
}

#[cfg(feature = "serde")]
mod serde {
    use std::ffi::OsString;

    use serde::Deserialize;
    use serde::Deserializer;
    use serde::Serialize;
    use serde::Serializer;

    use super::BasePath;
    use super::BasePathBuf;

    impl<'de> Deserialize<'de> for BasePathBuf {
        #[inline]
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            OsString::deserialize(deserializer).map(Self)
        }
    }

    impl Serialize for BasePath {
        #[inline]
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.serialize_newtype_struct("BasePath", &self.0)
        }
    }

    impl Serialize for BasePathBuf {
        #[inline]
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.serialize_newtype_struct("BasePathBuf", &self.0)
        }
    }
}