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
#![allow(clippy::manual_range_contains)]

use std::{convert::TryFrom, fmt};

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

// ----------------------------------------------------------------------------

/// Is the given string a non-empty snake_case string?
/// In particular, does it match  ^[_a-z][_a-z0-9]*$  ?
pub const fn is_snake_case(string: &str) -> bool {
    // we only care about ascii chars, which fit in a byte.
    // iterating over utf8 continuation bytes and the like will not count as valid snake case anyway.
    let (len, bytes) = (string.len(), string.as_bytes());
    const fn valid_start(b: u8) -> bool {
        b == b'_' || b'a' <= b && b <= b'z'
    };
    const fn is_snake_case_character(c: u8) -> bool {
        b'a' <= c && c <= b'z' || b'0' <= c && c <= b'9' || c == b'_'
    }
    // non-empty and starts with a..z or _
    if bytes.is_empty() || !valid_start(bytes[0]) {
        return false;
    }
    //check the rest
    let mut i = 1; // we already checked the first byte, its fine
    loop {
        if i >= len - 1 {
            break true;
        }
        if !is_snake_case_character(bytes[i]) {
            break false;
        }
        i += 1;
    }
}

// ----------------------------------------------------------------------------

/// Only one possible error: the given string was not valid snake_case.
#[derive(Clone, Debug)]
pub struct InvalidSnakeCase;

// ----------------------------------------------------------------------------

/// An owning string type that can only contain valid snake_case.
/// In other words, it always matches  ^[_a-z][_a-z0-9]*$
/// * Non-empty
/// * Starts with a lower case ASCII letter or underscore
/// * Contains only lower case ASCII letters, underscores and digits
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct SnakeCase(String);

impl SnakeCase {
    pub fn try_from_str(s: &str) -> Result<SnakeCase, InvalidSnakeCase> {
        if is_snake_case(s) {
            Ok(SnakeCase(s.to_string()))
        } else {
            Err(InvalidSnakeCase)
        }
    }

    pub fn try_from_string(s: String) -> Result<SnakeCase, InvalidSnakeCase> {
        if is_snake_case(&s) {
            Ok(SnakeCase(s))
        } else {
            Err(InvalidSnakeCase)
        }
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn as_ref(&self) -> SnakeCaseRef {
        SnakeCaseRef(&self.0)
    }
}

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

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        SnakeCase::try_from_str(s)
    }
}

impl TryFrom<String> for SnakeCase {
    type Error = InvalidSnakeCase;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        SnakeCase::try_from_string(s)
    }
}

impl std::borrow::Borrow<str> for SnakeCase {
    fn borrow(&self) -> &str {
        &self.0
    }
}

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

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

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for SnakeCase {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(deserializer)?;
        SnakeCase::try_from_str(&string).map_err(|_: InvalidSnakeCase| {
            serde::de::Error::custom(format!("Expected snake_case, got '{}'", string))
        })
    }
}

impl std::cmp::PartialEq<SnakeCase> for &str {
    fn eq(&self, other: &SnakeCase) -> bool {
        *self == other.as_str()
    }
}

impl std::cmp::PartialEq<str> for SnakeCase {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl std::cmp::PartialEq<&str> for SnakeCase {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl std::cmp::PartialEq<String> for SnakeCase {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == *other
    }
}

// ----------------------------------------------------------------------------

/// An non-owning string type that can only refer to string containing valid snake_case.
/// In other words, it always matches  ^[_a-z][_a-z0-9]*$
/// * Non-empty
/// * Starts with a lower case ASCII letter or underscore
/// * Contains only lower case ASCII letters, underscores and digits
#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct SnakeCaseRef<'a>(&'a str);

impl<'a> SnakeCaseRef<'a> {
    pub const fn try_from_str(s: &str) -> Result<SnakeCaseRef, InvalidSnakeCase> {
        if is_snake_case(s) {
            Ok(SnakeCaseRef(s))
        } else {
            Err(InvalidSnakeCase)
        }
    }

    pub const fn as_str(&self) -> &'a str {
        self.0
    }

    pub fn to_owned(&self) -> SnakeCase {
        SnakeCase(self.0.to_string())
    }
}

impl<'a> TryFrom<&'a str> for SnakeCaseRef<'a> {
    type Error = InvalidSnakeCase;

    fn try_from(s: &'a str) -> Result<Self, Self::Error> {
        SnakeCaseRef::try_from_str(s)
    }
}

impl std::borrow::Borrow<str> for SnakeCaseRef<'_> {
    fn borrow(&self) -> &str {
        &self.0
    }
}

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

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

impl std::cmp::PartialEq<SnakeCaseRef<'_>> for str {
    fn eq(&self, other: &SnakeCaseRef<'_>) -> bool {
        self == other.0
    }
}

impl std::cmp::PartialEq<SnakeCaseRef<'_>> for &str {
    fn eq(&self, other: &SnakeCaseRef<'_>) -> bool {
        *self == other.0
    }
}

impl std::cmp::PartialEq<str> for SnakeCaseRef<'_> {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl std::cmp::PartialEq<&str> for SnakeCaseRef<'_> {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl std::cmp::PartialEq<String> for SnakeCaseRef<'_> {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == *other
    }
}

// ----------------------------------------------------------------------------

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

    #[test]
    fn snake_case() {
        assert_eq!(SnakeCase::try_from_str("_hello42").unwrap(), "_hello42");
        assert_eq!(
            SnakeCase::try_from_str("_hello42").unwrap(),
            "_hello42".to_string()
        );
        assert_eq!("_hello42", SnakeCase::try_from_str("_hello42").unwrap());
        assert!(SnakeCase::try_from_str("").is_err());
        assert!(SnakeCase::try_from_str("42").is_err());
        assert!(SnakeCase::try_from_str("_").is_ok());
    }

    #[test]
    fn snake_case_ref() {
        assert_eq!(SnakeCaseRef::try_from_str("_hello42").unwrap(), "_hello42");
        assert_eq!(
            SnakeCaseRef::try_from_str("_hello42").unwrap(),
            "_hello42".to_string()
        );
        assert_eq!("_hello42", SnakeCaseRef::try_from_str("_hello42").unwrap());
        assert!(SnakeCaseRef::try_from_str("").is_err());
        assert!(SnakeCaseRef::try_from_str("42").is_err());
        assert!(SnakeCaseRef::try_from_str("_").is_ok());
    }

    #[test]
    fn snake_case_conversions() {
        let sc = SnakeCase::try_from_str("hello_world").unwrap();
        let scr: SnakeCaseRef = sc.as_ref();
        assert_eq!(scr, "hello_world");
        let sc2: SnakeCase = scr.to_owned();
        assert_eq!(sc2, "hello_world");

        use std::collections::HashSet;
        let mut set: HashSet<SnakeCase> = HashSet::new();
        set.insert(SnakeCase::try_from_str("hello_world").unwrap());
        assert!(set.contains(SnakeCaseRef::try_from_str("hello_world").unwrap().as_str()));
    }
}