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
//! Strings atop octet sequences.
//!
//! This module provides the type `Str<Octets>` that guarantees the same
//! invariants – namely that the content is an UTF-8 encoded string – as
//! the standard library’s `str` and `String` types but atop a generic
//! octet sequence.

use core::{borrow, cmp, fmt, hash, ops, str};
use core::convert::Infallible;
use crate::builder::{
    EmptyBuilder, FreezeBuilder, OctetsBuilder, Truncate, infallible
};
use crate::octets::OctetsFrom;


//------------ Str -----------------------------------------------------------

/// A fixed length UTF-8 encoded string atop an octet sequence.
#[derive(Clone, Default)]
pub struct Str<Octets: ?Sized>(Octets);

impl<Octets> Str<Octets> {
    /// Converts a sequence of octets into a string.
    pub fn from_utf8(octets: Octets) -> Result<Self, FromUtf8Error<Octets>>
    where Octets: AsRef<[u8]> {
        if let Err(error) = str::from_utf8(octets.as_ref()) {
            Err(FromUtf8Error { octets, error })
        }
        else {
            Ok(Self(octets))
        }
    }

    /// Converts a sequence of octets into a string without checking.
    ///
    /// # Safety
    ///
    /// The caller must make sure that the contents of `octets` is a
    /// correctly encoded UTF-8 string.
    pub unsafe fn from_utf8_unchecked(octets: Octets) -> Self {
        Self(octets)
    }
}

impl Str<[u8]> {
    /// Creates a string value from a UTF-8 slice.
    pub fn from_utf8_slice(
        slice: &[u8]
    ) -> Result<&Self, FromUtf8Error<&[u8]>> {
        match str::from_utf8(slice) {
            Ok(s) => Ok(Self::from_str(s)),
            Err(error) => Err(FromUtf8Error { octets: slice, error })
        }
    }

    /// Creates a string value from a string slice.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> &Self {
        unsafe { &*(s as *const str as *const Self) }
    }
}

#[cfg(feature = "std")]
impl Str<std::vec::Vec<u8>> {
    pub fn from_string(s: std::string::String) -> Self {
        unsafe { Self::from_utf8_unchecked(s.into_bytes()) }
    }
}

impl<Octets> Str<Octets> {
    /// Converts the string into its raw octets.
    pub fn into_octets(self) -> Octets {
        self.0
    }
}

impl<Octets: ?Sized> Str<Octets> {
    /// Returns the string as a string slice.
    pub fn as_str(&self) -> &str
    where Octets: AsRef<[u8]> {
        unsafe { str::from_utf8_unchecked(self.0.as_ref()) }
    }

    /// Returns the string as a mutable string slice.
    pub fn as_str_mut(&mut self) -> &mut str
    where Octets: AsMut<[u8]> {
        unsafe { str::from_utf8_unchecked_mut(self.0.as_mut()) }
    }

    /// Returns a reference to the underlying octets sequence.
    pub fn as_octets(&self) -> &Octets {
        &self.0
    }

    /// Returns a mutable reference to the underlying octets sequence.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the content of the octets sequence is
    /// valid UTF-8 before the borrow ends.
    pub unsafe fn as_octets_mut(&mut self) -> &mut Octets {
        &mut self.0
    }

    /// Returns the string’s octets as a slice.
    pub fn as_slice(&self) -> &[u8]
    where Octets: AsRef<[u8]> {
        self.0.as_ref()
    }

    /// Returns a mutable slice of the string’s octets.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the content of the slice is
    /// valid UTF-8 before the borrow ends.
    pub unsafe fn as_slice_mut(&mut self) -> &mut [u8]
    where Octets: AsMut<[u8]> {
        self.0.as_mut()
    }

    /// Returns the length of the string in octets.
    pub fn len(&self) -> usize
    where Octets: AsRef<[u8]> {
        self.0.as_ref().len()
    }

    /// Returns whether the string is empty.
    pub fn is_empty(&self) -> bool
    where Octets: AsRef<[u8]> {
        self.0.as_ref().is_empty()
    }
}


//--- OctetsFrom

impl<Octs, SrcOcts> OctetsFrom<Str<SrcOcts>> for Str<Octs>
where
    Octs: OctetsFrom<SrcOcts>
{
    type Error = Octs::Error;

    fn try_octets_from(src: Str<SrcOcts>) -> Result<Self, Self::Error> {
        Octs::try_octets_from(src.into_octets()).map(|octs| unsafe {
            Self::from_utf8_unchecked(octs)
        })
    }
}


//--- Deref, DerefMut, AsRef, AsMut, Borrow, BorrowMut

impl<Octets: AsRef<[u8]> + ?Sized> ops::Deref for Str<Octets> {
    type Target = str;

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

impl<Octets> ops::DerefMut for Str<Octets>
where Octets: AsRef<[u8]> + AsMut<[u8]> + ?Sized {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_str_mut()
    }
}

impl<Octets: AsRef<[u8]> + ?Sized> AsRef<str> for Str<Octets>{
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<Octets: AsRef<[u8]> + ?Sized> AsRef<[u8]> for Str<Octets>{
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}

impl<Octets: AsMut<[u8]> + ?Sized> AsMut<str> for Str<Octets> {
    fn as_mut(&mut self) -> &mut str {
        self.as_str_mut()
    }
}

impl<Octets: AsRef<[u8]> + ?Sized> borrow::Borrow<str> for Str<Octets>{
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl<Octets> borrow::BorrowMut<str> for Str<Octets> 
where Octets: AsRef<[u8]> +  AsMut<[u8]> + ?Sized {
    fn borrow_mut(&mut self) -> &mut str {
        self.as_str_mut()
    }
}

//--- Debug and Display

impl<Octets: AsRef<[u8]> + ?Sized> fmt::Debug for Str<Octets> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

impl<Octets: AsRef<[u8]> + ?Sized> fmt::Display for Str<Octets> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self.as_str(), f)
    }
}

//--- PartialEq and Eq

impl<Octets, Other> PartialEq<Other> for Str<Octets>
where
    Octets: AsRef<[u8]> + ?Sized,
    Other: AsRef<str> + ?Sized,
{
    fn eq(&self, other: &Other) -> bool {
        self.as_str().eq(other.as_ref())
    }
}

impl<Octets: AsRef<[u8]> + ?Sized> Eq for Str<Octets> { }

//--- Hash

impl<Octets: AsRef<[u8]> + ?Sized> hash::Hash for Str<Octets> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.as_str().hash(state)
    }
}

//--- PartialOrd and Ord

impl<Octets, Other> PartialOrd<Other> for Str<Octets>
where
    Octets: AsRef<[u8]> + ?Sized,
    Other: AsRef<str> + ?Sized,
{
    fn partial_cmp(&self, other: &Other) -> Option<cmp::Ordering> {
        self.as_str().partial_cmp(other.as_ref())
    }
}

impl<Octets: AsRef<[u8]> + ?Sized> Ord for Str<Octets> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.as_str().cmp(other.as_str())
    }
}


//------------ StrBuilder ----------------------------------------------------

/// A growable, UTF-8 encoded string atop an octets builder.
pub struct StrBuilder<Octets>(Octets);

impl<Octets> StrBuilder<Octets> {
    /// Creates a new, empty string builder.
    pub fn new() -> Self
    where Octets: EmptyBuilder {
        StrBuilder(Octets::empty())
    }

    /// Creates a new, empty string builder with a given minimum capacity.
    pub fn with_capacity(capacity: usize) -> Self
    where Octets: EmptyBuilder {
        StrBuilder(Octets::with_capacity(capacity))
    }

    /// Creates a new string builder from an octets builder.
    ///
    /// The function expects the contents of the octets builder to contain
    /// a sequence of UTF-8 encoded characters.
    pub fn from_utf8(octets: Octets) -> Result<Self, FromUtf8Error<Octets>>
    where Octets: AsRef<[u8]> {
        if let Err(error) = str::from_utf8(octets.as_ref()) {
            Err(FromUtf8Error { octets, error })
        }
        else {
            Ok(Self(octets))
        }
    }

    /// Converts on octets builder into a string builder.
    ///
    /// If the octets builder contains invalid octets, they are replaced with
    /// `U+FFFD REPLACEMENT CHARACTER`.
    ///
    /// If the content is UTF-8 encoded, it will remain unchanged. Otherwise,
    /// a new builder is created and the passed builder is dropped.
    pub fn try_from_utf8_lossy(
        octets: Octets
    ) -> Result<Self, Octets::AppendError>
    where Octets: AsRef<[u8]> + OctetsBuilder + EmptyBuilder {
        const REPLACEMENT_CHAR: &[u8] = &[239, 191, 189];

        let mut err = match str::from_utf8(octets.as_ref()) {
            Ok(_) => return Ok(Self(octets)),
            Err(err) => err,
        };
        let mut octets = octets.as_ref();
        let mut res = Octets::with_capacity(octets.len());
        while !octets.is_empty() {
            if err.valid_up_to() > 0 {
                res.append_slice(&octets[..err.valid_up_to()])?;
            }
            res.append_slice(REPLACEMENT_CHAR)?;
            octets = match err.error_len() {
                Some(len) => &octets[err.valid_up_to() + len ..],
                None => b""
            };
            err = match str::from_utf8(octets) {
                Ok(_) => {
                    res.append_slice(octets)?;
                    break;
                }
                Err(err) => err,
            };
        }
        Ok(Self(res))
    }

    pub fn from_utf8_lossy(octets: Octets) -> Self
    where
        Octets: AsRef<[u8]> + OctetsBuilder + EmptyBuilder,
        Octets::AppendError: Into<Infallible>
    {
        infallible(Self::try_from_utf8_lossy(octets))
    }

    /// Converts an octets builder into a string builder without checking.
    ///
    /// For the safe versions, see [from_utf8][Self::from_utf8],
    /// [try_from_utf8_lossy][Self::try_from_utf8_lossy] and
    /// [from_utf8_lossy][Self::from_utf8_lossy].
    ///
    /// # Safety
    ///
    /// The caller must ensure that `octets` contains data that is a correctly
    /// UTF-8 encoded string. It may be empty.
    pub unsafe fn from_utf8_unchecked(octets: Octets) -> Self {
        Self(octets)
    }

    /// Converts the string builder into the underlying octets builder.
    pub fn into_octets_builder(self) -> Octets {
        self.0
    }

    /// Converts the string builder into the final str.
    pub fn freeze(self) -> Str<Octets::Octets>
    where Octets: FreezeBuilder {
        Str(self.0.freeze())
    }

    /// Returns a slice of the already assembled string.
    pub fn as_str(&self) -> &str
    where Octets: AsRef<[u8]> {
        unsafe { str::from_utf8_unchecked(self.0.as_ref()) }
    }

    /// Returns a mutable slice of the already assembled string.
    pub fn as_str_mut(&mut self) -> &mut str
    where Octets: AsMut<[u8]> {
        unsafe { str::from_utf8_unchecked_mut(self.0.as_mut()) }
    }

    /// Returns the string’s octets as a slice.
    pub fn as_slice(&self) -> &[u8]
    where Octets: AsRef<[u8]> {
        self.0.as_ref()
    }

    /// Returns the length of the string in octets.
    pub fn len(&self) -> usize
    where Octets: AsRef<[u8]> {
        self.0.as_ref().len()
    }

    /// Returns whether the string is empty.
    pub fn is_empty(&self) -> bool
    where Octets: AsRef<[u8]> {
        self.0.as_ref().is_empty()
    }

    /// Appends a given string slice onto the end of this builder.
    pub fn try_push_str(
        &mut self, s: &str,
    ) -> Result<(), Octets::AppendError>
    where Octets: OctetsBuilder {
        self.0.append_slice(s.as_bytes())
    }

    /// Appends a given string slice onto the end of this builder.
    pub fn push_str(
        &mut self, s: &str,
    ) 
    where Octets: OctetsBuilder, Octets::AppendError: Into<Infallible>  {
        infallible(self.try_push_str(s))
    }

    /// Appends the given character to the end of the builder.
    pub fn try_push(
        &mut self, ch: char
    ) -> Result<(), Octets::AppendError>
    where Octets: OctetsBuilder {
        let mut buf = [0u8; 4];
        self.0.append_slice(ch.encode_utf8(&mut buf).as_bytes())
    }

    /// Appends the given character to the end of the builder.
    pub fn push(&mut self, ch: char)
    where Octets: OctetsBuilder, Octets::AppendError: Into<Infallible> {
        infallible(self.try_push(ch))
    }

    /// Truncates the builder, keeping the first `new_len` octets.
    ///
    /// # Panics
    ///
    /// The method panics if `new_len` does not lie on a `char` boundary.
    pub fn truncate(&mut self, new_len: usize)
    where Octets: AsRef<[u8]> + Truncate {
        if new_len < self.len() {
            assert!(self.as_str().is_char_boundary(new_len));
            self.0.truncate(new_len)
        }
    }

    /// Clears the builder into an empty builder.
    pub fn clear(&mut self)
    where Octets: AsRef<[u8]> + Truncate {
        self.truncate(0)
    }

    /// Removes the last character from the builder and returns it.
    ///
    /// Returns `None` if the builder is empty.
    pub fn pop(&mut self) -> Option<char>
    where Octets: AsRef<[u8]> + Truncate {
        let ch = self.as_str().chars().next_back()?;
        self.truncate(self.len() - ch.len_utf8());
        Some(ch)
    }
}


//-- Default

impl<Octets: EmptyBuilder> Default for StrBuilder<Octets> {
    fn default() -> Self {
        Self::new()
    }
}


//--- Deref, DerefMut, AsRef, AsMut, Borrow, BorrowMut

impl<Octets: AsRef<[u8]>> ops::Deref for StrBuilder<Octets> {
    type Target = str;

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

impl<Octets: AsRef<[u8]> + AsMut<[u8]>> ops::DerefMut for StrBuilder<Octets> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_str_mut()
    }
}

impl<Octets: AsRef<[u8]>> AsRef<str> for StrBuilder<Octets>{
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<Octets: AsRef<[u8]>> AsRef<[u8]> for StrBuilder<Octets>{
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}

impl<Octets: AsMut<[u8]>> AsMut<str> for StrBuilder<Octets> {
    fn as_mut(&mut self) -> &mut str {
        self.as_str_mut()
    }
}

impl<Octets: AsRef<[u8]>> borrow::Borrow<str> for StrBuilder<Octets>{
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl<Octets> borrow::BorrowMut<str> for StrBuilder<Octets> 
where Octets: AsRef<[u8]> +  AsMut<[u8]> {
    fn borrow_mut(&mut self) -> &mut str {
        self.as_str_mut()
    }
}

//--- Debug and Display

impl<Octets: AsRef<[u8]>> fmt::Debug for StrBuilder<Octets> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

impl<Octets: AsRef<[u8]>> fmt::Display for StrBuilder<Octets> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self.as_str(), f)
    }
}

//--- PartialEq and Eq

impl<Octets, Other> PartialEq<Other> for StrBuilder<Octets>
where
    Octets: AsRef<[u8]>,
    Other: AsRef<str>,
{
    fn eq(&self, other: &Other) -> bool {
        self.as_str().eq(other.as_ref())
    }
}

impl<Octets: AsRef<[u8]>> Eq for StrBuilder<Octets> { }

//--- Hash

impl<Octets: AsRef<[u8]>> hash::Hash for StrBuilder<Octets> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.as_str().hash(state)
    }
}

//--- PartialOrd and Ord

impl<Octets, Other> PartialOrd<Other> for StrBuilder<Octets>
where
    Octets: AsRef<[u8]>,
    Other: AsRef<str>,
{
    fn partial_cmp(&self, other: &Other) -> Option<cmp::Ordering> {
        self.as_str().partial_cmp(other.as_ref())
    }
}

impl<Octets: AsRef<[u8]>> Ord for StrBuilder<Octets> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.as_str().cmp(other.as_str())
    }
}


//============ Error Types ===================================================

//------------ FromUtf8Error -------------------------------------------------

/// An error happened when converting octets into a string.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct FromUtf8Error<Octets> {
    octets: Octets,
    error: str::Utf8Error,
}

impl<Octets> FromUtf8Error<Octets> {
    /// Returns an octets slice of the data that failed to convert.
    pub fn as_slice(&self) -> &[u8]
    where Octets: AsRef<[u8]> {
        self.octets.as_ref()
    }

    /// Returns the octets sequence that failed to convert.
    pub fn into_octets(self) -> Octets {
        self.octets
    }

    /// Returns the reason for the conversion error.
    pub fn utf8_error(&self) -> str::Utf8Error {
        self.error
    }
}

impl<Octets> fmt::Debug for FromUtf8Error<Octets> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("FromUtf8Error")
            .field("error", &self.error)
            .finish_non_exhaustive()
    }
}

impl<Octets> fmt::Display for FromUtf8Error<Octets> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.error, f)
    }
}

#[cfg(feature = "std")]
impl<Octets> std::error::Error for FromUtf8Error<Octets> {}


//============ Testing =======================================================

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

    // Most of the test cases herein have been borrowed from the test cases
    // of the Rust standard library.

    #[test]
    #[cfg(feature = "std")]
    fn from_utf8_lossy() {
        fn check(src: impl AsRef<[u8]>) {
            assert_eq!(
                StrBuilder::from_utf8_lossy(std::vec::Vec::from(src.as_ref())),
                std::string::String::from_utf8_lossy(src.as_ref())
            );
        }

        check(b"hello");
        check("ศไทย中华Việt Nam");
        check(b"Hello\xC2 There\xFF Goodbye");
        check(b"Hello\xC0\x80 There\xE6\x83 Goodbye");
        check(b"\xF5foo\xF5\x80bar");
        check(b"\xF1foo\xF1\x80bar\xF1\x80\x80baz");
        check(b"\xF4foo\xF4\x80bar\xF4\xBFbaz");
        check(b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar");
        check(b"\xED\xA0\x80foo\xED\xBF\xBFbar");
    }

    #[test]
    #[cfg(feature = "std")]
    fn push_str() {
        let mut s = StrBuilder::<std::vec::Vec<u8>>::new();
        s.push_str("");
        assert_eq!(&s[0..], "");
        s.push_str("abc");
        assert_eq!(&s[0..], "abc");
        s.push_str("ประเทศไทย中华Việt Nam");
        assert_eq!(&s[0..], "abcประเทศไทย中华Việt Nam");
    }

    #[test]
    #[cfg(feature = "std")]
    fn push() {
        let mut data = StrBuilder::from_utf8(
            std::vec::Vec::from("ประเทศไทย中".as_bytes())
        ).unwrap();
        data.push('华');
        data.push('b'); // 1 byte
        data.push('¢'); // 2 byte
        data.push('€'); // 3 byte
        data.push('𤭢'); // 4 byte
        assert_eq!(data, "ประเทศไทย中华b¢€𤭢");
    }

    #[test]
    #[cfg(feature = "std")]
    fn pop() {
        let mut data = StrBuilder::from_utf8(
            std::vec::Vec::from("ประเทศไทย中华b¢€𤭢".as_bytes())
        ).unwrap();
        assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes
        assert_eq!(data.pop().unwrap(), '€'); // 3 bytes
        assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes
        assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes
        assert_eq!(data.pop().unwrap(), '华');
        assert_eq!(data, "ประเทศไทย中");
    }
}