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
const SEP: char = '.';

// Path

#[derive(Clone, Copy, Debug)]
pub enum Path<'a> {
    End,
    Pair(&'a str, &'a Path<'a>),
}

impl<'a> Path<'a> {
    pub fn new(s: &str) -> Path {
        Path::Pair(s, &Path::End)
    }

    pub fn parts(&self) -> Parts {
        Parts { path: *self }
    }

    pub fn prepend(&'a self, first: &'a str) -> Path<'a> {
        Path::Pair(first, self)
    }

    pub fn deconstruct(&self) -> Option<(&'a str, Path<'a>)> {
        let mut node = self;

        while let &Path::Pair(first, rest) = node {
            let mut chars  = first.chars();
            let mut substr = first;

            while let Some(c) = chars.next() {
                if c == SEP {
                    substr = chars.as_str();
                    continue;
                }

                return Some(
                    if let Some(end) = substr.find(SEP) {
                        let first  = &substr[..end];
                        let second = &substr[end + SEP.len_utf8()..];
                        (first, Path::Pair(second, rest))
                    } else {
                        (substr, *rest)
                    }
                );
            }

            node = rest;
        }

        None
    }

    pub fn to_owned(&self) -> PathBuf {
        let mut buf = PathBuf::new();
        let mut cur = self;

        if let &Path::Pair(first, next) = cur {
            buf.push_str(first);
            cur = next;
        } else {
            return buf;
        }

        while let &Path::Pair(first, next) = cur {
            buf.push(SEP);
            buf.push_str(first);
            cur = next;
        }

        buf
    }
}

// Parts

#[derive(Debug)]
pub struct Parts<'a> {
    path: Path<'a>,
}

impl<'a> Iterator for Parts<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        let (res, path) = match self.path.deconstruct() {
            Some((res, path)) => (Some(res), path),
            None => (None, Path::End),
        };

        self.path = path;
        res
    }
}

impl<'a> Parts<'a> {
    pub fn as_path(&self) -> Path {
        self.path
    }
}

// PathBuf

pub type PathBuf = String;