gmi 0.2.1

A rust library to use the gemini protocol with an aim to be lightweight
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
//! A URL Library made specifically for Gemini clients
//!
//! This is a subset of [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.2)
//!
//! This URL library will NOT interpret anything more than
//! what is required for a Gemini client. These things are as
//! shown:
//!
//! Components that are required:
//! - Authority
//!   - Host
//!   - !userinfo
//!
//! Additional Information:
//! - Spaces should be percent encoded to %20
//!
//! Personal limitations:
//! - IPv6 hosts are not allowed

/// The main holder of a URL.
/// This consts of 4 parts:
/// - An optinal scheme (gemini://),
/// - An authority (example.com:1234),
/// - A path (hello/world.gmi)
/// - A query (?user=23)
///
/// An easy way to construct the Url struct is using `try_from()`
#[derive(Debug, Clone)]
pub struct Url {
    /// The scheme of the URL
    pub scheme: Option<String>,
    /// The authority of the URL
    pub authority: Authority,
    /// The path of the URL
    pub path: Option<Path>,
    /// The query portion of the URL
    pub query: Option<Query>,
}

impl core::fmt::Display for Url {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        // Print the scheme
        match &self.scheme {
            Some(s) => write!(f, "{}://", s)?,
            None => (),
        }
        // Then the authority
        write!(f, "{}", self.authority)?;
        // Then the path
        match &self.path {
            Some(p) => write!(f, "{}", p)?,
            None => (),
        }
        // Then the query
        match &self.query {
            Some(q) => write!(f, "{}", q)?,
            None => (),
        }
        Ok(())
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// An error during the parsing of a URL
pub enum UrlParseError {
    /// An error occured during the parsing of the authority
    /// part of the URL.
    AuthorityParseError(AuthorityParseError),
    /// The URL was empty
    EmptyURL,
}

impl core::fmt::Display for UrlParseError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            UrlParseError::AuthorityParseError(e) => write!(f, "URL parse error: {}", e),
            UrlParseError::EmptyURL => write!(f, "URL Parse error: Empty URL"),
        }
    }
}

impl std::error::Error for UrlParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            UrlParseError::AuthorityParseError(e) => Some(e),
            UrlParseError::EmptyURL => None,
        }
    }
}

impl core::convert::TryFrom<&str> for Url {
    type Error = UrlParseError;
    /// Parse a URL from a [`&str`] object.
    ///
    /// # Example:
    /// ```
    /// # use gmi::url::Url;
    /// # use gmi::url::UrlParseError;
    /// # fn main() -> Result<(), UrlParseError> {
    /// use std::convert::TryFrom;
    /// let url = Url::try_from("gemini://example.com")?;
    /// assert_eq!(url.scheme, Some(String::from("gemini")));
    /// assert_eq!(url.authority.host, "example.com");
    /// assert_eq!(url.path, None);
    /// assert_eq!(url.query, None);
    /// # Ok(())
    /// # }
    /// ```
    fn try_from(raw_url: &str) -> Result<Self, UrlParseError> {
        if raw_url.trim().is_empty() {
            return Err(UrlParseError::EmptyURL);
        }
        let raw_url = raw_url.trim();
        let mut scheme_ret: Option<String> = None;
        // Check if there's a scheme
        let remainder = match raw_url.split_once("://") {
            Some((s, u)) => {
                scheme_ret = Some(s.to_string());
                u
            }
            None => raw_url,
        };

        // Split off the path if there is any
        let (auth, path) = match remainder.split_once('/') {
            Some((a, p)) => (a, Some(p)),
            None => (remainder, None),
        };

        // Now we get the authority
        let authority = match Authority::try_from(auth) {
            Ok(a) => a,
            Err(e) => return Err(UrlParseError::AuthorityParseError(e)),
        };

        // Now we see if there's a path
        if path.is_none() {
            // There is none, and with no path, there also is no query,
            // so we'll just exit here
            return Ok(Self {
                scheme: scheme_ret,
                authority,
                path: None,
                query: None,
            });
        }

        let path = path.unwrap();

        // At this point there is a path, so we'll split off a query
        let (parsed_path, query_str) = match path.split_once('?') {
            Some((p, q)) => (Path::from(("/".to_string() + &p).as_ref()), Some(q)),
            None => (Path::from(("/".to_string() + &path).as_ref()), None),
        };

        // And now we get the query part, if it exists
        let query = match query_str {
            None => None,
            Some(q) => Some(Query::from(q)),
        };

        Ok(Self {
            scheme: scheme_ret,
            authority,
            path: Some(parsed_path),
            query,
        })
    }
}

/// An authority of a URL
///
/// An authority of a URL is essentially the
/// host of the URL. Think "example.com" or "127.0.0.1"
///
/// This can also optionally include a port number separated by a colon (:)
///
/// For more info see [section 3.2 of the
/// RFC](https://datatracker.ietf.org/doc/html/rfc3986#section-3.2)
///
/// # Constructing the struct
/// An easy way to construct this struct is to use `try_from()`
///
/// ## Example
/// ```
/// # use gmi::url::Authority;
/// # fn main() -> Result<(), gmi::url::AuthorityParseError> {
/// use std::convert::TryFrom;
/// let auth = Authority::try_from("example.com:1963")?;
/// assert_eq!(auth.port, Some(1963));
/// assert_eq!(auth.host, "example.com");
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct Authority {
    /// The host portion of the authority
    pub host: String,
    /// The optinal port of the authority
    pub port: Option<u16>,
}

impl core::fmt::Display for Authority {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(
            f,
            "{}{}",
            self.host,
            match self.port {
                Some(p) => String::from(":") + &p.to_string(),
                None => String::from(""),
            }
        )
    }
}

#[derive(Debug, Eq, PartialEq, Clone, Copy)]
/// A parsing error for the Authority
///
/// This enum contains various possible errors that can occur while
/// parsing an authority
pub enum AuthorityParseError {
    /// Occurs when a port cannot be parsed
    InvalidPort,
    /// Occurs when the authority is completely
    /// missing a host in the first place
    MissingHost,
}

impl core::fmt::Display for AuthorityParseError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            AuthorityParseError::InvalidPort => write!(f, "Error parsing authority: Invalid port"),
            AuthorityParseError::MissingHost => write!(f, "Error parsing authority: Missing host"),
        }
    }
}

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

impl core::convert::TryFrom<&str> for Authority {
    type Error = AuthorityParseError;
    fn try_from(s: &str) -> Result<Self, AuthorityParseError> {
        let host;
        let mut port = None;
        // Split once by colon
        if let Some(new_host) = s.split_once(':') {
            // Add the host
            host = String::from(new_host.0);
            // Get the port
            if !new_host.1.is_empty() {
                port = Some({
                    match new_host.1.parse::<u16>() {
                        Err(_) => return Err(AuthorityParseError::InvalidPort),
                        Ok(n) => n,
                    }
                })
            }
        } else {
            // The entire thing should be the host so let's do that
            host = s.to_string();
        }
        if host.is_empty() {
            return Err(AuthorityParseError::MissingHost);
        }
        Ok(Self { host, port })
    }
}

/// The path part of the URL.
///
/// This part is optional in a URL and specifies the specific resource to access
///
/// This implementation is based on the API of [`std::path::Path`]
///
/// # Constructing this struct
/// You can just use the `from()` implementations for this. You can also just
/// construct it from its raw parts, although I do not recommend it.
///
/// ## Example:
///```
/// # use gmi::url::Path;
/// # fn main() {
/// let path = Path::from("/help/me");
/// assert_eq!(path.to_string(), "/help/me");
/// # }
/// ```

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Path {
    /// The raw path string of the URL
    pub raw_path: String,
}

impl core::fmt::Display for Path {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.raw_path)
    }
}

impl From<&str> for Path {
    fn from(s: &str) -> Self {
        Self {
            raw_path: s.to_owned(),
        }
    }
}

impl Path {
    /// Returns a path with the parent part
    ///
    /// # Example
    /// ```
    /// # fn main() {
    /// use gmi::url::Path;
    /// assert_eq!(Path::from("/hi/hello/").parent(), Some(Path::from("/hi/")));
    /// # }
    /// ```
    pub fn parent(&self) -> Option<Self> {
        // If the path is the root, there is no parent
        if self.raw_path == "/" {
            return None;
        }
        // If the path is empty, there is no parent
        if self.raw_path == "" {
            return None;
        }
        let raw_path = {
            // Check if the path ends in a slash
            if self.raw_path.ends_with('/') {
                self.raw_path[..self.raw_path.len() - 1].to_owned()
            } else {
                self.raw_path.clone()
            }
        };
        // Split on the final / and give that back
        match raw_path.rsplit_once('/') {
            None => None,
            Some((parent,_)) => Some({
                let mut raw_path = parent.to_owned();
                raw_path.push('/');
                Self { raw_path }
            }),
        }
    }

    /// Returns true if the path is an absolute path
    ///
    /// # Example
    /// ```
    /// # use gmi::url::Path;
    /// # fn main() {
    /// let path = Path::from("/a/good/path");
    /// assert!(path.is_absolute());
    /// # }
    /// ```
    pub fn is_absolute(&self) -> bool {
        // This is actually pretty simple. A path is absolute if it begins with a slash
        self.raw_path.starts_with('/')
    }

    /// Returns true if the path is a relative path
    ///
    /// # Example
    /// ```
    /// # use gmi::url::Path;
    /// # fn main() {
    /// let path = Path::from("a/relative/path");
    /// assert!(path.is_relative());
    /// # }
    /// ```
    pub fn is_relative(&self) -> bool {
        !self.is_absolute()
    }

    /// Returns the file name with no associated hierarchy
    ///
    /// # Example
    /// ```
    /// # fn main() {
    /// use gmi::url::Path;
    /// assert_eq!(Path::from("/help/me.hi").file_name(), Some("me.hi"));
    /// # }
    /// ```
    pub fn file_name(&self) -> Option<&str> {
        // Is the path empty?
        if self.raw_path.trim().is_empty() {
            return None;
        }
        // Does the path end in a slash?
        if self.raw_path.trim().ends_with('/') {
            return None;
        }

        return Some(self.raw_path.trim().rsplit_once('/').unwrap().1);
    }

    /// Creates a new [`Path`] with a different [`Path`] adjoined to `self`.
    ///
    /// # Example
    /// ```
    /// # fn main() {
    /// use gmi::url::Path;
    /// assert_eq!(Path::from("/help/").merge_path(&Path::from("me")), Path::from("/help/me"));
    /// # }
    /// ```
    pub fn merge_path(&self, other_path: &Self) -> Self {
        // If the other path is empty, we don't need to do anything
        if other_path.raw_path.trim().is_empty() {
            return self.clone();
        }
        // If the other path is an absolute path, there is no merging and the
        // other path completely takes over
        if other_path.is_absolute() {
            Self {
                raw_path: other_path.to_string(),
            }
        } else {
            // The other path is relative, so we'll just append the other path to this path.
            // If this path is empty, we can just set the path to the other path, but absolute.
            if self.raw_path.trim().is_empty() {
                let mut new_path = String::from("/");
                new_path.push_str(&other_path.raw_path);
                return Self { raw_path: new_path };
            }

            // If the path ends in a slash, it's already a directory and we can just append our new
            // path to this path
            if self.raw_path.ends_with('/') {
                let mut new_path = self.clone();
                new_path.raw_path.push_str(&other_path.raw_path);
                return new_path;
            }

            // The path ends in some file name, so we'll take that off the path, and then put this
            // new path on top of it
            let path = self.raw_path.trim().rsplit_once('/').unwrap().0;
            let mut new_raw_path = String::from(path);
            new_raw_path.push('/');
            new_raw_path.push_str(&other_path.raw_path);
            Self {
                raw_path: new_raw_path,
            }
        }
    }

    /// Removes any relative dot pathing from the path.
    ///
    /// # Example
    /// ```
    /// # use gmi::url::Path;
    /// # fn main() {
    /// let mut path = Path::from("/a/dotted/../path/./with/stuff");
    /// path.dedotify();
    /// assert_eq!(path.to_string(), "/a/path/with/stuff");
    /// # }
    pub fn dedotify(&mut self) {
        // Input buffer
        let mut input = self.raw_path.clone();
        let input_ends_with_slash = input.ends_with('/');
        // Output buffer
        let mut output = String::new();
        while !input.is_empty() && input != "/" {
            // A. If input buffer starts with "../" or "./" remove them
            if input.starts_with("../") || input.starts_with("./") {
                input = input
                    .trim_start_matches("../")
                    .trim_start_matches("./")
                    .to_string();
            }
            // B. If input starts with "/./", "/." replace with /
            if input.starts_with("/./") {
                input = input.replacen("/./", "/", 1);
            }
            if input.starts_with("/.") && !input.starts_with("/..") {
                input = input.replacen("/.", "/", 1);
            }
            // C. If input starts with "/../" or "/.." then replace with "/" and remove
            // previous path segment from output buffer
            if input.starts_with("/../") {
                input = input.replacen("/../", "/", 1);
                let output_split = output.rsplit_once('/').unwrap_or(("", ""));
                let output_split = if output_split.1 == "" {
                    output_split.0.rsplit_once('/').unwrap_or(("", ""))
                } else {
                    output_split
                };
                output = String::from(output_split.0);
            }
            if input.starts_with("/..") {
                input = input.replacen("/..", "/", 1);
                let output_split = output.rsplit_once('/').unwrap_or(("", ""));
                let output_split = if output_split.1 == "" {
                    output_split.0.rsplit_once('/').unwrap_or(("", ""))
                } else {
                    output_split
                };
                output = String::from(output_split.0);
            }

            // D. If the input buffer only consists of "." or ".." then remove it
            if input == "." || input == ".." {
                input = String::new();
            }

            // E. Move the first path segment of the input buffer to the end of the
            // output buffer and remove it from the input buffer
            if input.starts_with('/') {
                input = (&input[1..]).to_string();
                output.push('/');
            }
            let input_clone = input.clone();
            let (input_left, input_right) = input.split_once('/').unwrap_or((&input_clone, ""));
            output.push_str(input_left);
            let mut new_input = String::from('/');
            new_input.push_str(input_right);
            input = new_input;
            println!("out: {}, in: {}", output, input);
        }
        if input_ends_with_slash && !output.ends_with('/') {
            output.push('/');
        }
        self.raw_path = output;
    }
}

/// The query part of the URL.
///
/// This part is optional in a URL and consists of "fragments"
/// The first query part is the first fragment, and each fragment following is separated by the
/// character '#'
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct Query {
    /// The various fragments of the query portion of the URL
    pub fragments: Vec<String>,
}

impl core::fmt::Display for Query {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(f, "?{}", self.fragments[0])?;
        for p in self.fragments[1..].iter() {
            write!(f, "#{}", p)?;
        }
        Ok(())
    }
}

impl From<&str> for Query {
    /// # NOTE
    ///
    /// See [`parse_str`](Query::parse_str) for various
    /// parsing infos
    fn from(s: &str) -> Self {
        Self::parse_str(s)
    }
}

impl Query {
    /// Parses a query part into separate parts. You can also use [`Query::from()`]
    ///
    /// This requires the query part to be already separated from the URL. The str will not start
    /// with a '?', and if it does, the first fragment will contain it
    ///
    /// # Examples:
    /// ```
    /// # use gmi::url::Query;
    /// # fn main() {
    /// let query = Query::parse_str("test#query");
    /// assert_eq!(query.fragments[0], "test");
    /// assert_eq!(query.fragments[1], "query");
    /// # }
    pub fn parse_str(raw_query: &str) -> Self {
        Self {
            fragments: raw_query.split('#').map(|s| String::from(s)).collect(),
        }
    }
}

/// Returns if a specific character is part of the reserved
/// characters list of the URL
///
/// See [section 2.2 of RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-2.2) for
/// more details
///
/// # Example
/// ```
/// # use gmi::url;
/// # fn main() {
/// assert!(url::is_reserved_char('!'));
/// assert!(!url::is_reserved_char('c'));
/// # }
/// ```
pub fn is_reserved_char(c: char) -> bool {
    // All alphanumeric characters are unreserved
    if c.is_alphanumeric() {
        return false;
    }
    match c {
        '-' | '.' | '_' | '~' => false,
        _ => true,
    }
}

/// Percent encodes any reserved characters in a string
///
/// See [section 2.1 of RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-2.1) for
/// more details
///
/// # Example
/// ```
/// # use gmi::url;
/// # fn main() {
/// let percent_encoding = url::percent_encode_reserved_characters("this is a test");
/// assert_eq!(percent_encoding, "this%20is%20a%20test");
/// # }
/// ```
pub fn percent_encode_reserved_characters(data: &str) -> String {
    let mut ret = String::new();
    for c in data.chars() {
        if is_reserved_char(c) {
            ret.push_str(&percent_encode(c));
        } else {
            ret.push(c);
        }
    }
    ret
}

/// Percent encodes a singular character
/// See [`percent_encode_reserved_characters`] for more info on this
///
/// # Example:
/// ```
/// # use gmi::url;
/// # fn main() {
/// assert_eq!(url::percent_encode('!'), "%21");
/// # }
pub fn percent_encode(c: char) -> String {
    let mut ret = String::new();
    let mut buf = [0; 4];
    c.encode_utf8(&mut buf);
    for i in 0..c.len_utf8() {
        ret.push_str(&format!("%{:02x}", buf[i]));
    }
    ret
}

#[cfg(test)]
mod test {
    //    use crate::url::*;
    mod bare_fns {
        use crate::url::*;
        #[test]
        fn test_percent_encode() {
            assert_eq!(percent_encode(' '), "%20");
            assert_eq!(percent_encode(''), "%e3%81%8b");
        }
        #[test]
        fn test_percent_encode_reserved_characters() {
            assert_eq!(
                percent_encode_reserved_characters("this is a test"),
                "this%20is%20a%20test"
            );
        }
    }
    mod authority {
        use std::convert::TryFrom;
        use crate::url::*;
        #[test]
        fn authority_parse_str_simple() {
            assert_eq!(
                Authority::try_from("example.com"),
                Ok(Authority {
                    host: "example.com".to_string(),
                    port: None,
                })
            );
        }
        #[test]
        fn authority_parse_str_with_port() {
            assert_eq!(
                Authority::try_from("example.com:1234"),
                Ok(Authority {
                    host: "example.com".to_string(),
                    port: Some(1234),
                })
            );
        }
        #[test]
        fn authority_parse_str_invalid_port() {
            assert_eq!(
                Authority::try_from("example.com:fjdklg"),
                Err(AuthorityParseError::InvalidPort)
            );
        }
        #[test]
        fn authority_parse_str_missing_host() {
            assert_eq!(
                Authority::try_from(""),
                Err(AuthorityParseError::MissingHost)
            );
            assert_eq!(
                Authority::try_from(":1323"),
                Err(AuthorityParseError::MissingHost)
            );
        }
    }
    mod query {
        use crate::url::*;
        #[test]
        fn query_test() {
            let q = Query::from("this=test#is_this");
            assert_eq!(q.fragments, vec!["this=test", "is_this"]);
        }
    }

    mod path {
        use crate::url::*;
        #[test]
        fn path_parent() {
            let path = Path::from("/just/a/test/path.txt");
            let parent = path.parent().unwrap();
            assert_eq!(parent.raw_path, "/just/a/test/");
        }
        #[test]
        fn path_ancestors() {
            /*
            let path = Path::from("/just/a/test/path.txt");
            let mut ancestors = path.ancestors();
            assert_eq!(ancestors.next(), Some(Path::from("/just/a/test/")));
            assert_eq!(ancestors.next(), Some(Path::from("/just/a/")));
            assert_eq!(ancestors.next(), Some(Path::from("/just/")));
            assert_eq!(ancestors.next(), Some(Path::from("/")));
            assert_eq!(ancestors.next(), None);
            */
        }
        #[test]
        fn path_merge() {
            let path_ending_file = Path::from("/a/test/path");
            let path_ending_dir = Path::from("/a/test/path/");
            let empty_path = Path::from("");
            let root_path = Path::from("/");
            let new_relative_path = Path::from("with/the/new/part");
            let new_absolute_path = Path::from("/this/is/the/new/part/");
            assert_eq!(
                path_ending_file.merge_path(&new_relative_path).raw_path,
                "/a/test/with/the/new/part"
            );
            assert_eq!(
                path_ending_dir.merge_path(&new_relative_path).raw_path,
                "/a/test/path/with/the/new/part"
            );

            assert_eq!(
                path_ending_file.merge_path(&new_absolute_path).raw_path,
                "/this/is/the/new/part/"
            );
            assert_eq!(
                path_ending_dir.merge_path(&new_absolute_path).raw_path,
                "/this/is/the/new/part/"
            );

            assert_eq!(
                path_ending_file.merge_path(&empty_path).raw_path,
                "/a/test/path"
            );
            assert_eq!(
                path_ending_dir.merge_path(&empty_path).raw_path,
                "/a/test/path/"
            );

            assert_eq!(path_ending_file.merge_path(&root_path).raw_path, "/");
            assert_eq!(path_ending_dir.merge_path(&root_path).raw_path, "/");

            assert_eq!(
                empty_path.merge_path(&new_relative_path).raw_path,
                "/with/the/new/part"
            );
            assert_eq!(
                empty_path.merge_path(&new_absolute_path).raw_path,
                "/this/is/the/new/part/"
            );

            assert_eq!(root_path.merge_path(&empty_path).raw_path, "/");
            assert_eq!(
                root_path.merge_path(&new_relative_path).raw_path,
                "/with/the/new/part"
            );
            assert_eq!(
                root_path.merge_path(&new_absolute_path).raw_path,
                "/this/is/the/new/part/"
            );
        }

        #[test]
        fn dedotify() {
            std::thread::sleep(std::time::Duration::from_secs(1));
            let mut p = Path::from("help/");
            p.dedotify();
            assert_eq!(p.raw_path, "help/");
        }
    }
}