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
//
// Copyright (c) 2017, 2020 ADLINK Technology Inc.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   ADLINK zenoh team, <zenoh@adlink-labs.tech>
//
use crate::net::ResKey;
use regex::Regex;
use std::convert::TryFrom;
use std::fmt;
use zenoh_util::core::{ZError, ZErrorKind, ZResult};
use zenoh_util::zerror;

/// A zenoh Path is a set of strings separated by `'/'` , as in a filesystem path.
///
/// A Path cannot contain any `'*'` character. Examples of paths:
/// `"/demo/example/hello"` , `"/org/eclipse/building/be/floor/1/office/2"` ...
///
/// A path can be absolute (i.e. starting with a `'/'`) or relative to a [`Workspace`](super::Workspace).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Path {
    pub(crate) p: String,
}

impl Path {
    fn is_valid(path: &str) -> bool {
        !path.is_empty()
            && !path.contains(|c| c == '?' || c == '#' || c == '[' || c == ']' || c == '*')
    }

    pub(crate) fn remove_useless_slashes(path: &str) -> String {
        lazy_static! {
            static ref RE: Regex = Regex::new("/+").unwrap();
        }
        let p = RE.replace_all(path, "/");
        // remove last '/' if any and return as String
        p.strip_suffix("/").unwrap_or(&p).to_string()
    }

    /// Creates a new Path from a String, checking its validity.  
    /// Returns `Err(`[`ZError`]`)` if not valid.
    pub fn new(p: String) -> ZResult<Path> {
        if !Self::is_valid(&p) {
            zerror!(ZErrorKind::InvalidPath { path: p })
        } else {
            Ok(Path {
                p: Self::remove_useless_slashes(&p),
            })
        }
    }

    /// Returns the Path as a &str.
    pub fn as_str(&self) -> &str {
        self.p.as_str()
    }

    /// Returns true is this Path is relative (i.e. not starting with `'/'`).
    pub fn is_relative(&self) -> bool {
        !self.p.starts_with('/')
    }

    /// Returns the concatenation of `prefix` with this Path.
    pub fn with_prefix(&self, prefix: &Path) -> Self {
        if self.is_relative() {
            Self {
                p: format!("{}/{}", prefix.p, self.p),
            }
        } else {
            Self {
                p: format!("{}{}", prefix.p, self.p),
            }
        }
    }

    /// If this Path starts with `prefix` returns a copy of this Path with the prefix removed.  
    /// Otherwise, returns `None`.
    pub fn strip_prefix(&self, prefix: &Path) -> Option<Self> {
        self.p
            .strip_prefix(&prefix.p)
            .map(|p| Path { p: p.to_string() })
    }
}

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

impl TryFrom<String> for Path {
    type Error = ZError;
    fn try_from(p: String) -> Result<Self, Self::Error> {
        Path::new(p)
    }
}

impl TryFrom<&str> for Path {
    type Error = ZError;
    fn try_from(p: &str) -> ZResult<Path> {
        Self::try_from(p.to_string())
    }
}

impl From<Path> for ResKey {
    fn from(path: Path) -> Self {
        ResKey::from(path.p.as_str())
    }
}

impl From<&Path> for ResKey {
    fn from(path: &Path) -> Self {
        ResKey::from(path.p.as_str())
    }
}

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

    #[test]
    fn test_path() {
        assert_eq!(Path::try_from("a/b").unwrap(), Path { p: "a/b".into() });

        assert_eq!(Path::try_from("/a/b").unwrap(), Path { p: "/a/b".into() });

        assert_eq!(
            Path::try_from("////a///b///").unwrap(),
            Path { p: "/a/b".into() }
        );

        assert!(Path::try_from("a/b").unwrap().is_relative());
        assert!(!Path::try_from("/a/b").unwrap().is_relative());

        assert_eq!(
            Path::try_from("c/d")
                .unwrap()
                .with_prefix(&"/a/b".try_into().unwrap()),
            Path {
                p: "/a/b/c/d".into()
            }
        );
        assert_eq!(
            Path::try_from("/c/d")
                .unwrap()
                .with_prefix(&"/a/b".try_into().unwrap()),
            Path {
                p: "/a/b/c/d".into()
            }
        );
    }
}