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
//! String utility types.

use std::{borrow::Cow, fmt};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A string which can never be empty.
pub struct NonEmptyString(Cow<'static, str>);

crate::macros::error::static_str_error! {
    #[doc = "empty string"]
    pub struct EmptyStringErr;
}

impl NonEmptyString {
    /// Creates a non-empty string a compile time.
    ///
    /// This function requires the static string be non-empty.
    ///
    /// # Panics
    ///
    /// This function panics at **compile time** when the static string is empty.
    pub const fn from_static(src: &'static str) -> NonEmptyString {
        if src.is_empty() {
            panic!("empty static string");
        }

        NonEmptyString(Cow::Borrowed(src))
    }

    /// Views this [`NonEmptyString`] as a string slice.
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }
}

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

impl From<NonEmptyString> for String {
    fn from(value: NonEmptyString) -> Self {
        value.0.to_string()
    }
}

impl TryFrom<String> for NonEmptyString {
    type Error = EmptyStringErr;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.is_empty() {
            Err(Self::Error::default())
        } else {
            Ok(Self(Cow::Owned(value)))
        }
    }
}

impl TryFrom<&String> for NonEmptyString {
    type Error = EmptyStringErr;

    fn try_from(value: &String) -> Result<Self, Self::Error> {
        if value.is_empty() {
            Err(Self::Error::default())
        } else {
            Ok(Self(Cow::Owned(value.clone())))
        }
    }
}

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

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        if value.is_empty() {
            Err(Self::Error::default())
        } else {
            Ok(Self(Cow::Owned(value.to_owned())))
        }
    }
}

impl std::str::FromStr for NonEmptyString {
    type Err = EmptyStringErr;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.try_into()
    }
}

impl AsRef<str> for NonEmptyString {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

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

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

impl PartialEq<&String> for NonEmptyString {
    fn eq(&self, other: &&String) -> bool {
        self.0.as_ref() == *other
    }
}

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

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

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

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

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

impl serde::Serialize for NonEmptyString {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.0.serialize(serializer)
    }
}

impl<'de> serde::Deserialize<'de> for NonEmptyString {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.try_into().map_err(serde::de::Error::custom)
    }
}

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

    fn assert_try_into_err(src: impl TryInto<NonEmptyString>) {
        assert!(src.try_into().is_err());
    }

    fn assert_try_into_ok<S>(src: S)
    where
        S: TryInto<NonEmptyString, Error: std::error::Error>
            + fmt::Debug
            + Clone
            + PartialEq<NonEmptyString>,
    {
        let expected = src.clone();
        let value: NonEmptyString = src.try_into().unwrap();
        assert_eq!(expected, value);
    }

    #[test]
    fn test_non_empty_string_construction_failure() {
        assert_try_into_err("");
        assert_try_into_err(String::from(""));
        #[allow(clippy::needless_borrows_for_generic_args)]
        assert_try_into_err(&String::from(""));
    }

    #[test]
    fn test_non_empty_string_construction_success() {
        assert_try_into_ok("a");
        assert_try_into_ok(String::from("b"));
        #[allow(clippy::needless_borrows_for_generic_args)]
        assert_try_into_ok(&String::from("c"));
    }
}