non 0.1.0

Type-safe wrappers for strings with compile-time guarantees.
Documentation
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! Type-safe wrappers for strings with compile-time guarantees.
//!
//! This crate provides zero-cost wrapper types around `String` that encode
//! specific invariants at the type level, preventing invalid states at compile time.
//!
//! # Types
//!
//! - [`NonEmpty`] - A string that is guaranteed to contain at least one character
//! - [`NonBlank`] - A string that is guaranteed to be non-empty and contain at least one non-whitespace character
//! - [`ASCII`] - A string that is guaranteed to contain only ASCII characters
//! - [`ExactLength`] - A string that is guaranteed to have exactly N characters
//! - [`Trimmed`] - A string that is guaranteed to be trimmed (no leading or trailing whitespace)
//! - [`Alphanumeric`] - A string that is guaranteed to only contain alphanumeric characters
//! - [`LowerCase`] - A string that is guaranteed to be all lowercase
//! - [`UpperCase`] - A string that is guaranteed all uppercase
//!
//! # Examples
//!
//! ```
//! use non::{NonEmpty, NonBlank, ASCII, ExactLength};
//!
//! // NonEmpty rejects empty strings
//! let valid = NonEmpty::new("hello".to_string()).unwrap();
//! let invalid = NonEmpty::new(String::new());
//! assert!(invalid.is_none());
//!
//! // NonBlank rejects whitespace-only strings
//! let valid = NonBlank::new("hello".to_string()).unwrap();
//! let invalid = NonBlank::new("   ".to_string());
//! assert!(invalid.is_none());
//!
//! // ASCII rejects non-ASCII characters
//! let valid = ASCII::new("hello".to_string()).unwrap();
//! let invalid = ASCII::new("cześć".to_string());
//! assert!(invalid.is_none());
//!
//! // ExactLength rejects strings that don't have exactly N chars
//! let valid = ExactLength::<2>::new("hi".to_string()).unwrap();
//! let invalid = ExactLength::<3>::new("helo world".to_string());
//! assert!(invalid.is_none());
//! ```
//!
//! # Deref Behavior
//!
//! All types implement `Deref<Target = String>`, giving you access to all `String` methods:
//!
//! ```
//! use non::NonEmpty;
//!
//! let s = NonEmpty::new("hello world".to_string()).unwrap();
//! assert_eq!(s.len(), 11);
//! assert!(s.contains("world"));
//! ```
//!
//! # Conversions
//!
//! All types can be converted back to `String` using `Into`:
//!
//! ```
//! use non::NonEmpty;
//!
//! let non_empty = NonEmpty::new("hello".to_string()).unwrap();
//! let s: String = non_empty.into();
//! ```
//!
//! # Composing Wrappers
//!
//! You can compose multiple wrappers together:
//!
//! ```
//! use non::{NonEmpty, ASCII};
//!
//! // Create a non-empty ASCII string
//! let non_empty = NonEmpty::new("hello".to_string()).unwrap();
//! let ascii_non_empty = ASCII::new(non_empty).unwrap();
//!
//! // Type is: ASCII<NonEmpty<String>>
//! assert_eq!(ascii_non_empty.as_ref(), "hello");
//! ```
//!
//! # Stripping Wrappers
//!
//! Use the [`Strip`] trait to remove one layer of wrapping:
//!
//! ```
//! use non::{NonEmpty, ASCII, Strip};
//!
//! let non_empty = NonEmpty::new("hello".to_string()).unwrap();
//! let ascii_non_empty = ASCII::new(non_empty).unwrap();
//!
//! // Strip the NonEmpty layer: ASCII<NonEmpty<String>> -> ASCII<String>
//! let ascii_only = ascii_non_empty.strip();
//! assert_eq!(ascii_only, ASCII::new("hello".to_string()).unwrap());
//! ```
//!
//! # `no_std` Support
//!
//! This crate supports `no_std` environments with `alloc`. To use in `no_std`:
//!
//! ```toml
//! [dependencies]
//! non = { version = "0.1", default-features = false }
//! ```
//!
//! # Features
//!
//! - `std` (default) - Enables standard library support

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(feature = "std")]
use std::string::String;

#[cfg(not(feature = "std"))]
use alloc::string::String;

#[cfg(feature = "std")]
use std::fmt::{Display, Formatter, Result};

#[cfg(not(feature = "std"))]
use core::fmt::{Display, Formatter, Result};

#[cfg(feature = "std")]
use std::ops::Deref;

#[cfg(not(feature = "std"))]
use core::ops::Deref;

/// Strips one layer of wrapper from nested types.
///
/// All wrapper types support `.strip()` to unwrap one layer.
/// This is crucial for converting `Type<Wrapper<String>>` to `Type<String>`.
///
/// # Example
///
/// ```
/// use non::{NonEmpty, Strip, ASCII};
/// let non_empty = NonEmpty::new("hello".to_string()).unwrap();
/// let ascii = ASCII::new(non_empty).unwrap();
/// assert_eq!(
///     ascii.strip(), // ASCII<NonEmpty<String>> -> ASCII<String>
///     ASCII::new("hello".to_string()).unwrap()
/// );
/// ```
pub trait Strip {
    type Output;

    fn strip(&self) -> Self::Output;
}

macro_rules! non {
    (string, $name: ident<$param: ident>, $func: expr, $guarantee: expr, $guarantee2: expr) => {
        #[doc = "A string that is known to "]
        #[doc = $guarantee2]
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #[repr(transparent)]
        pub struct $name<$param = String>($param);

        impl<$param> $name<$param>
        where
            $param: AsRef<str>
        {
            #[doc = "Creates a new `" ]
            #[doc = stringify!($name) ]
            #[doc = "` string if the string is "]
            #[doc = $guarantee]
            #[inline]
            pub fn new(value: $param) -> Option<Self> {
                if $func(&value) {
                    Some($name(value))
                } else {
                    None
                }
            }

            #[doc = "Creates a new `" ]
            #[doc = stringify!($name) ]
            #[doc = "` without checking the value."]
            ///
            /// # Safety
            #[doc = "The value must be "]
            #[doc = $guarantee]
            #[inline]
            pub unsafe fn new_unchecked(value: $param) -> Self {
                Self(value)
            }

            /// Returns the inner value
            #[inline]
            pub fn into_inner(self) -> $param {
                self.0
            }

            /// Gets a reference to the inner value
            #[inline]
            pub fn inner(&self) -> &$param {
                &self.0
            }
        }

        impl<$param> Deref for $name<$param> {
            type Target = $param;

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

        impl<$param> From<$name<$param>> for String 
        where
            $param: Into<String>
        {
            fn from(value: $name<$param>) -> Self {
                value.0.into()
            }
        }

        impl<$param> AsRef<str> for $name<$param> 
        where
            $param: AsRef<str>
        {
            fn as_ref(&self) -> &str {
                self.0.as_ref()
            }
        }

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

        impl<$param, Z> Strip for $name<$param>
        where
            $param: NotString + AsRef<str> + Deref<Target = Z>,
            Z: AsRef<str> + Clone
        {
            type Output = $name<Z>;
            fn strip(&self) -> Self::Output{
                unsafe { $name::<Z>::new_unchecked((*self.0).clone()) }
            }
        }
    };
    (string, $name: ident<$param: ident, const $param2: ident: $param3: ident>, $func: expr, $guarantee: expr, $guarantee2: expr) => {
        #[doc = "A string that is known to "]
        #[doc = $guarantee2]
        pub struct $name<const $param2: $param3, $param = String>($param);

        impl<$param, const $param2: $param3> $name<$param2, $param>
        where
            $param: AsRef<str>
        {
            #[doc = "Creates a new `" ]
            #[doc = stringify!($name) ]
            #[doc = "` string if the string is "]
            #[doc = $guarantee]
            #[inline]
            pub fn new(value: $param) -> Option<Self> {
                if $func(&value) {
                    Some($name(value))
                } else {
                    None
                }
            }

            #[doc = "Creates a new `" ]
            #[doc = stringify!($name) ]
            #[doc = "` without checking the value."]
            ///
            /// # Safety
            #[doc = "The value must be "]
            #[doc = $guarantee]
            #[inline]
            pub unsafe fn new_unchecked(value: $param) -> Self {
                Self(value)
            }

            /// Returns the inner value
            #[inline]
            pub fn into_inner(self) -> $param {
                self.0
            }

            /// Gets a reference to the inner value
            #[inline]
            pub fn inner(&self) -> &$param {
                &self.0
            }
        }

        impl<$param, const $param2: $param3> Deref for $name<$param2, $param> {
            type Target = $param;

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

        impl<$param, const $param2: $param3> From<$name<$param2, $param>> for String
        where
            $param: Into<String>
        {
            fn from(value: $name<$param2, $param>) -> Self {
                value.0.into()
            }
        }

        impl<$param, const $param2: $param3> AsRef<str> for $name<$param2, $param>
        where
            $param: AsRef<str>
        {
            fn as_ref(&self) -> &str {
                self.0.as_ref()
            }
        }

        impl<$param, const $param2: $param3> Display for $name<$param2, $param>
        where
            $param: Display
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> Result {
                self.0.fmt(f)
            }
        }

        impl<$param, Z, const $param2: $param3> Strip for $name<$param2, $param>
        where
            $param: NotString + AsRef<str> + Deref<Target = Z>,
            Z: AsRef<str> + Clone
        {
            type Output = $name<$param2, Z>;
            fn strip(&self) -> Self::Output{
                unsafe { $name::<$param2, Z>::new_unchecked((*self.0).clone()) }
            }
        }
    };
}

mod sealed {
    pub trait NotString {}
    impl<T> NotString for T where T: AsRef<str> + Clone {}
}
use sealed::NotString;

non!(string, NonEmpty<T>,|x: &T| !x.as_ref().is_empty(),"not empty", "not be empty");
non!(string, NonBlank<T>,|x: &T| !x.as_ref().chars().all(|y| y.is_whitespace()),"not only whitespace", "not be only whitespace");
non!(string, ASCII<T>,|x: &T| x.as_ref().is_ascii(),"ascii encoded", "be ascii encoded");
non!(string, ExactLength<T, const N: usize>, |x: &T| x.as_ref().chars().count() == N, "exactly N characters long", "have exactly N characters");
non!(string, LowerCase<T>, |x: &T| { let s = x.as_ref(); s.to_lowercase() == s }, "all lowercase", "be all lowercase");
non!(string, UpperCase<T>, |x: &T| { let s = x.as_ref(); s.to_uppercase() == s }, "all uppercase", "be all uppercase");
non!(string, Trimmed<T>, |x: &T| x.as_ref() == x.as_ref().trim(), "trimmed (no leading or trailing whitespace)", "be trimmed");
non!(string, Alphanumeric<T>, |x: &T| x.as_ref().chars().all(|c| c.is_alphanumeric()), "only alphanumeric characters", "contain only alphanumeric characters");

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

    #[test]
    fn test_non_empty_new_some() {
        let s = String::from("helo world");
        let non_empty = NonEmpty::new(s);
        assert!(non_empty.is_some());
    }
    
    #[test]
    fn test_non_empty_new_none() {
        let s = String::new();
        let empty = NonEmpty::new(s);
        assert!(empty.is_none());
    }
    
    #[test]
    fn test_non_empty_new_unchecked() {
        let s = String::from("helo world");
        let non_empty = unsafe { NonEmpty::new_unchecked(s.clone()) };
        assert_eq!(*non_empty, s);
    }
    
    #[test]
    fn test_ascii_new_some() {
        let s = String::from("helo world");
        let ascii = ASCII::new(s);
        assert!(ascii.is_some());
    }
    
    #[test]
    fn test_ascii_new_none() {
        let s = String::from("cześć");
        let ascii = ASCII::new(s);
        assert!(ascii.is_none());
    }
    
    #[test]
    fn test_ascii_new_unchecked() {
        let s = String::from("helo world");
        let ascii = unsafe { ASCII::new_unchecked(s.clone()) };
        assert_eq!(*ascii, s);
    }
    
    #[test]
    fn test_non_blank_new_some() {
        let s = String::from("helo world");
        let nonblank = NonBlank::new(s);
        assert!(nonblank.is_some());
    }
    
    #[test]
    fn test_non_blank_new_none() {
        let s = String::from("    \n");
        let nonblank = NonBlank::new(s);
        assert!(nonblank.is_none());
    }
    
    #[test]
    fn test_non_blank_new_unchecked() {
        let s = String::from("helo world");
        let nonblank = unsafe { NonBlank::new_unchecked(s.clone()) };
        assert_eq!(*nonblank, s);
    }

    #[test]
    fn test_exact_length_new_some() {
        let s = String::from("hi");
        let exact_length = ExactLength::<2>::new(s);
        assert!(exact_length.is_some());
    }

    #[test]
    fn test_exact_length_new_none() {
        let s = String::from("helo world");
        let exact_length = ExactLength::<2>::new(s);
        assert!(exact_length.is_none());
    }

    #[test]
    fn test_exact_length_new_unchecked() {
        let s = String::from("hi!");
        let exact_length = unsafe { ExactLength::<3>::new_unchecked(s.clone()) };
        assert_eq!(*exact_length, s);
    }
    
    #[test]
    fn test_combinations() {
        let s = String::from("helo world");
        let nonblank =  NonBlank::new(s.clone());
        assert!(nonblank.is_some());
        let ascii = ASCII::new(nonblank.unwrap());
        assert!(ascii.is_some());
        let ascii = ascii.unwrap();
        assert_eq!(ascii.as_ref(), s);
    }

    #[test]
    fn test_strip() {
        let s = String::from("helo world");
        let nonblank = NonBlank::new(s.clone());
        assert!(nonblank.is_some());
        let ascii = ASCII::new(nonblank.unwrap());
        assert!(ascii.is_some());
        let ascii = ascii.unwrap();
        unsafe { assert_eq!(ascii.strip(), ASCII::new_unchecked(s)); }
    }
}