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
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Types for representing block paths. The [BlockPath] type is an owned path similar to
//! [std::path::PathBuf] while [BlockPathRef] is a borrowed version similar to [std::path::Path].
//! Both of these types can be dereferenced to a [GenBlockPath] which is generic over a type
//! which is `AsRef<str>`.

use crate::{
    crypto::{BtHasher, HashKind},
    Principal, Result,
};
use core::hash::Hash;
use serde::{
    de::{self, Visitor},
    Deserialize, Deserializer, Serialize, Serializer,
};
use std::{
    fmt::{Display, Write},
    hash::Hasher,
    ops::{Deref, DerefMut},
    result::Result as StdResult,
};

pub use private::{
    BlockPath, BlockPathError, BlockPathGen, BlockPathRef, Components, RelBlockPath,
};

mod private {
    use std::str::FromStr;

    use super::*;

    /// An owned identifier for a block in a tree.
    #[derive(Debug, Clone, Default)]
    pub struct BlockPath(BlockPathGen<String>);

    impl BlockPath {
        /// The character that is used to separate path components.  pub const SEP: char = '/';
        pub const SEP: char = '/';
        /// The limit, in bytes, to a path's length.
        pub const BYTE_LIMIT: usize = 4096;

        /// Returns a path with the given root and the given components.
        pub fn new(path: String) -> StdResult<BlockPath, BlockPathError> {
            Ok(Self(BlockPathGen::new(path)?))
        }

        /// Creates a [BlockPath] which contains the given root and components.
        pub fn from_components<'a, I: Iterator<Item = &'a str>>(
            root: Principal,
            components: I,
        ) -> Self {
            Self(BlockPathGen::from_components(root, components))
        }

        /// Returns a reference to this block path.
        pub fn borrow(&self) -> BlockPathRef<'_> {
            BlockPathRef(self.0.borrow())
        }
    }

    impl Deref for BlockPath {
        type Target = BlockPathGen<String>;

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

    impl DerefMut for BlockPath {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.0
        }
    }

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

    impl TryFrom<String> for BlockPath {
        type Error = BlockPathError;

        fn try_from(value: String) -> StdResult<Self, Self::Error> {
            Ok(Self(BlockPathGen::try_from(value)?))
        }
    }

    impl<'a> TryFrom<&'a str> for BlockPath {
        type Error = BlockPathError;

        fn try_from(value: &'a str) -> StdResult<Self, Self::Error> {
            Ok(Self(BlockPathGen::try_from(value.to_owned())?))
        }
    }

    impl FromStr for BlockPath {
        type Err = BlockPathError;

        fn from_str(s: &str) -> StdResult<Self, Self::Err> {
            Self::try_from(s)
        }
    }

    impl Serialize for BlockPath {
        fn serialize<S: Serializer>(&self, serializer: S) -> StdResult<S::Ok, S::Error> {
            self.deref().serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for BlockPath {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
            Ok(Self(BlockPathGen::deserialize(deserializer)?))
        }
    }

    impl PartialEq for BlockPath {
        fn eq(&self, other: &Self) -> bool {
            self.deref().eq(other.deref())
        }
    }

    impl Eq for BlockPath {}

    impl PartialOrd for BlockPath {
        fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
            self.deref().partial_cmp(other.deref())
        }
    }

    impl Ord for BlockPath {
        fn cmp(&self, other: &Self) -> std::cmp::Ordering {
            self.deref().cmp(other.deref())
        }
    }

    impl<T: AsRef<str>> PartialEq<T> for BlockPath {
        fn eq(&self, other: &T) -> bool {
            self.deref().eq(&other.as_ref())
        }
    }

    impl Hash for BlockPath {
        fn hash<H: Hasher>(&self, state: &mut H) {
            self.deref().hash(state)
        }
    }

    /// A reference to a block path.
    ///
    /// [BlockPathRef] is to [BlockPath] as [std::path::Path] is to [std::path::PathBuf].
    #[derive(Debug, Clone, Default)]
    pub struct BlockPathRef<'a>(BlockPathGen<&'a str>);

    impl<'a> BlockPathRef<'a> {
        /// Creates a new [BlockPathRef] which references the path described by `path`.
        pub fn new(path: &'a str) -> StdResult<BlockPathRef, BlockPathError> {
            Ok(Self(BlockPathGen::new(path)?))
        }
    }

    impl<'a> Deref for BlockPathRef<'a> {
        type Target = BlockPathGen<&'a str>;

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

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

    impl<'a> TryFrom<&'a str> for BlockPathRef<'a> {
        type Error = BlockPathError;

        fn try_from(string: &'a str) -> StdResult<BlockPathRef, BlockPathError> {
            Ok(Self(BlockPathGen::try_from(string)?))
        }
    }

    impl<'a> Serialize for BlockPathRef<'a> {
        fn serialize<S: Serializer>(&self, serializer: S) -> StdResult<S::Ok, S::Error> {
            self.deref().serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for BlockPathRef<'de> {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
            Ok(Self(BlockPathGen::deserialize(deserializer)?))
        }
    }

    impl<'a> PartialEq for BlockPathRef<'a> {
        fn eq(&self, other: &Self) -> bool {
            self.deref().eq(other.deref())
        }
    }

    impl<'a> Eq for BlockPathRef<'a> {}

    impl<'a> PartialOrd for BlockPathRef<'a> {
        fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
            self.deref().partial_cmp(other.deref())
        }
    }

    impl<'a> Ord for BlockPathRef<'a> {
        fn cmp(&self, other: &Self) -> std::cmp::Ordering {
            self.deref().cmp(other.deref())
        }
    }

    impl<'a, T: AsRef<str>> PartialEq<T> for BlockPathRef<'a> {
        fn eq(&self, other: &T) -> bool {
            self.deref().eq(&other.as_ref())
        }
    }

    impl<'a> Hash for BlockPathRef<'a> {
        fn hash<H: Hasher>(&self, state: &mut H) {
            self.deref().hash(state)
        }
    }

    /// A generic block path.
    ///
    /// This type serves to unify the functionality of [BlockPath] and [BlockPathRef].
    #[derive(Debug, Clone, Default)]
    pub struct BlockPathGen<T> {
        root: Principal,
        begin_rel_part: usize,
        path: T,
    }

    impl<T: AsRef<str>> BlockPathGen<T> {
        /// Parses the given path.
        fn new(path: T) -> StdResult<Self, BlockPathError> {
            let path_str = path.as_ref();
            Self::assert_not_too_long(path_str)?;
            let mut components = path_str.split(BlockPath::SEP);
            if let Some("") = components.next() {
                // The string did start with the separator and so is absolute.
            } else {
                return Err(BlockPathError::NotAbsolute);
            }
            let root_str = components
                .next()
                .ok_or(BlockPathError::InvalidLeadingComponent)?;
            let root = Principal::try_from(root_str)
                .map_err(|_| BlockPathError::InvalidLeadingComponent)?;
            let begin_rel_path = 2 * BlockPath::SEP.len_utf8() + root_str.len();
            Ok(Self {
                root,
                begin_rel_part: begin_rel_path,
                path,
            })
        }

        /// Asserts that the number of bytes in the given string is no more than `Path::BYTE_LIMIT`.
        fn assert_not_too_long(string: &str) -> StdResult<(), BlockPathError> {
            let len = string.len();
            if len <= BlockPath::BYTE_LIMIT {
                Ok(())
            } else {
                Err(BlockPathError::PathTooLong(len))
            }
        }

        /// Returns true if `other` is a subpath of this path.
        pub fn contains<U: AsRef<str>>(&self, other: &BlockPathGen<U>) -> bool {
            if self.root != other.root {
                return false;
            };
            other.path.as_ref().starts_with(self.path.as_ref())
        }

        /// Returns a reference to the root of this path.
        pub fn root(&self) -> &Principal {
            &self.root
        }

        /// Returns a reference to the beginning of the relative part of this path, if it exists.
        /// The relative part begins at the start of the second component.
        fn rel_part(&self) -> Option<&str> {
            let path_str = self.path.as_ref();
            if self.begin_rel_part < path_str.len() {
                Some(&path_str[self.begin_rel_part..])
            } else {
                None
            }
        }

        /// Returns an iterator over the components in this path.
        pub fn components(&self) -> Components<'_> {
            if let Some(rel) = self.rel_part() {
                Components::Split(rel.split(BlockPath::SEP))
            } else if self.path.as_ref().ends_with(BlockPath::SEP) {
                Components::Split("".split(BlockPath::SEP))
            } else {
                Components::Empty
            }
        }

        /// Calculates the [RelBlockPath] representing this path relative to `rel_to`.
        pub fn relative_to<'a, U: AsRef<str>>(
            &'a self,
            rel_to: &BlockPathGen<U>,
        ) -> Result<RelBlockPath<'a>> {
            let self_str = self.path.as_ref();
            let other_str = rel_to.path.as_ref();
            if self_str.starts_with(other_str) {
                let start = self_str.len().min(other_str.len() + 1);
                let rel_path = &self_str[start..];
                Ok(RelBlockPath(rel_path))
            } else {
                Err(BlockPathError::NotContained.into())
            }
        }

        /// Returns the port to use if this path is used as the bind path of a process.
        pub fn port(&self) -> Result<u16> {
            let mut hasher = BtHasher::new(HashKind::Sha2_256)?;
            self.hash(&mut hasher);
            let hash = hasher.finish();
            // We compute a port in the dynamic range [49152, 65535] as defined by RFC 6335.
            const NUM_RES_PORTS: u16 = 49153;
            const PORTS_AVAIL: u64 = (u16::MAX - NUM_RES_PORTS) as u64;
            let port = NUM_RES_PORTS + (hash % PORTS_AVAIL) as u16;
            Ok(port)
        }
    }

    impl BlockPathGen<String> {
        fn from_components<'a, I: Iterator<Item = &'a str>>(
            root: Principal,
            components: I,
        ) -> Self {
            let mut path = String::new();
            // The `std::fmt::Write` implementation for `String` always returns `Ok`, and the
            // `Display` implementation for `Principal` always returns this value. Thus this is
            // safe to unwrap.
            write!(path, "{}{}", BlockPath::SEP, root).unwrap();
            let begin_rel_path = path.len() + BlockPath::SEP.len_utf8();
            for component in components {
                write!(path, "{}{}", BlockPath::SEP, component).unwrap();
            }
            Self {
                root,
                begin_rel_part: begin_rel_path,
                path,
            }
        }

        fn borrow(&self) -> BlockPathGen<&'_ str> {
            BlockPathGen {
                root: self.root.clone(),
                begin_rel_part: self.begin_rel_part,
                path: self.path.as_str(),
            }
        }

        /// Sets the `new_root` as the root of this path.
        pub fn set_root(&mut self, new_root: Principal) {
            self.root = new_root;
            if let Some(rel) = self.rel_part() {
                let rel = rel.to_owned();
                self.path.truncate(0);
                write!(
                    self.path,
                    "{}{}{}{}",
                    BlockPath::SEP,
                    self.root,
                    BlockPath::SEP,
                    rel
                )
                .unwrap();
            } else {
                self.path.truncate(0);
                write!(self.path, "{}{}", BlockPath::SEP, self.root).unwrap();
            }
        }

        /// Pushes the given component onto the end of this path. The [Display] trait is used to
        /// write the component at the end of this path.
        pub fn push_component<T: Display>(&mut self, component: T) {
            if !self.path.ends_with(BlockPath::SEP) {
                self.path.push(BlockPath::SEP);
            }
            write!(self.path, "{component}").unwrap();
        }

        /// Removes the last component from this path. If there are no components (the path only
        /// has the root), then this method leaves the path unchanged.
        pub fn pop_component(&mut self) {
            if let Some((remaining, _)) = self.path.rsplit_once(BlockPath::SEP) {
                if self.begin_rel_part <= remaining.len() + BlockPath::SEP.len_utf8() {
                    self.path.truncate(remaining.len())
                }
            }
        }
    }

    impl<T: AsRef<str>> Display for BlockPathGen<T> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str(self.path.as_ref())
        }
    }

    impl<'s> TryFrom<&'s str> for BlockPathGen<&'s str> {
        type Error = BlockPathError;

        fn try_from(value: &'s str) -> StdResult<Self, Self::Error> {
            Self::new(value)
        }
    }

    impl TryFrom<String> for BlockPathGen<String> {
        type Error = BlockPathError;

        fn try_from(value: String) -> StdResult<Self, Self::Error> {
            Self::new(value)
        }
    }

    impl<T: AsRef<str>> Serialize for BlockPathGen<T> {
        fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
            serializer.collect_str(self)
        }
    }

    impl<'de> Deserialize<'de> for BlockPathGen<String> {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
            struct GenBlockPathVisitor;

            impl<'a> Visitor<'a> for GenBlockPathVisitor {
                type Value = BlockPathGen<String>;

                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                    formatter.write_str("a string containing a block path")
                }

                fn visit_string<E: de::Error>(self, v: String) -> StdResult<Self::Value, E> {
                    BlockPathGen::new(v).map_err(de::Error::custom)
                }

                fn visit_str<E: de::Error>(self, v: &str) -> StdResult<Self::Value, E> {
                    self.visit_string(v.to_owned())
                }
            }

            deserializer.deserialize_string(GenBlockPathVisitor)
        }
    }

    impl<'de> Deserialize<'de> for BlockPathGen<&'de str> {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
            struct GenBlockPathVisitor;

            impl<'a> Visitor<'a> for GenBlockPathVisitor {
                type Value = BlockPathGen<&'a str>;

                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                    formatter.write_str("a string containing a block path")
                }

                fn visit_borrowed_str<E: de::Error>(self, v: &'a str) -> StdResult<Self::Value, E> {
                    BlockPathGen::new(v).map_err(de::Error::custom)
                }
            }

            deserializer.deserialize_str(GenBlockPathVisitor)
        }
    }

    impl<T: AsRef<str>> PartialEq for BlockPathGen<T> {
        fn eq(&self, other: &Self) -> bool {
            self.path.as_ref() == other.path.as_ref()
        }
    }

    impl<T: AsRef<str>> Eq for BlockPathGen<T> {}

    impl<T: AsRef<str>> PartialOrd for BlockPathGen<T> {
        fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
            self.path.as_ref().partial_cmp(other.path.as_ref())
        }
    }

    impl<T: AsRef<str>> Ord for BlockPathGen<T> {
        fn cmp(&self, other: &Self) -> std::cmp::Ordering {
            self.path.as_ref().cmp(other.path.as_ref())
        }
    }

    impl<T: AsRef<str>, U: AsRef<str>> PartialEq<U> for BlockPathGen<T> {
        fn eq(&self, other: &U) -> bool {
            self.path.as_ref() == other.as_ref()
        }
    }

    impl<T: AsRef<str>> Hash for BlockPathGen<T> {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write(self.path.as_ref().as_bytes())
        }
    }

    /// Represents a relative block path.
    #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Default, Hash)]
    pub struct RelBlockPath<'a>(&'a str);

    impl<'a> RelBlockPath<'a> {
        /// Creates a new [RelBlockPath] containing the given string.
        pub fn new(rel_path: &'a str) -> StdResult<Self, BlockPathError> {
            if rel_path.starts_with(BlockPath::SEP) {
                return Err(BlockPathError::NotRelative);
            }
            Ok(Self(rel_path))
        }

        /// Returns an iterator over the components of this relative path.
        pub fn components(&self) -> impl DoubleEndedIterator<Item = &str> {
            self.0.split(BlockPath::SEP)
        }

        /// Creates a `RelBlockPath` with no components.
        pub fn empty() -> Self {
            Self::default()
        }
    }

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

    impl<'a> TryFrom<&'a str> for RelBlockPath<'a> {
        type Error = BlockPathError;

        fn try_from(value: &'a str) -> std::result::Result<Self, Self::Error> {
            Self::new(value)
        }
    }

    impl<'a> TryFrom<&'a String> for RelBlockPath<'a> {
        type Error = BlockPathError;

        fn try_from(value: &'a String) -> StdResult<Self, Self::Error> {
            Self::new(value.as_str())
        }
    }

    impl<'a, T: AsRef<str>> PartialEq<T> for RelBlockPath<'a> {
        fn eq(&self, other: &T) -> bool {
            self.0 == other.as_ref()
        }
    }

    /// Iterator over the components of a block path.
    pub enum Components<'a> {
        Split(std::str::Split<'a, char>),
        Empty,
    }

    impl<'a> Iterator for Components<'a> {
        type Item = &'a str;
        fn next(&mut self) -> Option<Self::Item> {
            match self {
                Self::Split(split) => split.next(),
                Self::Empty => None,
            }
        }
    }

    impl<'a> DoubleEndedIterator for Components<'a> {
        fn next_back(&mut self) -> Option<Self::Item> {
            match self {
                Self::Split(split) => split.next_back(),
                Self::Empty => None,
            }
        }
    }

    /// Errors which can occur when converting a string to a `Path`.
    #[derive(Debug, PartialEq, Eq)]
    pub enum BlockPathError {
        /// Occurs when the number of bytes in a string is greater than `Path::BYTE_LIMIT`.
        PathTooLong(usize),
        /// Indicates that a path string was empty.
        Empty,
        /// Occurs when the leading component of a path is not in the correct format.
        InvalidLeadingComponent,
        /// Occurs when one path was expected to be contained in another, but that was not the case.
        NotContained,
        /// Indicates that a relative path was expected, but an absolute path was encountered.
        NotRelative,
        /// Indicates that an absolute path was expected, but a relative path was encountered.
        NotAbsolute,
    }

    impl Display for BlockPathError {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                BlockPathError::PathTooLong(length) => formatter.write_fmt(format_args!(
                    "path contained {} bytes, which is over the {} byte limit",
                    length,
                    BlockPath::BYTE_LIMIT
                )),
                BlockPathError::Empty => formatter.write_str("path was empty"),
                BlockPathError::InvalidLeadingComponent => {
                    formatter.write_str("invalid leading path component")
                }
                BlockPathError::NotContained => {
                    formatter.write_str("one path was not contained in another")
                }
                BlockPathError::NotRelative => formatter.write_str("expected a relative path"),
                BlockPathError::NotAbsolute => formatter.write_str("expected an absolute path"),
            }
        }
    }

    impl std::error::Error for BlockPathError {}
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::{
        test_helpers::{make_path, make_principal, PRINCIPAL2},
        VarHash,
    };

    fn path_new_test_case(
        expected: StdResult<BlockPath, BlockPathError>,
        input: String,
    ) -> StdResult<(), BlockPathError> {
        let result = BlockPath::new(input);
        assert_eq!(expected, result);
        Ok(())
    }

    #[test]
    fn path_new_multiple_components_ok() -> StdResult<(), BlockPathError> {
        let expected = make_path(["red", "green", "blue"].into_iter());
        let input = format!("/{}/red/green/blue", expected.root());
        path_new_test_case(Ok(expected), input)
    }

    #[test]
    fn path_new_one_component_ok() -> StdResult<(), BlockPathError> {
        let expected = make_path(std::iter::empty());
        let input = format!("/{}", expected.root());
        path_new_test_case(Ok(expected), input)
    }

    #[test]
    fn path_new_trailing_slash_ok() -> StdResult<(), BlockPathError> {
        // Notice the empty component at the end of this path due to the trailing slash.
        let expected = make_path(["orange", "banana", "shotgun", ""].into_iter());
        let input = format!("/{}/orange/banana/shotgun/", expected.root());
        path_new_test_case(Ok(expected), input)
    }

    #[test]
    fn path_new_path_too_long_fail() -> StdResult<(), BlockPathError> {
        let principal = make_principal();
        let input = format!("/{}/{}", principal, "*".repeat(4097));
        let expected = Err(BlockPathError::PathTooLong(input.len()));
        path_new_test_case(expected, input)
    }

    #[test]
    fn path_new_no_leading_slash_fail() -> StdResult<(), BlockPathError> {
        let expected = Err(BlockPathError::NotAbsolute);
        let principal = make_principal();
        let input = format!("{}", principal);
        path_new_test_case(expected, input)
    }

    #[test]
    fn path_round_trip() -> StdResult<(), BlockPathError> {
        let expected = make_path(["interstitial", "inter-related", "intersections"].into_iter());
        let string = expected.to_string();
        let actual = BlockPath::new(string)?;
        assert_eq!(expected, actual);
        Ok(())
    }

    #[test]
    fn path_from_components() {
        let expected_root = make_principal();
        let expected_components = ["first", "second"];
        let actual =
            BlockPath::from_components(expected_root.clone(), expected_components.into_iter());
        assert_eq!(&expected_root, actual.root());
        assert!(expected_components.into_iter().eq(actual.components()));
    }

    #[test]
    fn path_contains_true() {
        let larger = make_path(["apps"].into_iter());
        let smaller = make_path(["apps", "bohdi"].into_iter());
        assert!(larger.contains(&smaller));
    }

    #[test]
    fn path_contains_true_only_owner() {
        let larger = make_path(std::iter::empty());
        let smaller = make_path(std::iter::empty());
        assert!(larger.contains(&smaller));
    }

    #[test]
    fn path_contains_false_self_is_longer() {
        let first = make_path(["apps", "bohdi"].into_iter());
        let second = make_path(["apps"].into_iter());
        assert!(!first.contains(&second));
    }

    #[test]
    fn path_contains_false_same_owners() {
        let first = make_path(["apps"].into_iter());
        let second = make_path(["nodes"].into_iter());
        assert!(!first.contains(&second));
    }

    #[test]
    fn path_contains_false_different_owners() {
        let first = make_path(["apps"].into_iter());
        let mut second = make_path(["apps"].into_iter());
        second.set_root(Principal(VarHash::Sha2_256(PRINCIPAL2.into())));
        assert!(!first.contains(&second));
    }

    #[test]
    fn path_set_root_no_components() {
        let expected = Principal::default();
        let mut path = make_path(std::iter::empty());
        assert_ne!(&expected, path.root());
        path.set_root(expected.clone());
        assert_eq!(&expected, path.root());
        assert_eq!(path, format!("/{}", expected));
    }

    #[test]
    fn path_set_root_with_components() {
        let original = make_principal();
        let new = Principal::default();
        let expected = format!("/{}/first/second", new);
        let mut path = BlockPath::new(format!("/{}/first/second", original)).unwrap();
        assert_ne!(&new, path.root());
        path.set_root(new.clone());
        assert_eq!(&new, path.root());
        assert_eq!(path, expected)
    }

    #[test]
    fn components_multiple() {
        let expected = ["first", "second"];
        let path = make_path(expected.into_iter());
        let actual = path.components();
        assert!(expected.into_iter().eq(actual));
    }

    #[test]
    fn components_multiple_with_trailing_slash() {
        let expected = ["first", ""];
        let path = BlockPath::new(format!("/{}/first/", make_principal())).unwrap();
        let actual = path.components();
        assert!(expected.into_iter().eq(actual));
    }

    #[test]
    fn components_single_empty() {
        let expected = [""];
        let path = BlockPath::new(format!("/{}/", make_principal())).unwrap();
        let actual = path.components();
        assert!(expected.into_iter().eq(actual));
    }

    #[test]
    fn components_none() {
        let empty = std::iter::empty::<&str>();
        let path = BlockPath::new(format!("/{}", make_principal())).unwrap();
        let actual = path.components();
        assert!(empty.eq(actual));
    }

    #[test]
    fn push_component_when_component_already_present() {
        let mut path = make_path(["first"].into_iter());
        path.push_component("second");
        assert_eq!(path, format!("/{}/first/second", path.root()));
    }

    #[test]
    fn push_component_when_no_component_present() {
        let mut path = make_path(std::iter::empty());
        let root = path.root().clone();
        path.push_component("first");
        assert_eq!(path, format!("/{}/first", root));
    }

    #[test]
    fn push_component_path_ends_with_sep() {
        let mut path = make_path([""].into_iter());
        let root = path.root().clone();
        path.push_component("component");
        assert_eq!(path, format!("/{}/component", root));
    }

    #[test]
    fn path_pop_component_single_component() {
        let mut path = make_path(["first"].into_iter());
        let root = path.root().clone();
        path.pop_component();
        assert_eq!(path, format!("/{}", root));
    }

    #[test]
    fn path_pop_component_two_components() {
        let mut path = make_path(["first", "second"].into_iter());
        let root = path.root().clone();
        path.pop_component();
        assert_eq!(path, format!("/{}/first", root));
    }

    #[test]
    fn path_pop_component_no_components() {
        let mut path = make_path(std::iter::empty());
        let root = path.root().clone();
        path.pop_component();
        assert_eq!(path, format!("/{}", root));
    }

    #[test]
    fn path_pop_component_empty_path() {
        let mut path = make_path(std::iter::empty());
        let root = path.root().clone();
        path.pop_component();
        path.pop_component();
        assert_eq!(path, format!("/{}", root));
    }

    #[test]
    fn relative_to_self_contained_in_rel_to() {
        let sich = make_path(["sub", "alpha", "sub", "beta"].into_iter());
        let rel_to = make_path(["sub", "alpha"].into_iter());

        let relative = sich.relative_to(&rel_to).unwrap();

        assert_eq!(relative, "sub/beta");
    }

    #[test]
    fn relative_to_no_difference_is_ok() {
        let sich = make_path(["sub", "alpha"].into_iter());
        let rel_to = make_path(["sub", "alpha"].into_iter());

        let relative = sich.relative_to(&rel_to).unwrap();

        assert_eq!(relative, "");
    }

    #[test]
    fn relative_to_roots_differ_is_err() {
        let sich = make_path(["etc"].into_iter());
        let mut rel_to = make_path(["etc"].into_iter());
        let default = Principal::default();
        assert_ne!(sich.root(), &default);
        rel_to.set_root(default);

        let result = sich.relative_to(&rel_to);

        let err = result.err().unwrap().downcast::<BlockPathError>().unwrap();
        let matched = if let BlockPathError::NotContained = err {
            true
        } else {
            false
        };
        assert!(matched)
    }

    #[test]
    fn relative_to_self_shorter_is_err() {
        let sich = make_path(["etc"].into_iter());
        let rel_to = make_path(["etc", "fstab"].into_iter());

        let result = sich.relative_to(&rel_to);

        let err = result.err().unwrap().downcast::<BlockPathError>().unwrap();
        let matched = if let BlockPathError::NotContained = err {
            true
        } else {
            false
        };
        assert!(matched)
    }

    #[test]
    fn relative_to_not_contained_is_err() {
        let sich = make_path(["etc"].into_iter());
        let rel_to = make_path(["etsy"].into_iter());

        let result = sich.relative_to(&rel_to);

        let err = result.err().unwrap().downcast::<BlockPathError>().unwrap();
        let matched = if let BlockPathError::NotContained = err {
            true
        } else {
            false
        };
        assert!(matched)
    }
}