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
//! A human-readable ID which is safe to use as a component in a URI path.
//! and supports constant [`Label`]s.
//!
//! Features:
//!  - `hash`: enable support for [`async-hash`](https://docs.rs/async-hash)
//!  - `serde`: enable support for [`serde`](https://docs.rs/serde)
//!  - `stream`: enable support for [`destream`](https://docs.rs/destream)
//!  - `uuid`: enable support for [`uuid`](https://docs.rs/uuid)
//!
//! Example:
//! ```
//! # use std::str::FromStr;
//! use hr_id::{label, Id, Label};
//!
//! const HELLO: Label = label("hello"); // unchecked!
//! let world: Id = "world".parse().expect("id");
//!
//! assert_eq!(format!("{}, {}!", HELLO, world), "hello, world!");
//! assert_eq!(Id::from(HELLO), "hello");
//! assert!(Id::from_str("this string has whitespace").is_err());
//! ```

use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt;
use std::ops::Deref;
use std::path::Path;
use std::str::FromStr;

use derive_more::*;
use get_size::GetSize;
use get_size_derive::*;
use regex::Regex;
use safecast::TryCastFrom;

#[cfg(feature = "stream")]
mod destream;
#[cfg(feature = "hash")]
mod hash;
#[cfg(feature = "serde")]
mod serde;

/// A set of prohibited character patterns.
pub const RESERVED_CHARS: [&str; 21] = [
    "/", "..", "~", "$", "`", "&", "|", "=", "^", "{", "}", "<", ">", "'", "\"", "?", ":", "@",
    "#", "(", ")",
];

/// An error encountered while parsing an [`Id`].
#[derive(Debug, Display, Error)]
#[display(fmt = "{}", msg)]
pub struct ParseError {
    msg: String,
}

impl From<String> for ParseError {
    fn from(msg: String) -> Self {
        Self { msg }
    }
}

impl From<&str> for ParseError {
    fn from(msg: &str) -> Self {
        Self {
            msg: msg.to_string(),
        }
    }
}

/// A static label which implements `Into<Id>`.
pub struct Label {
    id: &'static str,
}

impl Deref for Label {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.id
    }
}

impl From<Label> for Id {
    fn from(l: Label) -> Id {
        Id {
            inner: l.id.to_string(),
        }
    }
}

impl PartialEq<Id> for Label {
    fn eq(&self, other: &Id) -> bool {
        self.id == other.as_str()
    }
}

impl fmt::Display for Label {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.id)
    }
}

/// Return a [`Label`] with the given static `str`.
pub const fn label(id: &'static str) -> Label {
    Label { id }
}

/// A human-readable ID
#[derive(Clone, Eq, Hash, GetSize, PartialEq, Ord, PartialOrd)]
pub struct Id {
    inner: String,
}

impl Id {
    /// Borrows the String underlying this `Id`.
    #[inline]
    pub fn as_str(&self) -> &str {
        self.inner.as_str()
    }

    /// Return true if this `Id` begins with the specified string.
    pub fn starts_with(&self, prefix: &str) -> bool {
        self.inner.starts_with(prefix)
    }
}

impl AsRef<Path> for Id {
    fn as_ref(&self) -> &Path {
        self.inner.as_ref()
    }
}

#[cfg(feature = "uuid")]
impl From<uuid::Uuid> for Id {
    fn from(id: uuid::Uuid) -> Self {
        Self {
            inner: id.to_string(),
        }
    }
}

impl Borrow<str> for Id {
    fn borrow(&self) -> &str {
        &self.inner
    }
}

impl Borrow<String> for Id {
    fn borrow(&self) -> &String {
        &self.inner
    }
}

impl PartialEq<String> for Id {
    fn eq(&self, other: &String) -> bool {
        &self.inner == other
    }
}

impl PartialEq<str> for Id {
    fn eq(&self, other: &str) -> bool {
        self.inner == other
    }
}

impl<'a> PartialEq<&'a str> for Id {
    fn eq(&self, other: &&'a str) -> bool {
        self.inner == *other
    }
}

impl PartialEq<Label> for Id {
    fn eq(&self, other: &Label) -> bool {
        self.inner == other.id
    }
}

impl PartialEq<Id> for &str {
    fn eq(&self, other: &Id) -> bool {
        self == &other.inner
    }
}

impl PartialOrd<String> for Id {
    fn partial_cmp(&self, other: &String) -> Option<Ordering> {
        self.inner.partial_cmp(other)
    }
}

impl PartialOrd<str> for Id {
    fn partial_cmp(&self, other: &str) -> Option<Ordering> {
        self.inner.as_str().partial_cmp(other)
    }
}

impl<'a> PartialOrd<&'a str> for Id {
    fn partial_cmp(&self, other: &&'a str) -> Option<Ordering> {
        self.inner.as_str().partial_cmp(*other)
    }
}

impl From<usize> for Id {
    fn from(u: usize) -> Id {
        u.to_string().parse().expect("usize")
    }
}

impl From<u64> for Id {
    fn from(i: u64) -> Id {
        i.to_string().parse().expect("64-bit unsigned int")
    }
}

impl FromStr for Id {
    type Err = ParseError;

    fn from_str(id: &str) -> Result<Self, Self::Err> {
        validate_id(id)?;

        Ok(Id {
            inner: id.to_string(),
        })
    }
}

impl TryCastFrom<String> for Id {
    fn can_cast_from(id: &String) -> bool {
        validate_id(id).is_ok()
    }

    fn opt_cast_from(id: String) -> Option<Id> {
        id.parse().ok()
    }
}

impl From<Id> for String {
    fn from(id: Id) -> String {
        id.inner
    }
}

impl TryCastFrom<Id> for usize {
    fn can_cast_from(id: &Id) -> bool {
        id.as_str().parse::<usize>().is_ok()
    }

    fn opt_cast_from(id: Id) -> Option<usize> {
        id.as_str().parse::<usize>().ok()
    }
}

impl fmt::Debug for Id {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.inner)
    }
}

impl fmt::Display for Id {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.inner)
    }
}

fn validate_id(id: &str) -> Result<(), ParseError> {
    if id.is_empty() {
        return Err("cannot construct an empty Id".into());
    }

    let mut invalid_chars = id.chars().filter(|c| (*c as u8) < 32u8);
    if let Some(invalid) = invalid_chars.next() {
        return Err(format!(
            "Id {} contains ASCII control characters {}",
            id, invalid as u8,
        )
        .into());
    }

    for pattern in &RESERVED_CHARS {
        if id.contains(pattern) {
            return Err(format!("Id {} contains disallowed pattern {}", id, pattern).into());
        }
    }

    if let Some(w) = Regex::new(r"\s").expect("whitespace regex").find(id) {
        return Err(format!("Id {} is not allowed to contain whitespace {:?}", id, w).into());
    }

    Ok(())
}