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
use crate::{types::Error, Result};
use serde_derive::Deserialize;
use std::fmt;
use std::str::FromStr;

#[derive(Debug, Clone, PartialEq, Deserialize, Hash, Eq)]
struct Segment(String);

impl Segment {
    // Returns `true` if the character can be used in a segment of the
    // device name.

    fn is_valid_char((idx, ch): (usize, char), len: usize) -> bool {
        ch.is_alphanumeric() || (ch == '-' && idx != 0 && idx != len - 1)
    }

    // Creates a `Segment`, if the strings contains a well-formed
    // segment name.

    fn create(s: &str) -> Result<Self> {
        if !s.is_empty() {
            if s.chars()
                .enumerate()
                .all(|v| Segment::is_valid_char(v, s.len()))
            {
                Ok(Segment(String::from(s)))
            } else {
                Err(Error::InvArgument("segment contains invalid character"))
            }
        } else {
            Err(Error::InvArgument("contains zero-length segment"))
        }
    }
}

// This trait allows one to use `.parse::<Segment>()`.

impl FromStr for Segment {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Segment::create(s)
    }
}

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

#[derive(Debug, PartialEq, Clone, Deserialize, Hash, Eq)]
#[serde(try_from = "&str")]
pub struct Path(Vec<Segment>);

impl Path {
    pub fn create(s: &str) -> Result<Self> {
        s.split(':')
            .map(Segment::create)
            .collect::<Result<Vec<Segment>>>()
            .map(Path)
    }
}

// This trait is defined so that the .TOML parser will use it to parse
// the device prefix field. Without this, the .TOML parser wants array
// notation for the path specification (because `Path` is a newtype
// that wraps a `Vec<>`.)

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

    fn try_from(s: &str) -> Result<Self> {
        Path::create(s)
    }
}

// This trait allows one to use `.parse::<Path>()`.

impl FromStr for Path {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Path::create(s)
    }
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", &self.0[0])?;
        for ii in &self.0[1..] {
            write!(f, ":{}", &ii)?
        }
        Ok(())
    }
}

#[derive(Debug, PartialEq, Clone, Hash, Eq)]
pub struct Base(Segment);

impl Base {
    pub fn create(s: &str) -> Result<Self> {
        Segment::create(s).map(Base)
    }
}

// This trait allows one to use `.parse::<Base>()`.

impl FromStr for Base {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Base::create(s)
    }
}

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

/// Holds a validated device name. A device name consists of a path
/// and a base name where each portion of the path is separated with a
/// colon. Each segment of the path or the name is composed of alpha-
/// numeric and the dash characters. The dash cannot be the first or
/// last character, however.
///
/// More formally:
///
/// ```ignore
/// DEVICE-NAME = PATH NAME
/// PATH = (SEGMENT ':')+
/// NAME = SEGMENT
/// SEGMENT = [0-9a-zA-Z] ( [0-9a-zA-Z-]* [0-9a-zA-Z] )?
/// ```
///
/// All device names will have a path and a name. Although
/// superficially similar, device names are not like file system
/// names. Specifically, there's no concept of moving up or down
/// paths. The paths provide a naming convention to organize devices.
/// The client API supports looking up device names using patterns, so
/// a logical path hierarchy can make those searches more productive.

#[derive(Debug, PartialEq, Hash, Eq, Clone)]
pub struct Name {
    path: Path,
    base: Base,
}

impl Name {
    /// Creates an instance of `Name`, if the provided string
    /// describes a well-formed device name.

    pub fn create(s: &str) -> Result<Name> {
        match s
            .split(':')
            .map(Segment::create)
            .collect::<Result<Vec<Segment>>>()
        {
            Ok(segments) if segments.len() < 2 => Err(Error::InvArgument(
                "device name requires a path and base name",
            )),
            Ok(segments) => Ok(Name {
                path: Path(segments[0..segments.len() - 1].to_vec()),
                base: Base(segments[segments.len() - 1].clone()),
            }),
            Err(e) => Err(e),
        }
    }

    pub fn build(path: Path, base: Base) -> Name {
        Name { path, base }
    }

    /// Returns the path of the device name without the trailing ':'.

    pub fn get_path(&self) -> Path {
        self.path.clone()
    }

    /// Returns the base name of the device.

    pub fn get_name(&self) -> Base {
        self.base.clone()
    }
}

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

// This trait allows one to use `.parse::<Name>()`.

impl FromStr for Name {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Name::create(s)
    }
}

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

    #[test]
    fn test_segment() {
        assert!("".parse::<Segment>().is_err());
        assert!(
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
                .parse::<Segment>()
                .is_ok()
        );
        assert!("a-b".parse::<Segment>().is_ok());
        assert!("a:b".parse::<Segment>().is_err());
        assert!("-a".parse::<Segment>().is_err());
        assert!("a-".parse::<Segment>().is_err());
        assert!(" ".parse::<Segment>().is_err());
        assert_eq!(format!("{}", "a-b".parse::<Segment>().unwrap()), "a-b");

        // Check non-ASCII entries.

        assert!("٣".parse::<Segment>().is_ok());
        assert!("温度".parse::<Segment>().is_ok());
        assert!("🤖".parse::<Segment>().is_err());
    }

    #[test]
    fn test_base() {
        assert_eq!(format!("{}", "a-b".parse::<Base>().unwrap()), "a-b");
        assert!("a:b".parse::<Base>().is_err());
    }

    #[test]
    fn test_path() {
        assert!("".parse::<Path>().is_err());
        assert!("basement:🤖".parse::<Path>().is_err());

        assert_eq!(format!("{}", "a-b".parse::<Path>().unwrap()), "a-b");
        assert_eq!(format!("{}", "a:b".parse::<Path>().unwrap()), "a:b");
        assert_eq!(format!("{}", "a:b:c".parse::<Path>().unwrap()), "a:b:c");
        assert_eq!(
            format!("{}", "家:温度".parse::<Path>().unwrap()),
            "家:温度"
        );
    }

    #[test]
    fn test_device_name() {
        assert!("".parse::<Name>().is_err());
        assert!(":".parse::<Name>().is_err());
        assert!("a".parse::<Name>().is_err());
        assert!(":a".parse::<Name>().is_err());
        assert!("a:".parse::<Name>().is_err());
        assert!("a::a".parse::<Name>().is_err());

        assert!("p:a.".parse::<Name>().is_err());
        assert!("p:a.a".parse::<Name>().is_err());
        assert!("p.a:a".parse::<Name>().is_err());
        assert!("p:a-".parse::<Name>().is_err());
        assert!("p:-a".parse::<Name>().is_err());
        assert!("p-:a".parse::<Name>().is_err());
        assert!("-p:a".parse::<Name>().is_err());

        assert_eq!(
            "p:abc".parse::<Name>().unwrap(),
            Name {
                path: Path::create("p").unwrap(),
                base: Base::create("abc").unwrap(),
            }
        );
        assert_eq!(
            "p:abc1".parse::<Name>().unwrap(),
            Name {
                path: Path::create("p").unwrap(),
                base: Base::create("abc1").unwrap(),
            }
        );
        assert_eq!(
            "p:abc-1".parse::<Name>().unwrap(),
            Name {
                path: Path::create("p").unwrap(),
                base: Base::create("abc-1").unwrap(),
            }
        );
        assert_eq!(
            "p-1:p-2:abc".parse::<Name>().unwrap(),
            Name {
                path: Path::create("p-1:p-2").unwrap(),
                base: Base::create("abc").unwrap(),
            }
        );

        let dn = "p-1:p-2:abc".parse::<Name>().unwrap();

        assert_eq!(dn.get_path(), Path::create("p-1:p-2").unwrap());
        assert_eq!(dn.get_name(), Base::create("abc").unwrap());

        assert_eq!(format!("{}", dn), "p-1:p-2:abc");
    }
}