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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! # Copy String
//! Strings that exist on the stack. This makes them `Copy`. Useful for when you want to
//! keep some small text inside a struct or enum and retain copy semantics. Strings are
//! stored as a byte array with UTF8 conversion on the fly.
use std::{
    fmt,
    error,
    str::Utf8Error,
    cmp::{Ord, Ordering},
};

#[cfg(feature = "serde")]
use serde::{
    Serialize,
    Serializer,
    Deserialize,
    Deserializer,
    de::{Visitor, Error as DeError}
};

/// Convenience trait to blanked impl `PartialOrd` and `PartialEq` on all `copystr`
/// variants and `String` and `&str`.
pub trait CopystrComparable {
    fn relevant_bytes(&self) -> &[u8];
}

impl CopystrComparable for String {
    fn relevant_bytes(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl CopystrComparable for &str {
    fn relevant_bytes(&self) -> &[u8] {
        self.as_bytes()       
    }
}

#[macro_export]
macro_rules! csstruct {
    ($css:ident, $asize:expr) => {
        #[allow(non_camel_case_types)]
        #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
        pub struct $css {            
            raw: [u8; $asize],
            len: usize,
        }

        impl $css {
            pub fn new(string: &str) -> Result<Self, Error> {
                $css::from_slice(string.as_bytes())
            }

            /// Doesn't check UTF8, only if slice length is within capacity.
            pub fn from_slice(raw: &[u8]) -> Result<Self, Error> {
                let len = raw.len();
                if len > $asize {
                    return Err(Error::TooBig($asize, len));                    
                }

                let mut writeable: [u8; $asize] = [0; $asize];
                let (writearea, _) = writeable.split_at_mut(len);
                writearea.copy_from_slice(&raw);

                Ok($css { raw: writeable, len })
            }

            /// Const create by consuming an array. Length is set to the full length of the
            /// array. Doesn't UTF8 check! Watch out.
            pub const fn assume_from_array(arr: [u8; $asize]) -> Self {
                $css { raw: arr, len: $asize }
            }
            
            pub fn capacity() -> usize {
                $asize
            }

            pub fn len(&self) -> usize {
                self.len
            }

            pub fn is_empty(&self) -> bool {
                self.len == 0
            }

            /// Carry out on-the-fly `UTF8` conversion. Panics if this is violated.
            pub fn as_str(&self) -> &str {
                let (s, _) = self.raw.split_at(self.len);
                std::str::from_utf8(s).expect("Invalid UTF8.")
            }

            pub fn try_as_str(&self) -> Result<&str, Error> {
                let (s, _) = self.raw.split_at(self.len);
                std::str::from_utf8(s).map_err(|e| Error::from(e))
            }

            pub fn as_bytes(&self) -> &[u8] {
                let (b, _) = self.raw.split_at(self.len);
                b
            }

            pub fn as_all_bytes(&self) -> &[u8] {
                &self.raw
            }
        }

        impl std::convert::TryFrom<&str> for $css {
            type Error = Error;

            fn try_from(value: &str) -> Result<Self, Self::Error> {
                $css::new(value)
            }
        }

        impl fmt::Display for $css {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "{}", self.as_str())
            }
        }

        impl Default for $css {
            fn default() -> Self {
                $css {
                    raw: [0; $asize],
                    len: 0,
                }
            }
        }

        impl<T: CopystrComparable> PartialEq<T> for $css {
            #[inline]
            fn eq(&self, other: &T) -> bool {
                self.as_bytes() == other.relevant_bytes()
            }

            #[inline]
            fn ne(&self, other: &T) -> bool {
                !(self).eq(other)
            }
        }

        impl<T: CopystrComparable> PartialOrd<T> for $css {
            #[inline]
            fn partial_cmp(&self, other: &T) -> Option<Ordering> {
                Some(self.as_bytes().cmp(other.relevant_bytes()))
            }
        }

        #[cfg(feature = "serde")]
        impl Serialize for $css {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.serialize_str(self.as_str())
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> Deserialize<'de> for $css {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where D: Deserializer<'de>
            {
                struct CSSVisitor;

                impl<'de> Visitor<'de> for CSSVisitor {
                    type Value = $css;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        let msg = format!("a UTF-8 string no bigger than {} bytes", $asize);
                        formatter.write_str(msg.as_str())
                    }

                    fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {
                        $css::new(v).map_err(|e| E::custom(e))
                    }

                    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
                    where E: DeError,
                    {
                        $css::new(v).map_err(|e| E::custom(e))
                    }

                    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
                    where E: DeError,
                    {
                        $css::new(v.as_str()).map_err(|e| E::custom(e))
                    }
                }

                deserializer.deserialize_str(CSSVisitor)
            }
        }
    };
}

csstruct!(s3, 3);
csstruct!(s4, 4);

csstruct!(s5, 5);
csstruct!(s6, 6);
csstruct!(s7, 7);

csstruct!(s8, 8);

csstruct!(s9, 9);
csstruct!(s10, 10);
csstruct!(s11, 11);
csstruct!(s12, 12);
csstruct!(s13, 13);
csstruct!(s14, 14);
csstruct!(s15, 15);

csstruct!(s16, 16);

csstruct!(s17, 17);
csstruct!(s18, 18);
csstruct!(s19, 19);
csstruct!(s20, 20);
csstruct!(s21, 21);
csstruct!(s22, 22);
csstruct!(s23, 23);
csstruct!(s24, 24);
csstruct!(s25, 25);
csstruct!(s26, 26);
csstruct!(s27, 27);
csstruct!(s28, 28);
csstruct!(s29, 29);
csstruct!(s30, 30);
csstruct!(s31, 31);

csstruct!(s32, 32);

macro_rules! impl_copystr_comp {
    ($css:ident, $ ($o:ident),+ ) => {
        $(
            impl PartialEq<$o> for $css {
                #[inline]
                fn eq(&self, other: &$o) -> bool {
                    self.as_bytes() == other.as_bytes()
                }
                
                #[inline]
                fn ne(&self, other: &$o) -> bool {
                    !(self).eq(other)
                }
            }
            
            impl PartialOrd<$o> for $css {
                #[inline]
                fn partial_cmp(&self, other: &$o) -> Option<Ordering> {
                    Some(self.as_bytes().cmp(other.as_bytes()))
                }
            }
        )*
    };
}

impl_copystr_comp!(s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s4, s3, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s5, s3, s4, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s6, s3, s4, s5, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s7, s3, s4, s5, s6, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s8, s3, s4, s5, s6, s7, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s9, s3, s4, s5, s6, s7, s8, s10, s11, s12, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s10, s3, s4, s5, s6, s7, s8, s9, s11, s12, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s11, s3, s4, s5, s6, s7, s8, s9, s10, s12, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s12, s3, s4, s5, s6, s7, s8, s9, s10, s11, s13, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s13, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s14, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s14, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s15, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s15, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s16, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s16, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s17, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s17, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s18,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s18, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s19, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s20, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s21, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s22, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s23, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s24, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s23, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s25, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s23, s24, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s26, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s23, s24, s25, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s27, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s23, s24, s25, s26, s28, s29, s30, s31, s32);
impl_copystr_comp!(s28, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s29, s30, s31, s32);
impl_copystr_comp!(s29, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s30, s31, s32);
impl_copystr_comp!(s30, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s31, s32);
impl_copystr_comp!(s31, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s32);
impl_copystr_comp!(s32, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
                   s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31);


pub type CopyStringCapacity = usize;
pub type StringLength = usize;

/// Errors caught in construction via `new` or `from_slice`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// Valid UTF must exist in the byte array at all times.
    InvalidUtf8(Utf8Error),

    /// The source `&str` is larger than the internal fixed array capacity.
    TooBig(CopyStringCapacity, StringLength),

    /// For compatibility with serde error trait. Contain a string error msg.
    Msg(String),
}

impl Error {
    pub fn into_msg(self) -> Self {
        let msg = self.to_string();
        Error::Msg(msg)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::InvalidUtf8(e) => write!(f, "{}", &e),
            Self::TooBig(mlen, slen) => write!(
                f,
                "String length {} larger than internal array len {}.",
                &mlen,
                &slen,
            ),
            Self::Msg(m) => write!(f, "{}", &m),
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Self::InvalidUtf8(e) => Some(e),
            _ => None,
        }
    }
}

#[cfg(feature = "serde")]
impl DeError for Error {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        Error::Msg(msg.to_string())
    }    
}
        

impl From<Utf8Error> for Error {
    fn from(e: Utf8Error) -> Self {
        Error::InvalidUtf8(e)
    }
}
    
#[cfg(test)]
mod tests {
    use std::{
        convert::TryFrom,
        error,
    };

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

    #[cfg(feature = "serde")]
    #[derive(Serialize, Deserialize)]
    struct Msg {
        val: usize,
        txt: s4,
    }
    
    #[test]
    fn copy_string_struct() {
        let cs = s4::try_from("ABC").unwrap();
        assert_eq!(cs.as_str(), "ABC");
    }

    #[test]
    fn new_string_struct() {
        let cs = s8::new("It's me!").unwrap();
        assert_eq!(cs.as_str(), "It's me!");
    }

    #[test]
    fn default_ok() {
        let cs = s16::default();
        assert!(cs.len() == 0);
        assert_eq!(cs.as_str(), "");
    }

    #[test]
    fn display() {
        let cs = s4::try_from("XYZ").unwrap();
        assert_eq!(cs.to_string(), "XYZ");
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serialize_to_json() -> Result<(), Box<dyn error::Error>> {       
        let cs = s4::new("Yo!")?;
        let msg = Msg {
            val: 10,
            txt: cs,
        };

        let json = serde_json::to_string(&msg)?;
        assert_eq!(r##"{"val":10,"txt":"Yo!"}"##, &json);

        Ok(())
    }

    #[cfg(feature = "serde")]
    #[test]
    fn deserialize_from_json() -> Result<(), Box<dyn error::Error>> {
        let json = r##"{"val":45,"txt":"Hey!"}"##;
        let cs = s4::new("Hey!")?;
        let msg: Msg = serde_json::from_str(json)?;

        assert!(msg.val == 45);
        assert!(msg.txt == cs);

        Ok(())
    }

    #[cfg(feature = "serde")]
    #[test]
    fn deserialize_from_json_too_big() -> Result<(), Box<dyn error::Error>> {
        let json = r##"{"val":45,"txt":"HUGE!"}"##;
        let maybie_msg: Result<Msg, serde_json::Error> = serde_json::from_str(json);

        assert!(maybie_msg.is_err());

        Ok(())
    }

    #[test]
    fn str_comparison_works() -> Result<(), Box<dyn error::Error>> {
        let cs = s6::new("Yeah")?;
        assert!(cs == "Yeah");
        assert!(cs != "Alright");

        Ok(())
    }

    #[test]
    fn string_comparison_works() -> Result<(), Box<dyn error::Error>> {
        let cs = s6::new("Yeah")?;
        assert!(cs == "Yeah".to_string());
        assert!(cs != "Alright".to_string());

        Ok(())
    }

    #[test]
    fn const_construction_should_work() {
        const CS: s5 = s5::assume_from_array([b's', b'm', b'i', b'l', b'e']);
        assert!(CS == "smile");
    }

    #[test]
    fn str_ordering_works() -> Result<(), Box<dyn error::Error>> {
        let cs = s6::new("bcd")?;
        assert!(cs < "cde");
        assert!(cs > "abc");
        assert!(cs > "a");
        assert!(cs >= "bcd");
        assert!(cs <= "bcd");
        Ok(())
    }

    #[test]
    fn string_ordering_works() -> Result<(), Box<dyn error::Error>> {
        let cs = s6::new("bcd")?;
        assert!(cs < "cde".to_string());
        assert!(cs > "abc".to_string());
        assert!(cs > "a".to_string());
        assert!(cs >= "bcd".to_string());
        assert!(cs <= "bcd".to_string());
        Ok(())
    }

    #[test]
    fn same_sized_copystr_comparison_works() -> Result<(), Box<dyn error::Error>> {
        let cs1 = s6::new("bcd")?;
        let cs2 = s6::new("bcd")?;
        assert!(cs1 == cs2);
        Ok(())
    }

    #[test]
    fn different_sized_copystr_comparison_works() -> Result<(), Box<dyn error::Error>> {
        let cs1 = s6::new("bcd")?;
        let cs2 = s5::new("bcd")?;
        assert!(cs1 == cs2);
        Ok(())
    }

    const MT1: s3 = s3::assume_from_array([b'b', b'c', b'a']);
    const MT2: s3 = s3::assume_from_array([b'b', b'c', b'd']);

    #[test]
    fn same_size_copystr_match_works() -> Result<(), Box<dyn error::Error>> {
        let val = s3::new("bca")?;

        match val {
            MT1 => Ok(()),
            MT2 => panic!("Matched wrong copystr"),
            _ => panic!("Didn't match copystr"),
        }
    }
}