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
// Copyright 2022 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 {
    cm_types::{LongName, Name},
    core::cmp::Ordering,
    moniker::{ChildName, ChildNameBase, MonikerError},
    std::fmt,
};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// An instanced child moniker locally identifies a child component instance using the name assigned by
/// its parent and its collection (if present). It is a building block for more complex monikers.
///
/// Display notation: "[collection:]name:instance_id".
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Eq, PartialEq, Clone, Hash)]
pub struct InstancedChildName {
    name: LongName,
    collection: Option<Name>,
    instance: IncarnationId,
}

pub type IncarnationId = u32;

impl ChildNameBase for InstancedChildName {
    /// Parses an `ChildName` from a string.
    ///
    /// Input strings should be of the format `(<collection>:)?<name>:<instance_id>`, e.g. `foo:42`
    /// or `coll:foo:42`.
    fn parse<T: AsRef<str>>(rep: T) -> Result<Self, MonikerError> {
        let rep = rep.as_ref();
        let parts: Vec<&str> = rep.split(":").collect();
        // An instanced moniker is either just a name (static instance), or
        // collection:name:instance_id.
        let (coll, name, instance) = match parts.len() {
            2 => {
                let instance = parts[1]
                    .parse::<IncarnationId>()
                    .map_err(|_| MonikerError::invalid_moniker(rep))?;
                (None, parts[0], instance)
            }
            3 => {
                let instance = parts[2]
                    .parse::<IncarnationId>()
                    .map_err(|_| MonikerError::invalid_moniker(rep))?;
                (Some(parts[0]), parts[1], instance)
            }
            _ => return Err(MonikerError::invalid_moniker(rep)),
        };
        Self::try_new(name, coll, instance)
    }

    fn name(&self) -> &LongName {
        &self.name
    }

    fn collection(&self) -> Option<&Name> {
        self.collection.as_ref()
    }
}

impl InstancedChildName {
    pub fn try_new<S>(
        name: S,
        collection: Option<S>,
        instance: IncarnationId,
    ) -> Result<Self, MonikerError>
    where
        S: AsRef<str> + Into<String>,
    {
        let name = LongName::new(name)?;
        let collection = match collection {
            Some(coll) => {
                let coll_name = Name::new(coll)?;
                Some(coll_name)
            }
            None => None,
        };
        Ok(Self { name, collection, instance })
    }

    /// Returns a moniker for a static child.
    ///
    /// The returned value will have no `collection`, and will have an `instance_id` of 0.
    pub fn static_child(name: &str) -> Result<Self, MonikerError> {
        Self::try_new(name, None, 0)
    }

    /// Converts this child moniker into an instanced moniker.
    pub fn from_child_moniker(m: &ChildName, instance: IncarnationId) -> Self {
        Self::try_new(m.name().as_str(), m.collection().map(|c| c.as_str()), instance)
            .expect("child moniker is guaranteed to be valid")
    }

    /// Convert an InstancedChildName to an allocated ChildName
    /// without an InstanceId
    pub fn without_instance_id(&self) -> ChildName {
        ChildName::try_new(self.name().as_str(), self.collection().map(|c| c.as_str()))
            .expect("moniker is guaranteed to be valid")
    }

    pub fn instance(&self) -> IncarnationId {
        self.instance
    }

    pub fn format(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(coll) = &self.collection {
            write!(f, "{}:{}:{}", coll, self.name, self.instance)
        } else {
            write!(f, "{}:{}", self.name, self.instance)
        }
    }
}

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

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

impl Ord for InstancedChildName {
    fn cmp(&self, other: &Self) -> Ordering {
        (&self.collection, &self.name, &self.instance).cmp(&(
            &other.collection,
            &other.name,
            &other.instance,
        ))
    }
}

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

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

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

#[cfg(test)]
mod tests {
    use {
        super::*,
        cm_types::{MAX_LONG_NAME_LENGTH, MAX_NAME_LENGTH},
    };

    #[test]
    fn instanced_child_monikers() {
        let m = InstancedChildName::try_new("test", None, 42).unwrap();
        assert_eq!("test", m.name().as_str());
        assert_eq!(None, m.collection());
        assert_eq!(42, m.instance());
        assert_eq!("test:42", format!("{}", m));
        assert_eq!(m, InstancedChildName::try_from("test:42").unwrap());
        assert_eq!("test", m.without_instance_id().to_string());
        assert_eq!(m, InstancedChildName::from_child_moniker(&"test".try_into().unwrap(), 42));

        let m = InstancedChildName::try_new("test", Some("coll"), 42).unwrap();
        assert_eq!("test", m.name().as_str());
        assert_eq!(Some(&Name::new("coll").unwrap()), m.collection());
        assert_eq!(42, m.instance());
        assert_eq!("coll:test:42", format!("{}", m));
        assert_eq!(m, InstancedChildName::try_from("coll:test:42").unwrap());
        assert_eq!("coll:test", m.without_instance_id().to_string());
        assert_eq!(m, InstancedChildName::from_child_moniker(&"coll:test".try_into().unwrap(), 42));

        let max_coll_length_part = "f".repeat(MAX_NAME_LENGTH);
        let max_name_length_part: LongName = "f".repeat(MAX_LONG_NAME_LENGTH).parse().unwrap();
        let m = InstancedChildName::parse(format!(
            "{}:{}:42",
            max_coll_length_part, max_name_length_part
        ))
        .expect("valid moniker");
        assert_eq!(max_name_length_part, m.name().as_str());
        assert_eq!(Some(&Name::new(max_coll_length_part).unwrap()), m.collection());
        assert_eq!(42, m.instance());

        assert!(InstancedChildName::parse("").is_err(), "cannot be empty");
        assert!(InstancedChildName::parse(":").is_err(), "cannot be empty with colon");
        assert!(InstancedChildName::parse("::").is_err(), "cannot be empty with double colon");
        assert!(InstancedChildName::parse("f:").is_err(), "second part cannot be empty with colon");
        assert!(InstancedChildName::parse(":1").is_err(), "first part cannot be empty with colon");
        assert!(
            InstancedChildName::parse("f:f:").is_err(),
            "third part cannot be empty with colon"
        );
        assert!(
            InstancedChildName::parse("f::1").is_err(),
            "second part cannot be empty with colon"
        );
        assert!(
            InstancedChildName::parse(":f:1").is_err(),
            "first part cannot be empty with colon"
        );
        assert!(
            InstancedChildName::parse("f:f:1:1").is_err(),
            "more than three colons not allowed"
        );
        assert!(InstancedChildName::parse("f:f").is_err(), "second part must be int");
        assert!(InstancedChildName::parse("f:f:f").is_err(), "third part must be int");
        assert!(InstancedChildName::parse("@:1").is_err(), "invalid character in name");
        assert!(InstancedChildName::parse("@:f:1").is_err(), "invalid character in collection");
        assert!(
            InstancedChildName::parse("f:@:1").is_err(),
            "invalid character in name with collection"
        );
        assert!(
            InstancedChildName::parse(&format!("f:{}", "x".repeat(MAX_LONG_NAME_LENGTH + 1)))
                .is_err(),
            "name too long"
        );
        assert!(
            InstancedChildName::parse(&format!("{}:x", "f".repeat(MAX_NAME_LENGTH + 1))).is_err(),
            "collection too long"
        );
    }

    #[test]
    fn instanced_child_moniker_compare() {
        let a = InstancedChildName::try_new("a", None, 1).unwrap();
        let a2 = InstancedChildName::try_new("a", None, 2).unwrap();
        let aa = InstancedChildName::try_new("a", Some("a"), 1).unwrap();
        let aa2 = InstancedChildName::try_new("a", Some("a"), 2).unwrap();
        let ab = InstancedChildName::try_new("a", Some("b"), 1).unwrap();
        let ba = InstancedChildName::try_new("b", Some("a"), 1).unwrap();
        let bb = InstancedChildName::try_new("b", Some("b"), 1).unwrap();
        let aa_same = InstancedChildName::try_new("a", Some("a"), 1).unwrap();

        assert_eq!(Ordering::Less, a.cmp(&a2));
        assert_eq!(Ordering::Greater, a2.cmp(&a));
        assert_eq!(Ordering::Less, a2.cmp(&aa));
        assert_eq!(Ordering::Greater, aa.cmp(&a2));
        assert_eq!(Ordering::Less, a.cmp(&ab));
        assert_eq!(Ordering::Greater, ab.cmp(&a));
        assert_eq!(Ordering::Less, a.cmp(&ba));
        assert_eq!(Ordering::Greater, ba.cmp(&a));
        assert_eq!(Ordering::Less, a.cmp(&bb));
        assert_eq!(Ordering::Greater, bb.cmp(&a));

        assert_eq!(Ordering::Less, aa.cmp(&aa2));
        assert_eq!(Ordering::Greater, aa2.cmp(&aa));
        assert_eq!(Ordering::Less, aa.cmp(&ab));
        assert_eq!(Ordering::Greater, ab.cmp(&aa));
        assert_eq!(Ordering::Less, aa.cmp(&ba));
        assert_eq!(Ordering::Greater, ba.cmp(&aa));
        assert_eq!(Ordering::Less, aa.cmp(&bb));
        assert_eq!(Ordering::Greater, bb.cmp(&aa));
        assert_eq!(Ordering::Equal, aa.cmp(&aa_same));
        assert_eq!(Ordering::Equal, aa_same.cmp(&aa));

        assert_eq!(Ordering::Greater, ab.cmp(&ba));
        assert_eq!(Ordering::Less, ba.cmp(&ab));
        assert_eq!(Ordering::Less, ab.cmp(&bb));
        assert_eq!(Ordering::Greater, bb.cmp(&ab));

        assert_eq!(Ordering::Less, ba.cmp(&bb));
        assert_eq!(Ordering::Greater, bb.cmp(&ba));
    }
}