devela 0.27.0

A development layer of coherence.
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
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
// devela::text::str::nonul
//
//! Non-nul `String` backed by an array.
//
// TOC
// - definitions
// - trait impls

use crate::{
    Char, CharIter, InvalidText, MismatchedCapacity, NotEnoughElements, NotEnoughSpace, Str, char7,
    char8, char16, charu, is, lets, slice, unwrap, whilst,
};

/* definitions */

/// The nul character.
const NUL_CHAR: char = '\0';

#[doc = crate::_tags!(text)]
/// A null-terminated UTF-8 string with up to `u8::MAX` bytes capacity.
#[doc = crate::_doc_location!("text/str")]
///
/// Suited for write-once or protocol-level text where the length is rarely queried.
/// Uses one less byte of storage, with length determined by scanning.
/// For the opposite trade-off see [`StringU8`][crate::StringU8].
///
/// ## Methods
///
/// - [Constructors](#constructors):
///   [`new`][Self::new],
///   [`from_str`][Self::from_str],
///     *([_truncate][Self::from_str_truncate],
///       [_unchecked][Self::from_str_unchecked])*,
///   [`from_char`][Self::from_char]
///     *([7](Self::from_char7),
///       [8](Self::from_char8),
///       [16](Self::from_char16),
///       [utf8](Self::from_charu))*.
///   [`from_array`][Self::from_array],
#[cfg_attr(
    feature = "unsafe_str",
    doc = "[_unchecked][Self::from_array_unchecked]<sup title='unsafe function'>⚠</sup>."
)]
///
/// - [Deconstructors](#deconstructors):
///   [`into_array`][Self::into_array],
///   [`as_array`][Self::as_array],
///   [`as_bytes`][Self::as_bytes]
#[cfg_attr(
    feature = "unsafe_str",
    doc = "*([mut][Self::as_bytes_mut]<sup title='unsafe function'>⚠</sup>)*."
)]
///   [`as_str`][Self::as_str]
#[cfg_attr(
    feature = "unsafe_str",
    doc = "*([mut][Self::as_mut_str]<sup title='unsafe function'>⚠</sup>)*."
)]
///   [`chars`][Self::chars],
///
/// - [Queries](#queries):
///   [`len`][Self::len],
///   [`is_empty`][Self::is_empty],
///   [`is_full`][Self::is_full],
///   [`capacity`][Self::capacity],
///   [`remaining_capacity`][Self::remaining_capacity].
///
/// - Operations:
///   [`clear`][Self::clear],
///   [`pop`][Self::pop]*([try][Self::try_pop])*,
///   [`push`][Self::push]*([try][Self::try_push])*.
///   [`push_str`][Self::push]*([try][Self::try_push_str])*,
///   [`try_push_str_complete`][Self::try_push_str_complete].
#[must_use]
#[derive(Clone, Copy, Eq, PartialOrd, Ord)]
pub struct StringNonul<const CAP: usize> {
    arr: [u8; CAP],
}

#[rustfmt::skip]
impl<const CAP: usize> StringNonul<CAP> {
    /// Creates a new empty `StringNonul`.
    ///
    /// # Panics
    /// Panics if `CAP` > [`u8::MAX`].
    ///
    /// # Example
    /// ```
    /// # use devela::StringNonul;
    /// let mut s = StringNonul::<10>::new();
    /// assert_eq![size_of_val(&s), 10];
    /// ```
    pub const fn new() -> Self {
        assert![CAP <= u8::MAX as usize, "Mismatched capacity, greater than u8::MAX"];
        Self { arr: [0; CAP] }
    }

    /// Creates a new empty `StringNonul`.
    ///
    /// # Errors
    /// Returns [`MismatchedCapacity`] if `CAP` > [`u8::MAX`].
    pub const fn new_checked() -> Result<Self, MismatchedCapacity> {
        if CAP <= u8::MAX as usize {
            Ok(Self { arr: [0; CAP] })
        } else {
            Err(MismatchedCapacity::too_large(CAP, u8::MAX as usize))
        }
    }

    /// Creates a new `StringNonul` from a complete `&str`.
    ///
    /// # Errors
    /// Returns [`MismatchedCapacity`] if `CAP` > [`u8::MAX`] or if `CAP < string.len()`.
    ///
    /// This is implemented via `Self::`[`try_push_str_complete()`][Self::try_push_str_complete].
    ///
    /// # Example
    /// ```
    /// # use devela::StringU8;
    /// let s = StringU8::<13>::from_str("Hello Wørld!").unwrap();
    /// assert_eq![s.as_str(), "Hello Wørld!"];
    /// ```
    pub const fn from_str(string: &str) -> Result<Self, MismatchedCapacity> {
        let mut new_string = unwrap![ok? Self::new_checked()];
        if new_string.try_push_str_complete(string).is_ok() { Ok(new_string) }
        else { Err(MismatchedCapacity::too_small(CAP, string.len())) }
    }

    /// Creates a new `StringNonul` from a `&str`, truncating if it does not fit.
    ///
    /// Returns [`MismatchedCapacity`] if `CAP` > [`u8::MAX`].
    ///
    /// This is implemented via `Self::`[`push_str()`][Self::push_str].
    pub const fn from_str_truncate(string: &str) -> Result<Self, MismatchedCapacity> {
        let mut new_string = unwrap![ok? Self::new_checked()];
        let _ = new_string.push_str(string);
        Ok(new_string)
    }

    /// Creates a new `StringNonul` from a `&str`, truncating if it does not fit.
    ///
    /// # Panics
    /// Panics if `CAP` > [`u8::MAX`].
    ///
    /// This is implemented via `Self::`[`push_str()`][Self::push_str].
    #[inline(always)]
    pub const fn from_str_unchecked(string: &str) -> Self {
        let mut new_string = Self::new();
        let _ = new_string.push_str(string);
        new_string
    }

    /* queries */

    /// Returns the total capacity in bytes.
    #[must_use] #[inline(always)]
    pub const fn capacity() -> usize { CAP }

    /// Returns the remaining capacity.
    #[must_use] #[inline(always)]
    pub const fn remaining_capacity(&self) -> usize { CAP - self.len() }

    /// Returns the current length.
    ///
    /// Time complexity: O(n) where n is the string length.
    ///
    /// # Examples
    /// ```
    /// # use devela::{StringNonul, MismatchedCapacity};
    /// # fn main() -> Result<(), MismatchedCapacity> {
    /// let mut s = StringNonul::<4>::new_checked()?;
    /// assert_eq![0, s.len()];
    ///
    /// assert_eq![1, s.push('a')];
    /// assert_eq![1, s.len()];
    ///
    /// assert_eq![3, s.push('€')];
    /// assert_eq![4, s.len()];
    /// # Ok(()) }
    /// ```
    #[must_use]
    pub const fn len(&self) -> usize {
        let mut position = 0;
        while position < CAP {
            is![self.arr[position] == 0, break];
            position += 1;
        }
        position
    }

    /// Returns `true` if the current length is 0.
    #[must_use] #[inline(always)]
    pub const fn is_empty(&self) -> bool { self.len() == 0 }

    /// Returns `true` if the current remaining capacity is 0.
    #[must_use] #[inline(always)]
    pub const fn is_full(&self) -> bool { self.len() == CAP }

    /// Checks the equality of two strings, with the same capacity and length.
    ///
    /// It only checks the first `self.len()` bytes.
    /// # Example
    /// ```
    /// # use devela::StringNonul;
    /// let mut a = StringNonul::<16>::from_str_unchecked("hello world!");
    /// let mut b = StringNonul::<16>::from_str_unchecked("hello world!!!");
    /// assert![!a.eq(&b)];
    /// b.pop();
    /// b.pop();
    /// assert![a.eq(&b)];
    /// ```
    #[must_use] #[inline(always)]
    pub const fn eq(&self, other: &Self) -> bool {
        let mut i = 0;
        while i < CAP {
            if self.arr[i] != other.arr[i] { return false; }
            if self.arr[i] == 0 { return true; }
            i += 1;
        }
        true
    }

    /* deconstruct */

    /// Returns the inner array with the full contents.
    ///
    /// The array contains all the bytes, including those outside the current length.
    #[must_use] #[inline(always)]
    pub const fn into_array(self) -> [u8; CAP] { self.arr }

    /// Returns a copy of the inner array with the full contents.
    ///
    /// The array contains all the bytes, including those outside the current length.
    #[must_use] #[inline(always)]
    pub const fn as_array(&self) -> &[u8; CAP] { &self.arr }

    /// Returns a byte slice of the inner string slice.
    ///
    /// # Features
    /// Makes use of the `unsafe_slice` feature if enabled.
    #[must_use] #[inline(always)]
    pub const fn as_bytes(&self) -> &[u8] { self.arr.split_at(self.len()).0 }

    /// Returns a mutable byte slice of the inner string slice.
    ///
    /// # Safety
    /// The caller must ensure that the content of the slice is valid UTF-8
    /// and that it doesn't contain any `NUL` characters before the borrow
    /// ends and the underlying `str` is used.
    ///
    /// # Features
    /// Makes use of the `unsafe_slice` feature if enabled.
    #[must_use] #[inline(always)]
    #[cfg(all(not(feature = "safe_text"), feature = "unsafe_str"))]
    #[cfg_attr(nightly_doc, doc(cfg(feature = "unsafe_str")))]
    pub const unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
        let len = self.len();
        #[cfg(any(feature = "safe_text", not(feature = "unsafe_slice")))]
        return slice![mut &mut self.arr, ..len];

        #[cfg(all(not(feature = "safe_text"), feature = "unsafe_slice"))]
        // SAFETY: we ensure to uphold a valid length
        unsafe { slice![mut_unchecked &mut self.arr, ..len] }
    }

    /// Returns the inner string slice.
    /// # Features
    /// Makes use of the `unsafe_slice` feature if enabled.
    #[must_use]
    pub const fn as_str(&self) -> &str {
        #[cfg(any(feature = "safe_text", not(feature = "unsafe_slice")))]
        return unwrap![ok_expect Str::from_utf8(self.as_bytes()), "Invalid UTF-8"];

        #[cfg(all(not(feature = "safe_text"), feature = "unsafe_slice"))]
        // SAFETY: we ensure to contain only valid UTF-8
        unsafe { Str::from_utf8_unchecked(self.as_bytes()) }
    }

    /// Returns the mutable inner string slice.
    ///
    /// # Safety
    /// The caller must ensure that the content of the slice is valid UTF-8
    /// and that it doesn't contain any `NUL` characters before the borrow
    /// ends and the underlying `str` is used.
    #[must_use]
    #[cfg(all(not(feature = "safe_text"), feature = "unsafe_str"))]
    #[cfg_attr(nightly_doc, doc(cfg(feature = "unsafe_str")))]
    pub const unsafe fn as_mut_str(&mut self) -> &mut str {
        // SAFETY: we ensure to contain only valid UTF-8
        unsafe { Str::from_utf8_unchecked_mut(self.as_bytes_mut()) }
    }

    /// Returns an iterator over the `chars` of the string.
    #[inline(always)]
    pub const fn chars(&self) -> CharIter<'_, &str> { CharIter::<&str>::new(self.as_str()) }

    /* operations */

    /// Sets the length to 0, by resetting all bytes to 0.
    pub const fn clear(&mut self) { self.arr = [0; CAP]; }

    /// Removes the last character and returns it, or `None` if the string is empty.
    #[must_use]
    pub const fn pop(&mut self) -> Option<char> {
        if self.is_empty() { None } else { Some(self.pop_unchecked()) }
    }

    /// Tries to remove the last character and return it.
    ///
    /// # Errors
    /// Returns [`NotEnoughElements`] if the string is empty.
    pub const fn try_pop(&mut self) -> Result<char, NotEnoughElements> {
        if self.is_empty() {
            Err(NotEnoughElements(Some(1)))
        } else {
            Ok(self.pop_unchecked())
        }
    }

    /// Removes the last character and returns it.
    ///
    /// # Panics
    /// Panics if the string is empty.
    ///
    /// # Example
    /// ```
    /// # use devela::StringNonul;
    /// let mut s = StringNonul::<16>::new();
    /// s.push_str("hello worlð!");
    /// assert_eq![s.len(), 13];
    ///
    /// assert_eq![s.pop_unchecked(), '!'];
    /// assert_eq![s.len(), 12];
    ///
    /// assert_eq![s.pop_unchecked(), 'ð'];
    /// assert_eq![s.len(), 10];
    /// ```
    #[must_use] #[rustfmt::skip]
    pub const fn pop_unchecked(&mut self) -> char {
        let (len, string) = (self.len(), self.as_str());
        let mut idx_last_char = len - 1;
        while idx_last_char > 0 && !string.is_char_boundary(idx_last_char) { idx_last_char -= 1; }

        let range = Str::range(string, idx_last_char, len);
        let last_char = unwrap![some CharIter::<&str>::new(range).next_char()];

        let mut i = idx_last_char; while i < len { self.arr[i] = 0; i += 1; } // clean char bytes
        last_char
    }

    /// Appends to the end of the string the given `character`.
    ///
    /// Returns the number of bytes written.
    ///
    /// It will return 0 bytes if the given `character` doesn't fit in
    /// the remaining capacity, or if it is the nul character.
    ///
    /// # Example
    /// ```
    /// # use devela::StringNonul;
    /// let mut s = StringNonul::<16>::new();
    /// s.push('h');
    /// assert_eq![s.len(), 1];
    ///
    /// s.push('€');
    /// assert_eq![s.len(), 4];
    ///
    /// assert_eq![s.as_str(), "h€"];
    /// ```
    pub const fn push(&mut self, character: char) -> usize {
        let char_len = character.len_utf8();
        if character != NUL_CHAR && self.remaining_capacity() >= char_len {
            let len = self.len();
            let _ = character.encode_utf8(slice![mut &mut self.arr, len, ..len + char_len]);
            char_len
        } else {
            0
        }
    }

    /// Tries to append to the end of the string the given `character`.
    ///
    /// Returns the number of bytes written.
    ///
    /// Trying to push a nul character does nothing and returns 0 bytes.
    ///
    /// # Errors
    /// Returns [`NotEnoughSpace`]
    /// if the available capacity is not enough to hold the given character.
    pub const fn try_push(&mut self, character: char) -> Result<usize, NotEnoughSpace> {
        let char_len = character.len_utf8();
        if character == NUL_CHAR {
            Ok(0)
        } else if self.remaining_capacity() >= char_len {
            let len = self.len();
            let _ = character.encode_utf8(slice![mut &mut self.arr, len, ..len + char_len]);
            Ok(char_len)
        } else {
            Err(NotEnoughSpace(Some(char_len)))
        }
    }

    /// Appends to the end the fitting characters from the given `string` slice.
    ///
    /// Nul characters will be stripped out.
    ///
    /// Returns the number of bytes written, which will be 0
    /// if not even the first non-nul character can fit.
    ///
    /// # Features
    /// Uses the `unsafe_str` feature to skip validation checks.
    pub const fn push_str(&mut self, string: &str) -> usize {
        let mut rem_cap = self.remaining_capacity();
        let mut bytes_written = 0;
        let mut chars = CharIter::<&str>::new(string);
        while let Some(character) = chars.next_char() {
            if character != NUL_CHAR {
                let char_len = character.len_utf8();
                if char_len <= rem_cap {
                    self.push(character);
                    rem_cap -= char_len;
                    bytes_written += char_len;
                } else {
                    break;
                }
            }
        }
        bytes_written
    }

    /// Tries to append to the end the fitting characters from the given `string` slice.
    ///
    /// Nul characters will be stripped out.
    ///
    /// Returns the number of bytes written.
    ///
    /// # Errors
    /// Returns [`NotEnoughSpace`] if the capacity is not enough
    /// to hold not even the first non-nul character.
    ///
    /// # Example
    /// ```
    /// # use devela::StringNonul;
    /// let mut s = StringNonul::<8>::new();
    /// s.push_str("hello");
    ///
    /// // successfully appends a string while removing NUL characters
    /// let result = s.try_push_str("\0\0\0\0\0 world");
    /// assert!(result.is_ok());
    /// assert_eq!(s.as_str(), "hello wo"); // truncates if it can't fit all
    /// assert!(s.try_push_str("!").is_err()); // fails if it can't fit 1 char
    ///
    /// // Insufficient capacity for the first non-NUL character
    /// let mut small = StringNonul::<3>::new();
    /// assert!(small.try_push_str("🚀").is_err()); // Needs 4 bytes for the rocket
    /// ```
    /// # Features
    /// Uses the `unsafe_str` feature to skip validation checks.
    pub const fn try_push_str(&mut self, string: &str) -> Result<usize, NotEnoughSpace> {
        let mut first_char_len = 0;
        let mut chars = CharIter::<&str>::new(string);
        while let Some(c) = chars.next_scalar() { // find the first non-zero length character:
            if c != NUL_CHAR as u32 { first_char_len = Char(c).len_utf8_unchecked(); break; }
        }
        if self.remaining_capacity() < first_char_len {
            Err(NotEnoughSpace(Some(first_char_len)))
        } else {
            Ok(self.push_str(string))
        }
    }

    /// Tries to append the complete `string` slice to the end.
    ///
    /// Returns the number of bytes written in success.
    ///
    /// Nul characters will not be taken into account.
    ///
    /// # Errors
    /// Returns [`NotEnoughSpace`] if the slice wont completely fit.
    ///
    /// # Features
    /// Uses the `unsafe_str` feature to skip validation checks.
    pub const fn try_push_str_complete(&mut self, string: &str) -> Result<usize, NotEnoughSpace> {
        lets![mut non_nul_len=0, bytes=string.as_bytes(), str_len=bytes.len()];
        whilst!{ i in 0..str_len; { is![bytes[i] != 0, non_nul_len += 1] }} // count !0 bytes
        if self.remaining_capacity() >= non_nul_len {
            Ok(self.push_str(string))
        } else {
            Err(NotEnoughSpace(Some(str_len)))
        }
    }

    /* from char */

    /// Creates a new `StringNonul` from a `char`.
    ///
    /// If `c` is NUL an empty string will be returned.
    ///
    /// # Errors
    /// Returns [`MismatchedCapacity`] if `CAP` > [`u8::MAX`],
    /// or  if `!c.is_nul()` and `CAP` < `c.`[`len_utf8()`][Char::len_utf8].
    ///
    /// Will always succeed if `CAP` >= 4.
    /// # Example
    /// ```
    /// # use devela::{StringNonul, char};
    /// assert_eq![StringNonul::<4>::from_char('🐛').unwrap().as_str(), "🐛"];
    /// assert_eq![StringNonul::<4>::from_char('\0').unwrap().as_str(), ""];
    /// assert![StringNonul::<3>::from_char('🐛').is_err()];
    /// ```
    pub const fn from_char(c: char) -> Result<Self, MismatchedCapacity> {
        let mut new = unwrap![ok? Self::new_checked()];
        if c != '\0' {
            let bytes = Char(c).to_utf8_bytes();
            let len = Char(bytes[0]).len_utf8_unchecked();
            is![CAP < len, return Err(MismatchedCapacity::too_small(CAP, len))];
            new.arr[0] = bytes[0];
            if len > 1 { new.arr[1] = bytes[1]; }
            if len > 2 { new.arr[2] = bytes[2]; }
            if len > 3 { new.arr[3] = bytes[3]; }
        }
        Ok(new)
    }

    /// Creates a new `StringNonul` from a `char7`.
    ///
    /// If `c`.[`is_nul()`][char7#method.is_nul] an empty string will be returned.
    ///
    /// # Errors
    /// Returns [`MismatchedCapacity`] if `CAP` > [`u8::MAX`],
    /// or if `!c.is_nul()` and `CAP` < 1.
    ///
    /// Will always succeed if `CAP` >= 1.
    /// # Example
    /// ```
    /// # use devela::{StringNonul, char7};
    /// let s = StringNonul::<1>::from_char7(char7::try_from_char('@').unwrap()).unwrap();
    /// assert_eq![s.as_str(), "@"];
    /// let s = StringNonul::<1>::from_char7(char7::try_from_char('\0').unwrap()).unwrap();
    /// assert_eq![s.as_str(), ""];
    ///
    /// assert![StringNonul::<0>::from_char7(char7::try_from_char('@').unwrap()).is_err()];
    /// ```
    pub const fn from_char7(c: char7) -> Result<Self, MismatchedCapacity> {
        is![CAP == 0, return Err(MismatchedCapacity::too_small(CAP, 1))];
        let mut new = unwrap![ok? Self::new_checked()];
        if !c.is_nul() {
            new.arr[0] = c.to_utf8_bytes()[0];
        }
        Ok(new)
    }

    /// Creates a new `StringNonul` from a `char8`.
    ///
    /// If `c`.[`is_nul()`][char8#method.is_nul] an empty string will be returned.
    ///
    /// # Errors
    /// Returns [`MismatchedCapacity`] if `CAP` > [`u8::MAX`],
    /// or if `!c.is_nul()` and `CAP` < `c.`[`len_utf8()`][char8#method.len_utf8].
    ///
    /// Will always succeed if `CAP` >= 2.
    /// # Example
    /// ```
    /// # use devela::{StringNonul, char8};
    /// let s = StringNonul::<2>::from_char8(char8::try_from_char('ß').unwrap()).unwrap();
    /// assert_eq![s.as_str(), "ß"];
    /// let s = StringNonul::<2>::from_char8(char8::try_from_char('\0').unwrap()).unwrap();
    /// assert_eq![s.as_str(), ""];
    ///
    /// assert![StringNonul::<1>::from_char8(char8::try_from_char('ß').unwrap()).is_err()];
    /// ```
    pub const fn from_char8(c: char8) -> Result<Self, MismatchedCapacity> {
        let mut new = unwrap![ok? Self::new_checked()];
        if !c.is_nul() {
            let bytes = c.to_utf8_bytes();
            let len = Char(bytes[0]).len_utf8_unchecked();
            is![CAP < len, return Err(MismatchedCapacity::too_small(CAP, len))];
            new.arr[0] = bytes[0];
            if len > 1 { new.arr[1] = bytes[1]; }
        }
        Ok(new)
    }

    /// Creates a new `StringNonul` from a `char16`.
    ///
    /// If `c`.[`is_nul()`][char16#method.is_nul] an empty string will be returned.
    ///
    /// # Errors
    /// Returns [`MismatchedCapacity`] if `CAP` > [`u8::MAX`],
    /// or if `!c.is_nul()` and `CAP` < `c.`[`len_utf8()`][char16#method.len_utf8].
    ///
    /// Will always succeed if `CAP` >= 3.
    /// # Example
    /// ```
    /// # use devela::{StringNonul, char16};
    /// let s = StringNonul::<3>::from_char16(char16::try_from_char('€').unwrap()).unwrap();
    /// assert_eq![s.as_str(), "€"];
    /// let s = StringNonul::<3>::from_char16(char16::try_from_char('\0').unwrap()).unwrap();
    /// assert_eq![s.as_str(), ""];
    ///
    /// assert![StringNonul::<2>::from_char16(char16::try_from_char('€').unwrap()).is_err()];
    /// ```
    pub const fn from_char16(c: char16) -> Result<Self, MismatchedCapacity> {
        let mut new = unwrap![ok? Self::new_checked()];
        if !c.is_nul() {
            let bytes = c.to_utf8_bytes();
            let len = Char(bytes[0]).len_utf8_unchecked();
            is![CAP < len, return Err(MismatchedCapacity::too_small(CAP, len))];
            new.arr[0] = bytes[0];
            if len > 1 { new.arr[1] = bytes[1]; }
            if len > 2 { new.arr[2] = bytes[2]; }
        }
        Ok(new)
    }

    /// Creates a new `StringNonul` from a `charu`.
    ///
    /// If `c`.[`is_nul()`][charu#method.is_nul] an empty string will be returned.
    ///
    /// # Errors
    /// Returns [`MismatchedCapacity`] if `CAP` > [`u8::MAX`],
    /// or if `CAP` < `c.`[`len_utf8()`][charu#method.len_utf8].
    ///
    /// Will always succeed if `CAP` >= 4.
    /// # Example
    /// ```
    /// # use devela::{StringNonul, charu};
    /// let s = StringNonul::<4>::from_charu(charu::from_char('🐛')).unwrap();
    /// assert_eq![s.as_str(), "🐛"];
    /// let s = StringNonul::<4>::from_charu(charu::from_char('\0')).unwrap();
    /// assert_eq![s.as_str(), ""];
    ///
    /// assert![StringNonul::<3>::from_charu(charu::from_char('🐛')).is_err()];
    /// ```
    pub const fn from_charu(c: charu) -> Result<Self, MismatchedCapacity> {
        let mut new = unwrap![ok? Self::new_checked()];
        if !c.is_nul() {
            let len = c.len_utf8();
            if len <= CAP {
                let bytes = c.to_utf8_bytes();
                slice![mut &mut new.arr, 0,..len].copy_from_slice(slice![&bytes, 0,..len]);
            } else {
                return Err(MismatchedCapacity::too_small(CAP, len));
            }
        }
        Ok(new)
    }

    /// Creates a new `StringNonul` from a `charu`.
    ///
    /// If `c`.[`is_nul()`][charu#method.is_nul] an empty string will be returned.
    ///
    /// # Panics
    /// Panics if `CAP` > [`u8::MAX`],
    /// or if `CAP` < `c.`[`len_utf8()`][charu#method.len_utf8].
    ///
    /// Will always succeed if `CAP` >= 4.
    /// # Examples
    /// ```
    /// # use devela::{StringNonul, charu};
    /// let s = StringNonul::<3>::from_charu_unchecked(charu::from_char('€'));
    /// assert_eq![s, "€"]
    /// ```
    /// ```should_panic
    /// # use devela::{StringNonul, charu};
    /// StringNonul::<2>::from_charu_unchecked(charu::from_char('€'));
    /// ```
    pub const fn from_charu_unchecked(c: charu) -> Self {
        let mut new = Self::new();
        if !c.is_nul() {
            let len = c.len_utf8();
            let bytes = c.to_utf8_bytes();
            slice![mut &mut new.arr, 0,..len].copy_from_slice(slice![&bytes, 0,..len]);
        }
        new
    }

    /* from_byte_array* conversions */

    /// Returns a string from an array of `bytes`.
    ///
    /// Note that the first NUL character will indicate the end of the string.
    ///
    /// # Errors
    /// Returns [`InvalidText::Utf8`] if the bytes are not valid UTF-8.
    #[inline(always)]
    pub const fn from_array(bytes: [u8; CAP]) -> Result<Self, InvalidText> {
        // IMPROVE: use Str
        match ::core::str::from_utf8(&bytes) {
            Ok(_) => Ok(Self { arr: bytes }),
            Err(e) => Err(InvalidText::from_utf8_error(e)),
        }
    }

    /// Returns a string from an array of `bytes` that must be valid UTF-8.
    ///
    /// # Safety
    /// The caller must ensure that the content of the slice is valid UTF-8,
    /// and that it has no NUL characters as part of the string.
    ///
    /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
    #[inline(always)]
    #[cfg(all(not(feature = "safe_text"), feature = "unsafe_str"))]
    #[cfg_attr(nightly_doc, doc(cfg(feature = "unsafe_str")))]
    pub const unsafe fn from_array_unchecked(bytes: [u8; CAP]) -> Self {
        Self { arr: bytes }
    }
    /// Internal accessor for trusted formatting operations, avoiding safe re-validation.
    ///
    /// # Safety
    /// The caller must ensure that the content of the slice is valid UTF-8,
    /// and that it has no NUL characters as part of the string.
    #[inline(always)]
    pub(crate) const fn _from_array_trusted(array: [u8; CAP]) -> Self {
        Self { arr: array }
    }
}

/* trait impls */

#[rustfmt::skip]
mod trait_impls {
    use crate::{
        ConstInit, Debug, Deref, Display, FmtError, FmtResult, FmtWrite, Formatter, Hash,
        Hasher,
    };
    use super::{StringNonul, InvalidText, MismatchedCapacity, is};

    impl<const CAP: usize> Default for StringNonul<CAP> {
        /// Returns an empty string.
        /// # Panics
        /// Panics if `CAP > [`u8::MAX`]`.
        fn default() -> Self { Self::new() }
    }
    impl<const CAP: usize> ConstInit for StringNonul<CAP> {
        /// Returns an empty string.
        /// # Panics
        /// Panics if `CAP > [`u8::MAX`]`.
        const INIT: Self = Self::new();
    }

    impl<const CAP: usize> Display for StringNonul<CAP> {
        fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult<()> {
            write!(f, "{}", self.as_str())
        }
    }
    impl<const CAP: usize> Debug for StringNonul<CAP> {
        fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult<()> {
            write!(f, "{:?}", self.as_str())
        }
    }

    /// Leverages [`try_push`][Self::try_push] and [`try_push_str`][Self::try_push_str].
    impl<const CAP: usize> FmtWrite for StringNonul<CAP> {
        fn write_str(&mut self, s: &str) -> FmtResult<()> {
            self.try_push_str(s).map_err(|_| FmtError)?;
            Ok(())
        }
        fn write_char(&mut self, c: char) -> FmtResult<()> {
            self.try_push(c).map_err(|_| FmtError)?;
            Ok(())
        }
    }

    impl<const CAP: usize> PartialEq for StringNonul<CAP> {
        fn eq(&self, other: &Self) -> bool { self.eq(other) }
    }

    impl<const CAP: usize> PartialEq<str> for StringNonul<CAP> { // str on the RHS
        fn eq(&self, slice: &str) -> bool { self.as_str() == slice }
    }
    impl<const CAP: usize> PartialEq<&str> for StringNonul<CAP> { // &str on the RHS
        fn eq(&self, slice: &&str) -> bool { self.as_str() == *slice }
    }
    impl<const CAP: usize> PartialEq<&[u8]> for StringNonul<CAP> { // &[u8] on the RHS
        fn eq(&self, bytes: &&[u8]) -> bool { self.as_bytes() == *bytes }
    }

    impl<const CAP: usize> PartialEq<StringNonul<CAP>> for str { // &str on the LHS
        fn eq(&self, string: &StringNonul<CAP>) -> bool { self == string.as_str() }
    }
    impl<const CAP: usize> PartialEq<StringNonul<CAP>> for &str { // &str on the LHS
        fn eq(&self, string: &StringNonul<CAP>) -> bool { *self == string.as_str() }
    }
    impl<const CAP: usize> PartialEq<StringNonul<CAP>> for &[u8] { // &[u8] on the LHS
        fn eq(&self, string: &StringNonul<CAP>) -> bool { *self == string.as_bytes() }
    }

    impl<const CAP: usize> Hash for StringNonul<CAP> {
        fn hash<H: Hasher>(&self, state: &mut H) {
            let len = self.len();
            self.arr[..len].hash(state);
        }
    }

    impl<const CAP: usize> Deref for StringNonul<CAP> {
        type Target = str;
        fn deref(&self) -> &Self::Target { self.as_str() }
    }

    impl<const CAP: usize> AsRef<str> for StringNonul<CAP> {
        fn as_ref(&self) -> &str { self.as_str() }
    }

    impl<const CAP: usize> AsRef<[u8]> for StringNonul<CAP> {
        fn as_ref(&self) -> &[u8] { self.as_bytes() }
    }

    impl<const CAP: usize> TryFrom<&str> for StringNonul<CAP> {
        type Error = MismatchedCapacity;

        /// Tries to create a new `StringNonul` from the given string slice.
        ///
        /// # Errors
        /// Returns [`MismatchedCapacity`] if `CAP > `[`u8::MAX`] or if `CAP < str.len()`.
        fn try_from(string: &str) -> Result<Self, MismatchedCapacity> {
            let non_nul_len = string.as_bytes().iter().filter(|x| **x != 0).count();
            if CAP < non_nul_len {
                Err(MismatchedCapacity::too_small(CAP, non_nul_len))
            } else {
                let mut new_string = Self::new_checked()?;
                let copied_bytes = new_string.push_str(string);
                debug_assert_eq![non_nul_len, copied_bytes];
                Ok(new_string)
            }
        }
    }

    impl<const CAP: usize> TryFrom<&[u8]> for StringNonul<CAP> {
        type Error = InvalidText;

        /// Tries to create a new `StringNonul` from the given slice of `bytes`.
        ///
        /// The string will stop before the first nul character or the end of the slice.
        ///
        /// # Errors
        /// Returns [`InvalidText::MismatchedCapacity`] if `CAP > `[u8::MAX`]
        /// or if `CAP < bytes.len()`,
        /// or [`InvalidText::Utf8`] if the `bytes` are not valid UTF-8.
        fn try_from(bytes: &[u8]) -> Result<Self, InvalidText> {
            let len = bytes.len();
            if len >= CAP { return Err(MismatchedCapacity::too_small(CAP, len).into()); }
            // IMPROVE: use Str
            match ::core::str::from_utf8(bytes) {
                Ok(_) => {
                    let mut arr = [0; CAP];
                    let mut idx = 0;

                    for &byte in bytes.iter() {
                        if byte != 0 {
                            arr[idx] = byte;
                            idx += 1;
                        }
                    }
                    Ok(Self { arr })
                }
                Err(e) => Err(InvalidText::from_utf8_error(e)),
            }
        }
    }

    /* Extend & FromIterator */

    impl<const CAP: usize> Extend<char> for StringNonul<CAP> {
        /// Creates an instance from an iterator of characters.
        ///
        /// Processes characters until it can fit no more, discarding the rest.
        ///
        /// # Panics
        /// Panics if `CAP > `[`u8::MAX`].
        ///
        /// # Example
        /// ```
        /// # use devela::StringNonul;
        /// let chars = ['a', 'b', 'c', '€', 'さ'];
        /// let mut s = StringNonul::<6>::new();
        /// s.extend(chars);
        /// assert_eq![s, "abc€"];
        /// ```
        fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
            for i in iter {
                is![self.push(i) == 0, break];
            }
        }
    }
    impl<const CAP: usize> FromIterator<char> for StringNonul<CAP> {
        /// Creates an instance from an iterator of characters.
        ///
        /// Processes characters until it can fit no more, discarding the rest.
        ///
        /// # Panics
        /// Panics if `CAP > `[`u8::MAX`].
        ///
        /// # Example
        /// ```
        /// # use devela::StringNonul;
        /// let chars = ['a', 'b', 'c', '€', 'さ'];
        /// assert_eq!(StringNonul::<9>::from_iter(chars), "abc€さ");
        /// assert_eq!(StringNonul::<6>::from_iter(chars), "abc€");
        /// assert_eq!(StringNonul::<5>::from_iter(chars), "abc");
        /// assert_eq!(StringNonul::<2>::from_iter(chars), "ab");
        /// assert_eq!(StringNonul::<0>::from_iter(chars), "");
        /// ```
        fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> Self {
            let mut string = StringNonul::new();
            string.extend(iter);
            string
        }
    }
}