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
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    crate::{
        child_name::{ChildName, ChildNameBase},
        error::MonikerError,
    },
    core::cmp::{self, Ordering, PartialEq},
    std::{fmt, hash::Hash},
};

/// MonikerBase is the common trait for both InstancedMoniker
/// and Moniker concrete types.
///
/// MonikerBase describes the identity of a component instance in terms of its path
/// relative to the root of the component instance tree.
pub trait MonikerBase: Default + Eq + PartialEq + fmt::Debug + Clone + Hash + fmt::Display {
    type Part: ChildNameBase;

    fn new(path: Vec<Self::Part>) -> Self;

    fn parse<T: AsRef<str>>(path: &[T]) -> Result<Self, MonikerError> {
        let path: Result<Vec<Self::Part>, MonikerError> =
            path.iter().map(|x| Self::Part::parse(x)).collect();
        Ok(Self::new(path?))
    }

    fn parse_str(input: &str) -> Result<Self, MonikerError> {
        if input.is_empty() {
            return Err(MonikerError::invalid_moniker(input));
        }
        if input == "/" || input == "." || input == "./" {
            return Ok(Self::new(vec![]));
        }

        // Optionally strip a prefix of "/" or "./".
        let stripped = match input.strip_prefix("/") {
            Some(s) => s,
            None => match input.strip_prefix("./") {
                Some(s) => s,
                None => input,
            },
        };
        let path =
            stripped.split('/').map(Self::Part::parse).collect::<Result<_, MonikerError>>()?;
        Ok(Self::new(path))
    }

    /// Concatenates other onto the end of this moniker.
    fn concat<T: MonikerBase<Part = Self::Part>>(&self, other: &T) -> Self {
        let mut path = self.path().clone();
        let mut other_path = other.path().clone();
        path.append(&mut other_path);
        Self::new(path)
    }

    fn path(&self) -> &Vec<Self::Part>;

    fn path_mut(&mut self) -> &mut Vec<Self::Part>;

    /// Indicates whether this moniker is prefixed by prefix.
    fn has_prefix<S: MonikerBase<Part = Self::Part>>(&self, prefix: &S) -> bool {
        if self.path().len() < prefix.path().len() {
            return false;
        }

        prefix.path().iter().enumerate().all(|item| *item.1 == self.path()[item.0])
    }

    fn root() -> Self {
        Self::new(vec![])
    }

    fn leaf(&self) -> Option<&Self::Part> {
        self.path().last()
    }

    fn is_root(&self) -> bool {
        self.path().is_empty()
    }

    fn parent(&self) -> Option<Self> {
        if self.is_root() {
            None
        } else {
            let l = self.path().len() - 1;
            Some(Self::new(self.path()[..l].to_vec()))
        }
    }

    fn child(&self, child: Self::Part) -> Self {
        let mut path = self.path().clone();
        path.push(child);
        Self::new(path)
    }

    /// Strips the moniker parts in prefix from the beginning of this moniker.
    fn strip_prefix<T: MonikerBase<Part = Self::Part>>(
        &self,
        prefix: &T,
    ) -> Result<Self, MonikerError> {
        if !self.has_prefix(prefix) {
            return Err(MonikerError::MonikerDoesNotHavePrefix {
                moniker: self.to_string(),
                prefix: prefix.to_string(),
            });
        }

        let prefix_len = prefix.path().len();
        let mut path = self.path().clone();
        path.drain(0..prefix_len);
        Ok(Self::new(path))
    }

    fn compare(&self, other: &Self) -> cmp::Ordering {
        let min_size = cmp::min(self.path().len(), other.path().len());
        for i in 0..min_size {
            if self.path()[i] < other.path()[i] {
                return cmp::Ordering::Less;
            } else if self.path()[i] > other.path()[i] {
                return cmp::Ordering::Greater;
            }
        }
        if self.path().len() > other.path().len() {
            return cmp::Ordering::Greater;
        } else if self.path().len() < other.path().len() {
            return cmp::Ordering::Less;
        }

        return cmp::Ordering::Equal;
    }

    fn format(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.path().is_empty() {
            write!(f, ".")?;
        } else {
            write!(f, "{}", self.path()[0])?;
            for segment in self.path()[1..].iter() {
                write!(f, "/{}", segment)?;
            }
        }
        Ok(())
    }
}

/// Moniker describes the identity of a component instance
/// in terms of its path relative to the root of the component instance
/// tree. The constituent parts of a Moniker do not include the
/// instance ID of the child.
///
/// Display notation: ".", "name1", "name1/name2", ...
#[derive(Eq, PartialEq, Clone, Hash, Default)]
pub struct Moniker {
    path: Vec<ChildName>,
}

impl MonikerBase for Moniker {
    type Part = ChildName;

    fn new(path: Vec<Self::Part>) -> Self {
        Self { path }
    }

    fn path(&self) -> &Vec<Self::Part> {
        &self.path
    }

    fn path_mut(&mut self) -> &mut Vec<Self::Part> {
        &mut self.path
    }
}

impl TryFrom<Vec<&str>> for Moniker {
    type Error = MonikerError;

    fn try_from(rep: Vec<&str>) -> Result<Self, MonikerError> {
        Self::parse(&rep)
    }
}

impl TryFrom<&str> for Moniker {
    type Error = MonikerError;

    fn try_from(input: &str) -> Result<Self, MonikerError> {
        Self::parse_str(input)
    }
}

impl std::str::FromStr for Moniker {
    type Err = MonikerError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_str(s)
    }
}

impl cmp::Ord for Moniker {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.compare(other)
    }
}

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

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

impl fmt::Debug for Moniker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.format(f)
    }
}

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

    #[test]
    fn monikers() {
        let root = Moniker::root();
        assert_eq!(true, root.is_root());
        assert_eq!(".", format!("{}", root));
        assert_eq!(root, Moniker::new(vec![]));
        assert_eq!(root, Moniker::try_from(vec![]).unwrap());

        let m = Moniker::new(vec![
            ChildName::try_new("a", None).unwrap(),
            ChildName::try_new("b", Some("coll")).unwrap(),
        ]);
        assert_eq!(false, m.is_root());
        assert_eq!("a/coll:b", format!("{}", m));
        assert_eq!(m, Moniker::try_from(vec!["a", "coll:b"]).unwrap());
        assert_eq!(m.leaf().map(|m| m.collection()).flatten(), Some(&Name::new("coll").unwrap()));
        assert_eq!(m.leaf().map(|m| m.name().as_str()), Some("b"));
        assert_eq!(m.leaf(), Some(&ChildName::try_from("coll:b").unwrap()));
    }

    #[test]
    fn moniker_parent() {
        let root = Moniker::root();
        assert_eq!(true, root.is_root());
        assert_eq!(None, root.parent());

        let m = Moniker::new(vec![
            ChildName::try_new("a", None).unwrap(),
            ChildName::try_new("b", None).unwrap(),
        ]);
        assert_eq!("a/b", format!("{}", m));
        assert_eq!("a", format!("{}", m.parent().unwrap()));
        assert_eq!(".", format!("{}", m.parent().unwrap().parent().unwrap()));
        assert_eq!(None, m.parent().unwrap().parent().unwrap().parent());
        assert_eq!(m.leaf(), Some(&ChildName::try_from("b").unwrap()));
    }

    #[test]
    fn moniker_concat() {
        let scope_root: Moniker = vec!["a:test1", "b:test2"].try_into().unwrap();

        let relative: Moniker = vec!["c:test3", "d:test4"].try_into().unwrap();
        let descendant = scope_root.concat(&relative);
        assert_eq!("a:test1/b:test2/c:test3/d:test4", format!("{}", descendant));

        let relative: Moniker = vec![].try_into().unwrap();
        let descendant = scope_root.concat(&relative);
        assert_eq!("a:test1/b:test2", format!("{}", descendant));
    }

    #[test]
    fn moniker_parse_str() {
        assert_eq!(Moniker::try_from("/foo").unwrap(), Moniker::try_from(vec!["foo"]).unwrap());
        assert_eq!(Moniker::try_from("./foo").unwrap(), Moniker::try_from(vec!["foo"]).unwrap());
        assert_eq!(Moniker::try_from("foo").unwrap(), Moniker::try_from(vec!["foo"]).unwrap());
        assert_eq!(Moniker::try_from("/").unwrap(), Moniker::try_from(vec![]).unwrap());
        assert_eq!(Moniker::try_from("./").unwrap(), Moniker::try_from(vec![]).unwrap());

        assert!(Moniker::try_from("//foo").is_err());
        assert!(Moniker::try_from(".//foo").is_err());
        assert!(Moniker::try_from("/./foo").is_err());
        assert!(Moniker::try_from("../foo").is_err());
        assert!(Moniker::try_from(".foo").is_err());
    }
}