non_empty_string/
lib.rs

1#![doc(issue_tracker_base_url = "https://github.com/MidasLamb/non-empty-string/issues/")]
2
3//! # NonEmptyString
4//! A simple wrapper type for `String`s that ensures that the string inside is not `.empty()`, meaning that the length > 0.
5
6// Test the items in the readme file.
7#[cfg(doctest)]
8mod test_readme {
9    #[doc = include_str!("../README.md")]
10    mod something {}
11}
12
13use std::str::FromStr;
14
15use delegate::delegate;
16
17#[cfg(feature = "serde")]
18mod serde_support;
19
20#[cfg(feature = "macros")]
21mod macros;
22
23mod trait_impls;
24
25/// A simple String wrapper type, similar to NonZeroUsize and friends.
26/// Guarantees that the String contained inside is not of length 0.
27#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
28#[repr(transparent)]
29pub struct NonEmptyString(String);
30
31#[allow(
32    clippy::len_without_is_empty,
33    reason = "is_empty would always returns false so it seems a bit silly to have it."
34)]
35impl NonEmptyString {
36    /// Attempts to create a new `NonEmptyString`.
37    /// If the given `string` is empty, `Err` is returned, containing the original `String`, `Ok` otherwise.
38    pub fn new(string: String) -> Result<Self, String> {
39        if string.is_empty() {
40            Err(string)
41        } else {
42            Ok(NonEmptyString(string))
43        }
44    }
45    /// Creates a new `NonEmptyString`, assuming `string` is not empty.
46    ///
47    /// # Safety
48    /// If the given `string` is empty, it'll be undefined behavior.
49    pub unsafe fn new_unchecked(string: String) -> Self {
50        Self::new(string).unwrap_unchecked()
51    }
52
53    /// Returns a reference to the contained value.
54    pub fn get(&self) -> &str {
55        &self.0
56    }
57
58    /// Consume the `NonEmptyString` to get the internal `String` out.
59    pub fn into_inner(self) -> String {
60        self.0
61    }
62
63    // These are safe methods that can simply be forwarded.
64    delegate! {
65        to self.0 {
66            /// Is forwarded to the inner String.
67            /// See [`String::into_bytes`]
68            pub fn into_bytes(self) -> Vec<u8>;
69
70            /// Is forwarded to the inner String.
71            /// See [`String::as_str`]
72            pub fn as_str(&self) -> &str;
73
74            /// Is forwarded to the inner String.
75            /// See [`String::push_str`]
76            pub fn push_str(&mut self, string: &str);
77
78            /// Is forwarded to the inner String.
79            /// See [`String::capacity`]
80            pub fn capacity(&self) -> usize;
81
82            /// Is forwarded to the inner String.
83            /// See [`String::reserve`]
84            pub fn reserve(&mut self, additional: usize);
85
86            /// Is forwarded to the inner String.
87            /// See [`String::reserve_exact`]
88            pub fn reserve_exact(&mut self, additional: usize);
89
90            // For some reason we cannot delegate the following:
91            // pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
92
93            /// Is forwarded to the inner String.
94            /// See [`String::try_reserve_exact`]
95            pub fn try_reserve_exact(
96                &mut self,
97                additional: usize
98            ) -> Result<(), std::collections::TryReserveError>;
99
100            /// Is forwarded to the inner String.
101            /// See std::string::String::[`(&`]
102            pub fn shrink_to_fit(&mut self);
103
104            /// Is forwarded to the inner String.
105            /// See [`String::shrink_to`]
106            pub fn shrink_to(&mut self, min_capacity: usize);
107
108            /// Is forwarded to the inner String.
109            /// See [`String::push`]
110            pub fn push(&mut self, ch: char);
111
112            /// Is forwarded to the inner String.
113            /// See [`String::as_bytes`]
114            pub fn as_bytes(&self) -> &[u8];
115
116            /// Is forwarded to the inner String.
117            /// See [`String::insert`]
118            pub fn insert(&mut self, idx: usize, ch: char);
119
120            /// Is forwarded to the inner String.
121            /// See [`String::insert_str`]
122            pub fn insert_str(&mut self, idx: usize, string: &str);
123
124            /// Is forwarded to the inner String.
125            /// See [`String::len`]
126            pub fn len(&self) -> usize;
127
128            /// Is forwarded to the inner String.
129            /// See [`String::into_boxed_str`]
130            pub fn into_boxed_str(self) -> Box<str>;
131        }
132    }
133}
134
135impl AsRef<str> for NonEmptyString {
136    fn as_ref(&self) -> &str {
137        &self.0
138    }
139}
140
141impl AsRef<String> for NonEmptyString {
142    fn as_ref(&self) -> &String {
143        &self.0
144    }
145}
146
147impl<'s> TryFrom<&'s str> for NonEmptyString {
148    type Error = &'s str;
149
150    fn try_from(value: &'s str) -> Result<Self, Self::Error> {
151        if value.is_empty() {
152            return Err(value);
153        }
154
155        Ok(NonEmptyString(value.to_owned()))
156    }
157}
158
159impl TryFrom<String> for NonEmptyString {
160    type Error = String;
161
162    fn try_from(value: String) -> Result<Self, Self::Error> {
163        NonEmptyString::new(value)
164    }
165}
166
167impl FromStr for NonEmptyString {
168    type Err = <NonEmptyString as TryFrom<String>>::Error;
169
170    fn from_str(s: &str) -> Result<Self, Self::Err> {
171        <Self as TryFrom<String>>::try_from(s.to_string())
172    }
173}
174
175impl From<NonEmptyString> for String {
176    fn from(value: NonEmptyString) -> Self {
177        value.0
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use std::hash::Hash;
184
185    use super::*;
186
187    #[test]
188    fn empty_string_returns_err() {
189        assert_eq!(NonEmptyString::new("".to_owned()), Err("".to_owned()));
190    }
191
192    #[test]
193    fn non_empty_string_returns_ok() {
194        assert!(NonEmptyString::new("string".to_owned()).is_ok())
195    }
196
197    #[test]
198    fn what_goes_in_comes_out() {
199        assert_eq!(
200            NonEmptyString::new("string".to_owned())
201                .unwrap()
202                .into_inner(),
203            "string".to_owned()
204        );
205    }
206
207    #[test]
208    fn as_ref_str_works() {
209        let nes = NonEmptyString::new("string".to_owned()).unwrap();
210        let val: &str = nes.as_ref();
211        assert_eq!(val, "string");
212    }
213
214    #[test]
215    fn as_ref_string_works() {
216        let nes = NonEmptyString::new("string".to_owned()).unwrap();
217        let val: &String = nes.as_ref();
218        assert_eq!(val, "string");
219    }
220
221    #[test]
222    fn calling_string_methods_works() {
223        let nes = NonEmptyString::new("string".to_owned()).unwrap();
224        // `len` is a `String` method.
225        assert!(nes.len() > 0);
226    }
227
228    #[test]
229    fn format_test() {
230        let str = NonEmptyString::new("string".to_owned()).unwrap();
231        println!("{}", &str);
232        assert_eq!(String::from("string"), str.to_string())
233    }
234
235    #[test]
236    fn from_str_works() {
237        let valid_str = "string";
238        let non_empty_string = NonEmptyString::from_str(valid_str).unwrap();
239        let parsed: NonEmptyString = valid_str.parse().unwrap();
240        assert_eq!(non_empty_string, parsed);
241    }
242
243    #[test]
244    fn into_works() {
245        let non_empty_string = NonEmptyString::new("string".to_string()).unwrap();
246        let _string: String = non_empty_string.into();
247
248        let non_empty_string = NonEmptyString::new("string".to_string()).unwrap();
249        let _string = String::from(non_empty_string);
250    }
251
252    #[test]
253    fn hash_works() {
254        fn is_hash<T: Hash>() {}
255        is_hash::<NonEmptyString>();
256    }
257}