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
// devela::text::u8string
//
//! `String` backed by an array.
//
// TOC
// - generate_array_string!
//   - definitions
//   - trait impls
// - tests

use super::{helpers::impl_sized_alias, ArrayStringError, Result};
use core::{fmt, ops::Deref};

#[cfg(feature = "alloc")]
use _alloc::{ffi::CString, str::Chars, string::ToString};

use super::char::*;

macro_rules! generate_array_string {
    ($($t:ty),+ $(,)?) => {
        $( generate_array_string![@$t]; )+
    };
    (@$t:ty) => { $crate::meta::paste! {

        /* definitions */

        #[doc = "A UTF-8–encoded string, backed by an array with [`" $t "::MAX`] bytes of capacity."]
        ///
        #[doc = "Internally, the current length is stored as a [`" u8 "`]."]
        #[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
        pub struct [<Array $t:upper String>]<const CAP: usize> {
            // WAITING for when we can use CAP: u8 for panic-less const boundary check.
            arr: [u8; CAP],
            len: $t,
        }

        impl<const CAP: usize> [<Array $t:upper String>]<CAP> {
            #[doc = "Creates a new empty `Array" $t:upper "String>]` with a capacity of `CAP` bytes."]
            ///
            /// # Panics
            #[doc = "Panics if `CAP > `[`" $t "::MAX`]."]
            #[inline]
            #[must_use]
            pub const fn new() -> Self {
                assert![CAP <= $t::MAX as usize];
                Self {
                    arr: [0; CAP],
                    len: 0,
                }
            }

            /// Creates a new `Array $t:upper String>]` from a `Char7`.
            ///
            /// # Panics
            #[doc = "Panics if `CAP > `[`" $t "::MAX`]` || CAP < 1`."]
            ///
            #[doc = "Will never panic if `CAP >= 1 && CAP <= `[`" $t "::MAX`]."]
            #[inline]
            #[must_use]
            pub const fn from_char7(c: Char7) -> Self {
                let mut new = Self::new();
                new.arr[0] = c.to_utf8_bytes()[0];
                new.len = 1;
                new
            }

            /// Creates a new `Array $t:upper String>]` from a `Char8`.
            ///
            /// # Panics
            #[doc = "Panics if `CAP > `[`" $t
                "::MAX`]` || CAP < c.`[`len_utf8()`][Char8#method.len_utf8]."]
            ///
            #[doc = "Will never panic if `CAP >= 2 && CAP <= `[`" $t "::MAX`]."]
            #[inline]
            #[must_use]
            pub const fn from_char8(c: Char8) -> Self {
                let mut new = Self::new();

                let bytes = c.to_utf8_bytes();
                new.len = char_utf8_2bytes_len(bytes) as $t;

                new.arr[0] = bytes[0];
                if new.len > 1 {
                    new.arr[1] = bytes[1];
                }
                new
            }

            /// Creates a new `Array $t:upper String>]` from a `Char16`.
            ///
            /// # Panics
            #[doc = "Panics if `CAP > `[`" $t
                "::MAX`]` || CAP < c.`[`len_utf8()`][Char16#method.len_utf8]."]
            ///
            #[doc = "Will never panic if `CAP >= 3 && CAP <= `[`" $t "::MAX`]."]
            #[inline]
            #[must_use]
            pub const fn from_char16(c: Char16) -> Self {
                let mut new = Self::new();

                let bytes = c.to_utf8_bytes();
                new.len = char_utf8_3bytes_len(bytes) as $t;

                new.arr[0] = bytes[0];
                if new.len > 1 {
                    new.arr[1] = bytes[1];
                }
                if new.len > 2 {
                    new.arr[2] = bytes[2];
                }
                new
            }

            /// Creates a new `Array $t:upper String>]` from a `Char24`.
            ///
            /// # Panics
            #[doc = "Panics if `CAP > `[`" $t
                "::MAX`]` || CAP < c.`[`len_utf8()`][Char24#method.len_utf8]."]
            ///
            #[doc = "Will never panic if `CAP >= 4 && CAP <= `[`" $t "::MAX`]."]
            #[inline]
            #[must_use]
            pub const fn from_char24(c: Char24) -> Self {
                let mut new = Self::new();

                let bytes = c.to_utf8_bytes();
                new.len = char_utf8_4bytes_len(bytes) as $t;

                new.arr[0] = bytes[0];
                if new.len > 1 {
                    new.arr[1] = bytes[1];
                }
                if new.len > 2 {
                    new.arr[2] = bytes[2];
                }
                if new.len > 3 {
                    new.arr[3] = bytes[3];
                }
                new
            }

            /// Creates a new `Array $t:upper String>]` from a `Char32`.
            ///
            /// # Panics
            #[doc = "Panics if `CAP > `[`" $t
                "::MAX`]` || CAP < c.`[`len_utf8()`][Char32#method.len_utf8]."]
            ///
            #[doc = "Will never panic if `CAP >= 4 && CAP <= `[`" $t "::MAX`]."]
            #[inline]
            #[must_use]
            pub const fn from_char32(c: Char32) -> Self {
                Self::from_char(c.0)
            }

            /// Creates a new `Array $t:upper String>]` from a `char`.
            ///
            /// # Panics
            #[doc = "Panics if `CAP > `[`" $t
                "::MAX`]` || CAP < c.`[`len_utf8()`][UnicodeScalar#method.len_utf8]."]
            ///
            #[doc = "Will never panic if `CAP >= 4 && CAP <= `[`" $t "::MAX`]."]
            #[inline]
            #[must_use]
            pub const fn from_char(c: char) -> Self {
                let mut new = Self::new();

                let bytes = char_to_utf8_bytes(c);
                new.len = char_utf8_4bytes_len(bytes) as $t;

                new.arr[0] = bytes[0];
                if new.len > 1 {
                    new.arr[1] = bytes[1];
                }
                if new.len > 2 {
                    new.arr[2] = bytes[2];
                }
                if new.len > 3 {
                    new.arr[3] = bytes[3];
                }
                new
            }

            //

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

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

            /// Returns the current length.
            #[inline]
            #[must_use]
            pub const fn len(&self) -> usize {
                self.len as usize
            }

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

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

            /// Sets the length to 0.
            #[inline]
            pub fn clear(&mut self) {
                self.len = 0;
            }

            /// Sets the length to 0, and resets all the bytes to 0.
            #[inline]
            pub fn reset(&mut self) {
                self.arr = [0; CAP];
                self.len = 0;
            }

            //

            /// Returns a byte slice of the inner string slice.
            #[inline]
            #[must_use]
            pub fn as_bytes(&self) -> &[u8] {
                #[cfg(feature = "unsafe_text")]
                unsafe {
                    self.arr.get_unchecked(0..self.len as usize)
                }

                #[cfg(not(feature = "unsafe_text"))]
                self.arr
                    .get(0..self.len as usize)
                    .expect("len must be <= arr.len()")
            }

            /// Returns a mutable byte slice of the inner string slice.
            ///
            /// # Safety
            /// TODO
            #[inline]
            #[must_use]
            #[cfg(feature = "unsafe_text")]
            #[cfg_attr(feature = "nightly", doc(cfg(feature = "unsafe_text")))]
            pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
                self.arr.get_unchecked_mut(0..self.len as usize)
            }

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

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

            /// Returns the inner string slice.
            #[inline]
            #[must_use]
            pub fn as_str(&self) -> &str {
                #[cfg(feature = "unsafe_text")]
                unsafe {
                    core::str::from_utf8_unchecked(
                        self.arr
                            .get(0..self.len as usize)
                            .expect("len must be <= arr.len()"),
                    )
                }
                #[cfg(not(feature = "unsafe_text"))]
                core::str::from_utf8(
                    self.arr
                        .get(0..self.len as usize)
                        .expect("len must be <= arr.len()"),
                )
                .expect("must be valid utf-8")
            }

            /// Returns the mutable inner string slice.
            ///
            /// # Safety
            /// TODO
            #[must_use]
            #[cfg(feature = "unsafe_text")]
            #[cfg_attr(feature = "nightly", doc(cfg(feature = "unsafe_text")))]
            pub fn as_str_mut(&mut self) -> &mut str {
                unsafe { &mut *(self.as_bytes_mut() as *mut [u8] as *mut str) }
            }

            /// Returns an iterator over the `chars` of this grapheme cluster.
            #[inline]
            #[cfg(feature = "alloc")]
            #[cfg_attr(feature = "nightly", doc(cfg(feature = "alloc")))]
            pub fn chars(&self) -> Chars {
                self.as_str().chars()
            }

            /// Returns a new allocated C-compatible, nul-terminanted string.
            #[inline]
            #[must_use]
            #[cfg(feature = "alloc")]
            #[cfg_attr(feature = "nightly", doc(cfg(feature = "alloc")))]
            pub fn to_cstring(&self) -> CString {
                CString::new(self.to_string()).unwrap()
            }

            //

            /// Removes the last character and returns it, or `None` if
            /// the string is empty.
            #[inline]
            #[must_use]
            pub fn pop(&mut self) -> Option<char> {
                self.as_str().chars().last().map(|c| {
                    self.len -= c.len_utf8() as $t;
                    c
                })
            }

            /// Tries to remove the last character and returns it, or `None` if
            /// the string is empty.
            ///
            /// # Errors
            /// Returns a [`NotEnoughElements`][ArrayStringError::NotEnoughElements] error
            /// if the capacity is not enough to hold the `character`.
            #[inline]
            pub fn try_pop(&mut self) -> Result<char> {
                self.as_str()
                    .chars()
                    .last()
                    .map(|c| {
                        self.len -= c.len_utf8() as $t;
                        c
                    })
                    .ok_or(ArrayStringError::NotEnoughElements(1))
            }

            /// 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.
            pub fn push(&mut self, character: char) -> usize {
                let char_len = character.len_utf8();
                if self.remaining_capacity() >= char_len {
                    let beg = self.len as usize;
                    let end = beg + char_len;
                    let _ = character.encode_utf8(&mut self.arr[beg..end]);
                    self.len += char_len as $t;
                    char_len
                } else {
                    0
                }
            }

            /// Tries to append to the end of the string the given `character`.
            ///
            /// Returns the number of bytes written.
            ///
            /// # Errors
            /// Returns a [`NotEnoughCapacity`][ArrayStringError::NotEnoughCapacity] error
            /// if the capacity is not enough to hold the `character`.
            pub fn try_push(&mut self, character: char) -> Result<usize> {
                let char_len = character.len_utf8();
                if self.remaining_capacity() >= char_len {
                    let beg = self.len as usize;
                    let end = beg + char_len;
                    let _ = character.encode_utf8(&mut self.arr[beg..end]);
                    self.len += char_len as $t;
                    Ok(char_len)
                } else {
                    Err(ArrayStringError::NotEnoughCapacity(char_len))
                }
            }
        }

        /* traits */

        impl<const CAP: usize> Default for [<Array $t:upper String>]<CAP> {
            /// Returns an empty string.
            ///
            /// # Panics
            /// Panics if `CAP` > 255.
            #[inline]
            #[must_use]
            fn default() -> Self {
                Self::new()
            }
        }

        impl<const CAP: usize> fmt::Display for [<Array $t:upper String>]<CAP> {
            #[inline]
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.as_str())
            }
        }

        impl<const CAP: usize> fmt::Debug for [<Array $t:upper String>]<CAP> {
            #[inline]
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{:?}", self.as_str())
            }
        }

        impl<const CAP: usize> Deref for [<Array $t:upper String>]<CAP> {
            type Target = str;
            #[inline]
            #[must_use]
            fn deref(&self) -> &Self::Target {
                self.as_str()
            }
        }

        impl<const CAP: usize> AsRef<str> for [<Array $t:upper String>]<CAP> {
            #[inline]
            #[must_use]
            fn as_ref(&self) -> &str {
                self.as_str()
            }
        }

        impl<const CAP: usize> AsRef<[u8]> for [<Array $t:upper String>]<CAP> {
            #[inline]
            #[must_use]
            fn as_ref(&self) -> &[u8] {
                self.as_bytes()
            }
        }

        #[cfg(all(feature = "std", any(unix, target_os = "wasi")))]
        mod [< std_impls_ $t >] {
            use super::[<Array $t:upper String>];
            use std::ffi::OsStr;

            #[cfg(unix)]
            use std::os::unix::ffi::OsStrExt;
            #[cfg(target_os = "wasi")]
            use std::os::wasi::ffi::OsStrExt;

            #[cfg_attr(feature = "nightly", doc(cfg(
                all(feature = "std", any(unix, target_os = "wasi"))
            )))]
            impl<const CAP: usize> AsRef<OsStr> for [<Array $t:upper String>]<CAP> {
            #[must_use]
                fn as_ref(&self) -> &OsStr {
                    OsStr::from_bytes(self.as_bytes())
                }
            }
        }
    }};
}
generate_array_string![u8, u16, u32];

impl_sized_alias![
    String, ArrayU8String,
    "UTF-8–encoded string, backed by an array of ", ".":
    "A" 16, 1 "";
    "A" 32, 3 "s";
    "A" 64, 7 "s";
    "A" 128, 15 "s";
];

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

    #[test]
    fn push() {
        let mut s = String32::new(); // max capacity == 3

        assert![s.try_push('ñ').is_ok()];
        assert_eq![2, s.len()];
        assert![s.try_push('ñ').is_err()];
        assert_eq![2, s.len()];
        assert![s.try_push('a').is_ok()];
        assert_eq![3, s.len()];
    }

    // TODO
    #[test]
    fn pop() {
        let mut s = String32::new(); // max capacity == 3

        s.push('ñ');
        s.push('a');
        assert_eq![Some('a'), s.pop()];
        assert_eq![Some('ñ'), s.pop()];
        assert_eq![None, s.pop()];
    }
}