Skip to main content

hstr/wtf8/
mod.rs

1// Copyright (c) 2014 Simon Sapin
2// Licensed under the MIT License
3// Original source: https://github.com/SimonSapin/rust-wtf8
4
5/*!
6
7Implementation of [the WTF-8 encoding](https://simonsapin.github.io/wtf-8/).
8
9This library uses Rust’s type system to maintain
10[well-formedness](https://simonsapin.github.io/wtf-8/#well-formed),
11like the `String` and `&str` types do for UTF-8.
12
13Since [WTF-8 must not be used
14for interchange](https://simonsapin.github.io/wtf-8/#intended-audience),
15this library deliberately does not provide access to the underlying bytes
16of WTF-8 strings,
17nor can it decode WTF-8 from arbitrary bytes.
18WTF-8 strings can be obtained from UTF-8, UTF-16, or code points.
19
20*/
21
22extern crate alloc;
23
24use alloc::{
25    borrow::{Borrow, Cow},
26    string::String,
27    vec::Vec,
28};
29use core::{
30    fmt, hash,
31    iter::{FromIterator, IntoIterator},
32    mem::transmute,
33    ops::Deref,
34    slice, str,
35    str::FromStr,
36};
37use std::ops::Add;
38
39mod not_quite_std;
40
41static UTF8_REPLACEMENT_CHARACTER: &[u8] = b"\xEF\xBF\xBD";
42
43/// A Unicode code point: from U+0000 to U+10FFFF.
44///
45/// Compare with the `char` type,
46/// which represents a Unicode scalar value:
47/// a code point that is not a surrogate (U+D800 to U+DFFF).
48#[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
49pub struct CodePoint {
50    value: u32,
51}
52
53impl Copy for CodePoint {}
54
55/// Format the code point as `U+` followed by four to six hexadecimal digits.
56/// Example: `U+1F4A9`
57impl fmt::Debug for CodePoint {
58    #[inline]
59    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
60        write!(formatter, "U+{:04X}", self.value)
61    }
62}
63
64impl CodePoint {
65    /// Unsafely create a new `CodePoint` without checking the value.
66    ///
67    /// # Safety
68    ///
69    /// Only use when `value` is known to be less than or equal to 0x10FFFF.
70    #[inline]
71    pub const unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
72        CodePoint { value }
73    }
74
75    /// Create a new `CodePoint` if the value is a valid code point.
76    ///
77    /// Return `None` if `value` is above 0x10FFFF.
78    #[inline]
79    pub const fn from_u32(value: u32) -> Option<CodePoint> {
80        match value {
81            0..=0x10ffff => Some(CodePoint { value }),
82            _ => None,
83        }
84    }
85
86    /// Create a new `CodePoint` from a `char`.
87    ///
88    /// Since all Unicode scalar values are code points, this always succeds.
89    #[inline]
90    pub const fn from_char(value: char) -> CodePoint {
91        CodePoint {
92            value: value as u32,
93        }
94    }
95
96    /// Return the numeric value of the code point.
97    #[inline]
98    pub fn to_u32(&self) -> u32 {
99        self.value
100    }
101
102    /// Optionally return a Unicode scalar value for the code point.
103    ///
104    /// Return `None` if the code point is a surrogate (from U+D800 to U+DFFF).
105    #[inline]
106    pub fn to_char(&self) -> Option<char> {
107        match self.value {
108            0xd800..=0xdfff => None,
109            _ => Some(unsafe { char::from_u32_unchecked(self.value) }),
110        }
111    }
112
113    /// Return a Unicode scalar value for the code point.
114    ///
115    /// Return `'\u{FFFD}'` (the replacement character “�”)
116    /// if the code point is a surrogate (from U+D800 to U+DFFF).
117    #[inline]
118    pub fn to_char_lossy(&self) -> char {
119        self.to_char().unwrap_or('\u{FFFD}')
120    }
121
122    /// Return `true` if the code point is in the ASCII range.
123    #[inline]
124    pub fn is_ascii(&self) -> bool {
125        self.value <= 0x7f
126    }
127}
128
129impl PartialEq<char> for CodePoint {
130    fn eq(&self, other: &char) -> bool {
131        self.value == *other as u32
132    }
133}
134
135/// An owned, growable string of well-formed WTF-8 data.
136///
137/// Similar to `String`, but can additionally contain surrogate code points
138/// if they’re not in a surrogate pair.
139#[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
140pub struct Wtf8Buf {
141    bytes: Vec<u8>,
142}
143
144impl Deref for Wtf8Buf {
145    type Target = Wtf8;
146
147    fn deref(&self) -> &Wtf8 {
148        unsafe { transmute(&*self.bytes) }
149    }
150}
151
152/// Format the string with double quotes,
153/// and surrogates as `\u` followed by four hexadecimal digits.
154/// Example: `"a\u{D800}"` for a string with code points [U+0061, U+D800]
155impl fmt::Debug for Wtf8Buf {
156    #[inline]
157    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
158        Wtf8::fmt(self, formatter)
159    }
160}
161
162impl Default for Wtf8Buf {
163    #[inline]
164    fn default() -> Self {
165        Self::new()
166    }
167}
168
169impl FromStr for Wtf8Buf {
170    type Err = core::convert::Infallible;
171
172    #[inline]
173    fn from_str(s: &str) -> Result<Self, Self::Err> {
174        Ok(Wtf8Buf {
175            bytes: s.as_bytes().to_vec(),
176        })
177    }
178}
179
180impl fmt::Write for Wtf8Buf {
181    fn write_str(&mut self, s: &str) -> std::fmt::Result {
182        self.push_str(s);
183        Ok(())
184    }
185}
186
187impl Add<&Wtf8> for Wtf8Buf {
188    type Output = Wtf8Buf;
189
190    fn add(self, rhs: &Wtf8) -> Self::Output {
191        let mut result = self;
192        result.push_wtf8(rhs);
193        result
194    }
195}
196
197impl Wtf8Buf {
198    /// Create an new, empty WTF-8 string.
199    #[inline]
200    pub fn new() -> Wtf8Buf {
201        Wtf8Buf { bytes: Vec::new() }
202    }
203
204    /// Create an new, empty WTF-8 string with pre-allocated capacity for `n`
205    /// bytes.
206    #[inline]
207    pub fn with_capacity(n: usize) -> Wtf8Buf {
208        Wtf8Buf {
209            bytes: Vec::with_capacity(n),
210        }
211    }
212
213    /// Create a WTF-8 string from an UTF-8 `String`.
214    ///
215    /// This takes ownership of the `String` and does not copy.
216    ///
217    /// Since WTF-8 is a superset of UTF-8, this always succeeds.
218    #[inline]
219    pub fn from_string(string: String) -> Wtf8Buf {
220        Wtf8Buf {
221            bytes: string.into_bytes(),
222        }
223    }
224
225    /// Create a WTF-8 string from an UTF-8 `&str` slice.
226    ///
227    /// This copies the content of the slice.
228    ///
229    /// Since WTF-8 is a superset of UTF-8, this always succeeds.
230    #[inline]
231    #[allow(clippy::should_implement_trait)]
232    pub fn from_str(s: &str) -> Wtf8Buf {
233        Wtf8Buf {
234            bytes: s.as_bytes().to_vec(),
235        }
236    }
237
238    /// Create a WTF-8 string from a potentially ill-formed UTF-16 slice of
239    /// 16-bit code units.
240    ///
241    /// This is lossless: calling `.to_ill_formed_utf16()` on the resulting
242    /// string will always return the original code units.
243    pub fn from_ill_formed_utf16(v: &[u16]) -> Wtf8Buf {
244        let mut string = Wtf8Buf::with_capacity(v.len());
245        for item in not_quite_std::decode_utf16(v.iter().cloned()) {
246            match item {
247                Ok(c) => string.push_char(c),
248                Err(s) => {
249                    // Surrogates are known to be in the code point range.
250                    let code_point = unsafe { CodePoint::from_u32_unchecked(s as u32) };
251                    // Skip the WTF-8 concatenation check,
252                    // surrogate pairs are already decoded by utf16_items
253                    not_quite_std::push_code_point(&mut string, code_point)
254                }
255            }
256        }
257        string
258    }
259
260    /// Reserves capacity for at least `additional` more bytes to be inserted
261    /// in the given `Wtf8Buf`.
262    /// The collection may reserve more space to avoid frequent reallocations.
263    ///
264    /// # Panics
265    ///
266    /// Panics if the new capacity overflows `usize`.
267    #[inline]
268    pub fn reserve(&mut self, additional: usize) {
269        self.bytes.reserve(additional)
270    }
271
272    /// Returns the number of bytes that this string buffer can hold without
273    /// reallocating.
274    #[inline]
275    pub fn capacity(&self) -> usize {
276        self.bytes.capacity()
277    }
278
279    /// Append an UTF-8 slice at the end of the string.
280    #[inline]
281    pub fn push_str(&mut self, other: &str) {
282        self.bytes.extend_from_slice(other.as_bytes())
283    }
284
285    /// Append a WTF-8 slice at the end of the string.
286    ///
287    /// This replaces newly paired surrogates at the boundary
288    /// with a supplementary code point,
289    /// like concatenating ill-formed UTF-16 strings effectively would.
290    #[inline]
291    pub fn push_wtf8(&mut self, other: &Wtf8) {
292        match (self.final_lead_surrogate(), other.initial_trail_surrogate()) {
293            // Replace newly paired surrogates by a supplementary code point.
294            (Some(lead), Some(trail)) => {
295                let len_without_lead_surrogate = self.len() - 3;
296                self.bytes.truncate(len_without_lead_surrogate);
297                let other_without_trail_surrogate = &other.bytes[3..];
298                // 4 bytes for the supplementary code point
299                self.bytes.reserve(4 + other_without_trail_surrogate.len());
300                self.push_char(decode_surrogate_pair(lead, trail));
301                self.bytes.extend_from_slice(other_without_trail_surrogate);
302            }
303            _ => self.bytes.extend_from_slice(&other.bytes),
304        }
305    }
306
307    /// Append a Unicode scalar value at the end of the string.
308    #[inline]
309    pub fn push_char(&mut self, c: char) {
310        not_quite_std::push_code_point(self, CodePoint::from_char(c))
311    }
312
313    /// Append a code point at the end of the string.
314    ///
315    /// This replaces newly paired surrogates at the boundary
316    /// with a supplementary code point,
317    /// like concatenating ill-formed UTF-16 strings effectively would.
318    #[inline]
319    pub fn push(&mut self, code_point: CodePoint) {
320        if let trail @ 0xdc00..=0xdfff = code_point.to_u32() {
321            if let Some(lead) = self.final_lead_surrogate() {
322                let len_without_lead_surrogate = self.len() - 3;
323                self.bytes.truncate(len_without_lead_surrogate);
324                self.push_char(decode_surrogate_pair(lead, trail as u16));
325                return;
326            }
327        }
328
329        // No newly paired surrogates at the boundary.
330        not_quite_std::push_code_point(self, code_point)
331    }
332
333    /// Shortens a string to the specified length.
334    ///
335    /// # Failure
336    ///
337    /// Fails if `new_len` > current length,
338    /// or if `new_len` is not a code point boundary.
339    #[inline]
340    pub fn truncate(&mut self, new_len: usize) {
341        assert!(not_quite_std::is_code_point_boundary(self, new_len));
342        self.bytes.truncate(new_len)
343    }
344
345    /// Clear the WTF-8 vector, removing all contents.
346    #[inline]
347    pub fn clear(&mut self) {
348        self.bytes.clear();
349    }
350
351    /// Consume the WTF-8 string and try to convert it to UTF-8.
352    ///
353    /// This does not copy the data.
354    ///
355    /// If the contents are not well-formed UTF-8
356    /// (that is, if the string contains surrogates),
357    /// the original WTF-8 string is returned instead.
358    pub fn into_string(self) -> Result<String, Wtf8Buf> {
359        match self.next_surrogate(0) {
360            None => Ok(unsafe { String::from_utf8_unchecked(self.bytes) }),
361            Some(_) => Err(self),
362        }
363    }
364
365    /// Consume the WTF-8 string and convert it lossily to UTF-8.
366    ///
367    /// This does not copy the data (but may overwrite parts of it in place).
368    ///
369    /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character
370    /// “�”)
371    pub fn into_string_lossy(mut self) -> String {
372        let mut pos = 0;
373        loop {
374            match self.next_surrogate(pos) {
375                Some((surrogate_pos, _)) => {
376                    pos = surrogate_pos + 3;
377                    self.bytes[surrogate_pos..pos].copy_from_slice(UTF8_REPLACEMENT_CHARACTER);
378                }
379                None => return unsafe { String::from_utf8_unchecked(self.bytes) },
380            }
381        }
382    }
383
384    /// Create a [Wtf8Buf] from a WTF-8 encoded byte vector.
385    ///
386    /// Returns `Ok(Wtf8Buf)` if the bytes are well-formed WTF-8, or
387    /// `Err(bytes)` with the original bytes if validation fails.
388    ///
389    /// This validates that:
390    /// - All bytes form valid UTF-8 sequences OR valid surrogate code point
391    ///   encodings
392    /// - Surrogate code points may appear unpaired and be encoded separately,
393    ///   but if they are paired, they must be encoded as a single 4-byte UTF-8
394    ///   sequence. For example, the byte sequence `[0xED, 0xA0, 0x80, 0xED,
395    ///   0xB0, 0x80]` is not valid WTF-8 because WTF-8 forbids encoding a
396    ///   surrogate pair as two separate 3-byte sequences.
397    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, Vec<u8>> {
398        if not_quite_std::validate_wtf8(&bytes) {
399            Ok(Self { bytes })
400        } else {
401            Err(bytes)
402        }
403    }
404
405    /// Create a [Wtf8Buf] from a WTF-8 encoded byte vector without checking
406    /// that the bytes contain valid WTF-8.
407    ///
408    /// For the safe version, see [Wtf8Buf::from_bytes].
409    ///
410    /// # Safety
411    ///
412    /// The bytes passed in must be valid WTF-8. See [Wtf8Buf::from_bytes] for
413    /// the requirements.
414    #[inline]
415    pub unsafe fn from_bytes_unchecked(bytes: Vec<u8>) -> Self {
416        Self { bytes }
417    }
418}
419
420/// Create a new WTF-8 string from an iterator of code points.
421///
422/// This replaces surrogate code point pairs with supplementary code points,
423/// like concatenating ill-formed UTF-16 strings effectively would.
424impl FromIterator<CodePoint> for Wtf8Buf {
425    fn from_iter<T: IntoIterator<Item = CodePoint>>(iterable: T) -> Wtf8Buf {
426        let mut string = Wtf8Buf::new();
427        string.extend(iterable);
428        string
429    }
430}
431
432/// Append code points from an iterator to the string.
433///
434/// This replaces surrogate code point pairs with supplementary code points,
435/// like concatenating ill-formed UTF-16 strings effectively would.
436impl Extend<CodePoint> for Wtf8Buf {
437    fn extend<T: IntoIterator<Item = CodePoint>>(&mut self, iterable: T) {
438        let iterator = iterable.into_iter();
439        let (low, _high) = iterator.size_hint();
440        // Lower bound of one byte per code point (ASCII only)
441        self.bytes.reserve(low);
442        for code_point in iterator {
443            self.push(code_point);
444        }
445    }
446}
447
448/// A borrowed slice of well-formed WTF-8 data.
449///
450/// Similar to `&str`, but can additionally contain surrogate code points
451/// if they're not in a surrogate pair.
452#[repr(transparent)]
453#[derive(PartialEq, Eq, PartialOrd, Ord)]
454pub struct Wtf8 {
455    bytes: [u8],
456}
457
458/// Format the slice with double quotes,
459/// and surrogates as `\u` followed by four hexadecimal digits.
460/// Example: `"a\u{D800}"` for a slice with code points [U+0061, U+D800]
461impl fmt::Debug for Wtf8 {
462    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
463        formatter.write_str("\"")?;
464        let mut pos = 0;
465        loop {
466            match self.next_surrogate(pos) {
467                None => break,
468                Some((surrogate_pos, surrogate)) => {
469                    formatter.write_str(unsafe {
470                        str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos])
471                    })?;
472                    write!(formatter, "\\u{{{surrogate:X}}}")?;
473                    pos = surrogate_pos + 3;
474                }
475            }
476        }
477        formatter.write_str(unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?;
478        formatter.write_str("\"")
479    }
480}
481
482impl Wtf8 {
483    /// Create a WTF-8 slice from a UTF-8 `&str` slice.
484    ///
485    /// Since WTF-8 is a superset of UTF-8, this always succeeds.
486    #[inline]
487    pub const fn from_str(value: &str) -> &Wtf8 {
488        unsafe { transmute(value.as_bytes()) }
489    }
490
491    /// Return the length, in WTF-8 bytes.
492    #[inline]
493    pub const fn len(&self) -> usize {
494        self.bytes.len()
495    }
496
497    /// Return `true` if the string has a length of zero bytes.
498    #[inline]
499    pub const fn is_empty(&self) -> bool {
500        self.bytes.is_empty()
501    }
502
503    /// Return `true` if the string contains only ASCII characters.
504    #[inline]
505    pub const fn is_ascii(&self) -> bool {
506        let mut i = 0;
507
508        while i < self.bytes.len() {
509            if !self.bytes[i].is_ascii() {
510                return false;
511            }
512
513            i += 1;
514        }
515
516        true
517    }
518
519    /// Return a slice of the given string for the byte range [`begin`..`end`).
520    ///
521    /// # Failure
522    ///
523    /// Fails when `begin` and `end` do not point to code point boundaries,
524    /// or point beyond the end of the string.
525    #[inline]
526    pub fn slice(&self, begin: usize, end: usize) -> &Wtf8 {
527        // is_code_point_boundary checks that the index is in [0, .len()]
528        if begin <= end
529            && not_quite_std::is_code_point_boundary(self, begin)
530            && not_quite_std::is_code_point_boundary(self, end)
531        {
532            unsafe { not_quite_std::slice_unchecked(self, begin, end) }
533        } else {
534            not_quite_std::slice_error_fail(self, begin, end)
535        }
536    }
537
538    /// Return a slice of the given string from byte `begin` to its end.
539    ///
540    /// # Failure
541    ///
542    /// Fails when `begin` is not at a code point boundary,
543    /// or is beyond the end of the string.
544    #[inline]
545    pub fn slice_from(&self, begin: usize) -> &Wtf8 {
546        // is_code_point_boundary checks that the index is in [0, .len()]
547        if not_quite_std::is_code_point_boundary(self, begin) {
548            unsafe { not_quite_std::slice_unchecked(self, begin, self.len()) }
549        } else {
550            not_quite_std::slice_error_fail(self, begin, self.len())
551        }
552    }
553
554    /// Return a slice of the given string from its beginning to byte `end`.
555    ///
556    /// # Failure
557    ///
558    /// Fails when `end` is not at a code point boundary,
559    /// or is beyond the end of the string.
560    #[inline]
561    pub fn slice_to(&self, end: usize) -> &Wtf8 {
562        // is_code_point_boundary checks that the index is in [0, .len()]
563        if not_quite_std::is_code_point_boundary(self, end) {
564            unsafe { not_quite_std::slice_unchecked(self, 0, end) }
565        } else {
566            not_quite_std::slice_error_fail(self, 0, end)
567        }
568    }
569
570    /// Return the code point at `position` if it is in the ASCII range,
571    /// or `b'\xFF' otherwise.
572    ///
573    /// # Failure
574    ///
575    /// Fails if `position` is beyond the end of the string.
576    #[inline]
577    pub fn ascii_byte_at(&self, position: usize) -> u8 {
578        match self.bytes[position] {
579            ascii_byte @ 0x00..=0x7f => ascii_byte,
580            _ => 0xff,
581        }
582    }
583
584    /// Return an iterator for the string’s code points.
585    #[inline]
586    pub fn code_points(&self) -> Wtf8CodePoints<'_> {
587        Wtf8CodePoints {
588            bytes: self.bytes.iter(),
589        }
590    }
591
592    /// Returns `true` if this WTF-8 string contains the given character.
593    #[inline]
594    pub fn contains_char(&self, ch: char) -> bool {
595        let target = CodePoint::from_char(ch);
596        self.contains(target)
597    }
598
599    /// Returns `true` if this WTF-8 string contains the given code point.
600    #[inline]
601    pub fn contains(&self, code_point: CodePoint) -> bool {
602        self.code_points().any(|cp| cp == code_point)
603    }
604
605    /// Returns `true` if this WTF-8 string starts with the given UTF-8 string.
606    #[inline]
607    pub fn starts_with(&self, pattern: &str) -> bool {
608        self.as_bytes().starts_with(pattern.as_bytes())
609    }
610
611    /// Try to convert the string to UTF-8 and return a `&str` slice.
612    ///
613    /// Return `None` if the string contains surrogates.
614    ///
615    /// This does not copy the data.
616    #[inline]
617    pub fn as_str(&self) -> Option<&str> {
618        // Well-formed WTF-8 is also well-formed UTF-8
619        // if and only if it contains no surrogate.
620        match self.next_surrogate(0) {
621            None => Some(unsafe { str::from_utf8_unchecked(&self.bytes) }),
622            Some(_) => None,
623        }
624    }
625
626    /// Return the underlying WTF-8 bytes.
627    #[inline]
628    pub const fn as_bytes(&self) -> &[u8] {
629        &self.bytes
630    }
631
632    /// Lossily convert the string to UTF-8.
633    /// Return an UTF-8 `&str` slice if the contents are well-formed in UTF-8.
634    ///
635    /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character
636    /// “�”).
637    ///
638    /// This only copies the data if necessary (if it contains any surrogate).
639    pub fn to_string_lossy(&self) -> Cow<'_, str> {
640        let surrogate_pos = match self.next_surrogate(0) {
641            None => return Cow::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) }),
642            Some((pos, _)) => pos,
643        };
644        let wtf8_bytes = &self.bytes;
645        let mut utf8_bytes = Vec::with_capacity(self.len());
646        utf8_bytes.extend_from_slice(&wtf8_bytes[..surrogate_pos]);
647        utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER);
648        let mut pos = surrogate_pos + 3;
649        loop {
650            match self.next_surrogate(pos) {
651                Some((surrogate_pos, _)) => {
652                    utf8_bytes.extend_from_slice(&wtf8_bytes[pos..surrogate_pos]);
653                    utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER);
654                    pos = surrogate_pos + 3;
655                }
656                None => {
657                    utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]);
658                    return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) });
659                }
660            }
661        }
662    }
663
664    /// Convert the WTF-8 string to potentially ill-formed UTF-16
665    /// and return an iterator of 16-bit code units.
666    ///
667    /// This is lossless:
668    /// calling `Wtf8Buf::from_ill_formed_utf16` on the resulting code units
669    /// would always return the original WTF-8 string.
670    #[inline]
671    pub fn to_ill_formed_utf16(&self) -> IllFormedUtf16CodeUnits<'_> {
672        IllFormedUtf16CodeUnits {
673            code_points: self.code_points(),
674            extra: 0,
675        }
676    }
677
678    /// Returns the uppercase equivalent of this wtf8 slice, as a new [Wtf8Buf].
679    #[inline]
680    pub fn to_uppercase(&self) -> Wtf8Buf {
681        let mut result = Wtf8Buf::with_capacity(self.len());
682        for cp in self.code_points() {
683            if let Some(ch) = cp.to_char() {
684                for upper_ch in ch.to_uppercase() {
685                    result.push_char(upper_ch);
686                }
687            } else {
688                // Surrogates are known to be in the code point range.
689                let code_point = unsafe { CodePoint::from_u32_unchecked(cp.to_u32()) };
690                // Skip the WTF-8 concatenation check,
691                // surrogate pairs are already decoded by utf16_items
692                not_quite_std::push_code_point(&mut result, code_point)
693            }
694        }
695        result
696    }
697
698    /// Returns the lowercase equivalent of this wtf8 slice, as a new [Wtf8Buf].
699    #[inline]
700    pub fn to_lowercase(&self) -> Wtf8Buf {
701        let mut result = Wtf8Buf::with_capacity(self.len());
702        for cp in self.code_points() {
703            if let Some(ch) = cp.to_char() {
704                for lower_ch in ch.to_lowercase() {
705                    result.push_char(lower_ch);
706                }
707            } else {
708                // Surrogates are known to be in the code point range.
709                let code_point = unsafe { CodePoint::from_u32_unchecked(cp.to_u32()) };
710                // Skip the WTF-8 concatenation check,
711                // surrogate pairs are already decoded by utf16_items
712                not_quite_std::push_code_point(&mut result, code_point)
713            }
714        }
715        result
716    }
717
718    /// Create a WTF-8 slice from a WTF-8 encoded byte slice.
719    ///
720    /// Returns `Ok(&Wtf8)` if the bytes are well-formed WTF-8, or
721    /// `Err(bytes)` with the original byte slice if validation fails.
722    ///
723    /// This validates that:
724    /// - All bytes form valid UTF-8 sequences OR valid surrogate code point
725    ///   encodings
726    /// - Surrogate code points may appear unpaired and be encoded separately,
727    ///   but if they are paired, they must be encoded as a single 4-byte UTF-8
728    ///   sequence. For example, the byte sequence `[0xED, 0xA0, 0x80, 0xED,
729    ///   0xB0, 0x80]` is not valid WTF-8 because WTF-8 forbids encoding a
730    ///   surrogate pair as two separate 3-byte sequences.
731    pub fn from_bytes(bytes: &[u8]) -> Result<&Wtf8, &[u8]> {
732        if not_quite_std::validate_wtf8(bytes) {
733            Ok(unsafe { transmute::<&[u8], &Wtf8>(bytes) })
734        } else {
735            Err(bytes)
736        }
737    }
738
739    /// Create a WTF-8 slice from a WTF-8 encoded byte slice without checking
740    /// that the bytes contain valid WTF-8.
741    ///
742    /// For the safe version, see [Wtf8::from_bytes].
743    ///
744    /// # Safety
745    ///
746    /// The bytes passed in must be valid WTF-8. See [Wtf8::from_bytes] for
747    /// the requirements.
748    #[inline]
749    pub const unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Wtf8 {
750        unsafe { transmute(bytes) }
751    }
752
753    #[inline]
754    fn next_surrogate(&self, mut pos: usize) -> Option<(usize, u16)> {
755        let mut iter = self.bytes[pos..].iter();
756        loop {
757            let b = match iter.next() {
758                None => return None,
759                Some(&b) => b,
760            };
761            if b < 0x80 {
762                pos += 1;
763            } else if b < 0xe0 {
764                iter.next();
765                pos += 2;
766            } else if b == 0xed {
767                match (iter.next(), iter.next()) {
768                    (Some(&b2), Some(&b3)) if b2 >= 0xa0 => {
769                        return Some((pos, decode_surrogate(b2, b3)))
770                    }
771                    _ => pos += 3,
772                }
773            } else if b < 0xf0 {
774                iter.next();
775                iter.next();
776                pos += 3;
777            } else {
778                iter.next();
779                iter.next();
780                iter.next();
781                pos += 4;
782            }
783        }
784    }
785
786    #[inline]
787    fn final_lead_surrogate(&self) -> Option<u16> {
788        let len = self.len();
789        if len < 3 {
790            return None;
791        }
792        let seq = &self.bytes[len - 3..];
793        if seq[0] == 0xed && 0xa0 <= seq[1] && seq[1] <= 0xaf {
794            Some(decode_surrogate(seq[1], seq[2]))
795        } else {
796            None
797        }
798    }
799
800    #[inline]
801    fn initial_trail_surrogate(&self) -> Option<u16> {
802        let len = self.len();
803        if len < 3 {
804            return None;
805        }
806        let seq = &self.bytes[..3];
807        if seq[0] == 0xed && 0xb0 <= seq[1] && seq[1] <= 0xbf {
808            Some(decode_surrogate(seq[1], seq[2]))
809        } else {
810            None
811        }
812    }
813}
814
815#[inline]
816fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 {
817    // The first byte is assumed to be 0xED
818    0xd800 | (second_byte as u16 & 0x3f) << 6 | third_byte as u16 & 0x3f
819}
820
821#[inline]
822fn decode_surrogate_pair(lead: u16, trail: u16) -> char {
823    let code_point = 0x10000 + (((lead as u32 - 0xd800) << 10) | (trail as u32 - 0xdc00));
824    unsafe { char::from_u32_unchecked(code_point) }
825}
826
827/// Iterator for the code points of a WTF-8 string.
828///
829/// Created with the method `.code_points()`.
830#[derive(Clone)]
831pub struct Wtf8CodePoints<'a> {
832    bytes: slice::Iter<'a, u8>,
833}
834
835impl<'a> Iterator for Wtf8CodePoints<'a> {
836    type Item = CodePoint;
837
838    #[inline]
839    fn next(&mut self) -> Option<CodePoint> {
840        not_quite_std::next_code_point(&mut self.bytes).map(|value| {
841            // Wtf8 invariant says `value` is a valid code point
842            unsafe { CodePoint::from_u32_unchecked(value) }
843        })
844    }
845
846    #[inline]
847    fn size_hint(&self) -> (usize, Option<usize>) {
848        let (len, _) = self.bytes.size_hint();
849        (len.saturating_add(3) / 4, Some(len))
850    }
851}
852
853#[derive(Clone)]
854pub struct IllFormedUtf16CodeUnits<'a> {
855    code_points: Wtf8CodePoints<'a>,
856    extra: u16,
857}
858
859impl<'a> Iterator for IllFormedUtf16CodeUnits<'a> {
860    type Item = u16;
861
862    #[inline]
863    fn next(&mut self) -> Option<u16> {
864        not_quite_std::next_utf16_code_unit(self)
865    }
866
867    #[inline]
868    fn size_hint(&self) -> (usize, Option<usize>) {
869        let (low, high) = self.code_points.size_hint();
870        // every code point gets either one u16 or two u16,
871        // so this iterator is between 1 or 2 times as
872        // long as the underlying iterator.
873        (low, high.and_then(|n| n.checked_mul(2)))
874    }
875}
876
877impl PartialEq<&Wtf8> for Wtf8Buf {
878    fn eq(&self, other: &&Wtf8) -> bool {
879        **self == **other
880    }
881}
882
883impl PartialEq<Wtf8Buf> for &Wtf8 {
884    fn eq(&self, other: &Wtf8Buf) -> bool {
885        **self == **other
886    }
887}
888
889impl PartialEq<str> for &Wtf8 {
890    fn eq(&self, other: &str) -> bool {
891        match self.as_str() {
892            Some(s) => s == other,
893            None => false,
894        }
895    }
896}
897
898impl PartialEq<&str> for &Wtf8 {
899    fn eq(&self, other: &&str) -> bool {
900        match self.as_str() {
901            Some(s) => s == *other,
902            None => false,
903        }
904    }
905}
906
907impl hash::Hash for CodePoint {
908    #[inline]
909    fn hash<H: hash::Hasher>(&self, state: &mut H) {
910        self.value.hash(state)
911    }
912}
913
914impl hash::Hash for Wtf8Buf {
915    #[inline]
916    fn hash<H: hash::Hasher>(&self, state: &mut H) {
917        Wtf8::hash(self, state)
918    }
919}
920
921impl hash::Hash for Wtf8 {
922    #[inline]
923    fn hash<H: hash::Hasher>(&self, state: &mut H) {
924        state.write(&self.bytes);
925        0xfeu8.hash(state)
926    }
927}
928
929impl Borrow<Wtf8> for Wtf8Buf {
930    #[inline]
931    fn borrow(&self) -> &Wtf8 {
932        self
933    }
934}
935
936impl ToOwned for Wtf8 {
937    type Owned = Wtf8Buf;
938
939    #[inline]
940    fn to_owned(&self) -> Wtf8Buf {
941        Wtf8Buf {
942            bytes: self.bytes.to_vec(),
943        }
944    }
945}
946
947impl<'a> From<&'a Wtf8> for Cow<'a, Wtf8> {
948    #[inline]
949    fn from(s: &'a Wtf8) -> Cow<'a, Wtf8> {
950        Cow::Borrowed(s)
951    }
952}
953
954impl<'a> From<&'a str> for &'a Wtf8 {
955    #[inline]
956    fn from(s: &'a str) -> &'a Wtf8 {
957        Wtf8::from_str(s)
958    }
959}
960
961impl<'a> From<Wtf8Buf> for Cow<'a, Wtf8> {
962    #[inline]
963    fn from(s: Wtf8Buf) -> Cow<'a, Wtf8> {
964        Cow::Owned(s)
965    }
966}
967
968#[cfg(test)]
969mod tests {
970    use alloc::{format, vec};
971    use core::mem::transmute;
972
973    use super::*;
974
975    #[test]
976    fn code_point_from_u32() {
977        assert!(CodePoint::from_u32(0).is_some());
978        assert!(CodePoint::from_u32(0xd800).is_some());
979        assert!(CodePoint::from_u32(0x10ffff).is_some());
980        assert!(CodePoint::from_u32(0x110000).is_none());
981    }
982
983    #[test]
984    fn code_point_to_u32() {
985        fn c(value: u32) -> CodePoint {
986            CodePoint::from_u32(value).unwrap()
987        }
988        assert_eq!(c(0).to_u32(), 0);
989        assert_eq!(c(0xd800).to_u32(), 0xd800);
990        assert_eq!(c(0x10ffff).to_u32(), 0x10ffff);
991    }
992
993    #[test]
994    fn code_point_from_char() {
995        assert_eq!(CodePoint::from_char('a').to_u32(), 0x61);
996        assert_eq!(CodePoint::from_char('💩').to_u32(), 0x1f4a9);
997    }
998
999    #[test]
1000    fn code_point_to_string() {
1001        let cp_a = CodePoint::from_char('a');
1002        assert_eq!(format!("{cp_a:?}"), "U+0061");
1003        let cp_poop = CodePoint::from_char('💩');
1004        assert_eq!(format!("{cp_poop:?}"), "U+1F4A9");
1005    }
1006
1007    #[test]
1008    fn code_point_to_char() {
1009        fn c(value: u32) -> CodePoint {
1010            CodePoint::from_u32(value).unwrap()
1011        }
1012        assert_eq!(c(0x61).to_char(), Some('a'));
1013        assert_eq!(c(0x1f4a9).to_char(), Some('💩'));
1014        assert_eq!(c(0xd800).to_char(), None);
1015    }
1016
1017    #[test]
1018    fn code_point_to_char_lossy() {
1019        fn c(value: u32) -> CodePoint {
1020            CodePoint::from_u32(value).unwrap()
1021        }
1022        assert_eq!(c(0x61).to_char_lossy(), 'a');
1023        assert_eq!(c(0x1f4a9).to_char_lossy(), '💩');
1024        assert_eq!(c(0xd800).to_char_lossy(), '\u{FFFD}');
1025    }
1026
1027    #[test]
1028    fn wtf8buf_new() {
1029        assert_eq!(Wtf8Buf::new().bytes, b"");
1030    }
1031
1032    #[test]
1033    fn wtf8buf_from_str() {
1034        assert_eq!(Wtf8Buf::from_str("").bytes, b"");
1035        assert_eq!(
1036            Wtf8Buf::from_str("aé 💩").bytes,
1037            b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1038        );
1039    }
1040
1041    #[test]
1042    fn wtf8buf_from_string() {
1043        assert_eq!(Wtf8Buf::from_string(String::from("")).bytes, b"");
1044        assert_eq!(
1045            Wtf8Buf::from_string(String::from("aé 💩")).bytes,
1046            b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1047        );
1048    }
1049
1050    #[test]
1051    fn wtf8buf_from_ill_formed_utf16() {
1052        assert_eq!(Wtf8Buf::from_ill_formed_utf16(&[]).bytes, b"");
1053        assert_eq!(
1054            Wtf8Buf::from_ill_formed_utf16(&[0x61, 0xe9, 0x20, 0xd83d, 0xd83d, 0xdca9]).bytes,
1055            b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9"
1056        );
1057    }
1058
1059    #[test]
1060    fn wtf8buf_push_str() {
1061        let mut string = Wtf8Buf::new();
1062        assert_eq!(string.bytes, b"");
1063        string.push_str("aé 💩");
1064        assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1065    }
1066
1067    #[test]
1068    fn wtf8buf_push_char() {
1069        let mut string = Wtf8Buf::from_str("aé ");
1070        assert_eq!(string.bytes, b"a\xC3\xA9 ");
1071        string.push_char('💩');
1072        assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1073    }
1074
1075    #[test]
1076    fn wtf8buf_push_code_points_of_each_encoded_width() {
1077        fn code_point(value: u32) -> CodePoint {
1078            CodePoint::from_u32(value).unwrap()
1079        }
1080
1081        let mut string = Wtf8Buf::new();
1082
1083        string.push(code_point(0x7f));
1084        assert_eq!(string.bytes, b"\x7f");
1085
1086        string.push(code_point(0x80));
1087        assert_eq!(string.bytes, b"\x7f\xc2\x80");
1088
1089        string.push(code_point(0x800));
1090        assert_eq!(string.bytes, b"\x7f\xc2\x80\xe0\xa0\x80");
1091
1092        string.push(code_point(0xd800));
1093        assert_eq!(string.bytes, b"\x7f\xc2\x80\xe0\xa0\x80\xed\xa0\x80");
1094
1095        string.push(code_point(0x10000));
1096        assert_eq!(
1097            string.bytes,
1098            b"\x7f\xc2\x80\xe0\xa0\x80\xed\xa0\x80\xf0\x90\x80\x80"
1099        );
1100    }
1101
1102    #[test]
1103    fn wtf8buf_push() {
1104        let mut string = Wtf8Buf::from_str("aé ");
1105        assert_eq!(string.bytes, b"a\xC3\xA9 ");
1106        string.push(CodePoint::from_char('💩'));
1107        assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1108
1109        fn c(value: u32) -> CodePoint {
1110            CodePoint::from_u32(value).unwrap()
1111        }
1112
1113        let mut string = Wtf8Buf::new();
1114        string.push(c(0xd83d)); // lead
1115        string.push(c(0xdca9)); // trail
1116        assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1117
1118        let mut string = Wtf8Buf::new();
1119        string.push(c(0xd83d)); // lead
1120        string.push(c(0x20)); // not surrogate
1121        string.push(c(0xdca9)); // trail
1122        assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1123
1124        let mut string = Wtf8Buf::new();
1125        string.push(c(0xd800)); // lead
1126        string.push(c(0xdbff)); // lead
1127        assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1128
1129        let mut string = Wtf8Buf::new();
1130        string.push(c(0xd800)); // lead
1131        string.push(c(0xe000)); // not surrogate
1132        assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
1133
1134        let mut string = Wtf8Buf::new();
1135        string.push(c(0xd7ff)); // not surrogate
1136        string.push(c(0xdc00)); // trail
1137        assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1138
1139        let mut string = Wtf8Buf::new();
1140        string.push(c(0x61)); // not surrogate, < 3 bytes
1141        string.push(c(0xdc00)); // trail
1142        assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
1143
1144        let mut string = Wtf8Buf::new();
1145        string.push(c(0xdc00)); // trail
1146        assert_eq!(string.bytes, b"\xED\xB0\x80");
1147    }
1148
1149    #[test]
1150    fn wtf8buf_push_wtf8() {
1151        let mut string = Wtf8Buf::from_str("aé");
1152        assert_eq!(string.bytes, b"a\xC3\xA9");
1153        string.push_wtf8(Wtf8::from_str(" 💩"));
1154        assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1155
1156        fn w(value: &[u8]) -> &Wtf8 {
1157            unsafe { transmute(value) }
1158        }
1159
1160        let mut string = Wtf8Buf::new();
1161        string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
1162        string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
1163        assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1164
1165        let mut string = Wtf8Buf::new();
1166        string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
1167        string.push_wtf8(w(b" ")); // not surrogate
1168        string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
1169        assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1170
1171        let mut string = Wtf8Buf::new();
1172        string.push_wtf8(w(b"\xED\xA0\x80")); // lead
1173        string.push_wtf8(w(b"\xED\xAF\xBF")); // lead
1174        assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1175
1176        let mut string = Wtf8Buf::new();
1177        string.push_wtf8(w(b"\xED\xA0\x80")); // lead
1178        string.push_wtf8(w(b"\xEE\x80\x80")); // not surrogate
1179        assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
1180
1181        let mut string = Wtf8Buf::new();
1182        string.push_wtf8(w(b"\xED\x9F\xBF")); // not surrogate
1183        string.push_wtf8(w(b"\xED\xB0\x80")); // trail
1184        assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1185
1186        let mut string = Wtf8Buf::new();
1187        string.push_wtf8(w(b"a")); // not surrogate, < 3 bytes
1188        string.push_wtf8(w(b"\xED\xB0\x80")); // trail
1189        assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
1190
1191        let mut string = Wtf8Buf::new();
1192        string.push_wtf8(w(b"\xED\xB0\x80")); // trail
1193        assert_eq!(string.bytes, b"\xED\xB0\x80");
1194    }
1195
1196    #[test]
1197    fn wtf8buf_truncate() {
1198        let mut string = Wtf8Buf::from_str("aé");
1199        string.truncate(1);
1200        assert_eq!(string.bytes, b"a");
1201    }
1202
1203    #[test]
1204    #[should_panic]
1205    fn wtf8buf_truncate_fail_code_point_boundary() {
1206        let mut string = Wtf8Buf::from_str("aé");
1207        string.truncate(2);
1208    }
1209
1210    #[test]
1211    #[should_panic]
1212    fn wtf8buf_truncate_fail_longer() {
1213        let mut string = Wtf8Buf::from_str("aé");
1214        string.truncate(4);
1215    }
1216
1217    #[test]
1218    fn wtf8buf_into_string() {
1219        let mut string = Wtf8Buf::from_str("aé 💩");
1220        assert_eq!(string.clone().into_string(), Ok(String::from("aé 💩")));
1221        string.push(CodePoint::from_u32(0xd800).unwrap());
1222        assert_eq!(string.clone().into_string(), Err(string));
1223    }
1224
1225    #[test]
1226    fn wtf8buf_into_string_lossy() {
1227        let mut string = Wtf8Buf::from_str("aé 💩");
1228        assert_eq!(string.clone().into_string_lossy(), String::from("aé 💩"));
1229        string.push(CodePoint::from_u32(0xd800).unwrap());
1230        assert_eq!(string.clone().into_string_lossy(), String::from("aé 💩�"));
1231    }
1232
1233    #[test]
1234    fn wtf8buf_from_iterator() {
1235        fn f(values: &[u32]) -> Wtf8Buf {
1236            values
1237                .iter()
1238                .map(|&c| CodePoint::from_u32(c).unwrap())
1239                .collect::<Wtf8Buf>()
1240        }
1241        assert_eq!(
1242            f(&[0x61, 0xe9, 0x20, 0x1f4a9]).bytes,
1243            b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1244        );
1245
1246        assert_eq!(f(&[0xd83d, 0xdca9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1247        assert_eq!(
1248            f(&[0xd83d, 0x20, 0xdca9]).bytes,
1249            b"\xED\xA0\xBD \xED\xB2\xA9"
1250        );
1251        assert_eq!(f(&[0xd800, 0xdbff]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1252        assert_eq!(f(&[0xd800, 0xe000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1253        assert_eq!(f(&[0xd7ff, 0xdc00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1254        assert_eq!(f(&[0x61, 0xdc00]).bytes, b"\x61\xED\xB0\x80");
1255        assert_eq!(f(&[0xdc00]).bytes, b"\xED\xB0\x80");
1256    }
1257
1258    #[test]
1259    fn wtf8buf_extend() {
1260        fn e(initial: &[u32], extended: &[u32]) -> Wtf8Buf {
1261            fn c(value: &u32) -> CodePoint {
1262                CodePoint::from_u32(*value).unwrap()
1263            }
1264            let mut string = initial.iter().map(c).collect::<Wtf8Buf>();
1265            string.extend(extended.iter().map(c));
1266            string
1267        }
1268
1269        assert_eq!(
1270            e(&[0x61, 0xe9], &[0x20, 0x1f4a9]).bytes,
1271            b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1272        );
1273
1274        assert_eq!(e(&[0xd83d], &[0xdca9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1275        assert_eq!(
1276            e(&[0xd83d, 0x20], &[0xdca9]).bytes,
1277            b"\xED\xA0\xBD \xED\xB2\xA9"
1278        );
1279        assert_eq!(e(&[0xd800], &[0xdbff]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1280        assert_eq!(e(&[0xd800], &[0xe000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1281        assert_eq!(e(&[0xd7ff], &[0xdc00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1282        assert_eq!(e(&[0x61], &[0xdc00]).bytes, b"\x61\xED\xB0\x80");
1283        assert_eq!(e(&[], &[0xdc00]).bytes, b"\xED\xB0\x80");
1284    }
1285
1286    #[test]
1287    fn wtf8buf_debug() {
1288        let mut string = Wtf8Buf::from_str("aé 💩");
1289        string.push(CodePoint::from_u32(0xd800).unwrap());
1290        assert_eq!(format!("{string:?}"), r#""aé 💩\u{D800}""#);
1291    }
1292
1293    #[test]
1294    fn wtf8buf_as_slice() {
1295        assert_eq!(Wtf8Buf::from_str("aé"), Wtf8::from_str("aé"));
1296    }
1297
1298    #[test]
1299    fn wtf8_debug() {
1300        let mut string = Wtf8Buf::from_str("aé 💩");
1301        string.push(CodePoint::from_u32(0xd800).unwrap());
1302        let string_ref = &*string;
1303        assert_eq!(format!("{string_ref:?}"), r#""aé 💩\u{D800}""#);
1304    }
1305
1306    #[test]
1307    fn wtf8_from_str() {
1308        assert_eq!(&Wtf8::from_str("").bytes, b"");
1309        assert_eq!(
1310            &Wtf8::from_str("aé 💩").bytes,
1311            b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1312        );
1313    }
1314
1315    #[test]
1316    fn wtf8_as_bytes() {
1317        assert_eq!(Wtf8::from_str("").as_bytes(), b"");
1318        assert_eq!(
1319            Wtf8::from_str("aé 💩").as_bytes(),
1320            b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1321        );
1322    }
1323
1324    #[test]
1325    fn wtf8_starts_with() {
1326        assert!(Wtf8::from_str("aé 💩").starts_with("aé"));
1327        assert!(!Wtf8::from_str("aé 💩").starts_with("a💩"));
1328        assert!(!Wtf8::from_str("aé 💩").starts_with("aé 💩!"));
1329
1330        // The pattern length falls inside the first non-ASCII code point.
1331        assert!(!Wtf8::from_str("/example/path/to/日本語").starts_with("next/dist/compiled"));
1332    }
1333
1334    #[test]
1335    fn wtf8_from_bytes_unchecked() {
1336        assert_eq!(unsafe { &Wtf8::from_bytes_unchecked(b"").bytes }, b"");
1337        assert_eq!(
1338            unsafe { &Wtf8::from_bytes_unchecked(b"a\xC3\xA9 \xF0\x9F\x92\xA9").bytes },
1339            b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1340        );
1341        assert_eq!(
1342            unsafe { Wtf8::from_bytes_unchecked(b"a\xC3\xA9 \xF0\x9F\x92\xA9") },
1343            Wtf8::from_str("aé 💩")
1344        )
1345    }
1346
1347    #[test]
1348    fn wtf8_cow() {
1349        let s: Cow<Wtf8> = Cow::from(Wtf8::from_str("aé 💩"));
1350        assert!(matches!(s, Cow::Borrowed(_)));
1351        let owned: Wtf8Buf = s.into_owned();
1352        assert_eq!(owned, Wtf8Buf::from_str("aé 💩"));
1353    }
1354
1355    #[test]
1356    fn wtf8_len() {
1357        assert_eq!(Wtf8::from_str("").len(), 0);
1358        assert_eq!(Wtf8::from_str("aé 💩").len(), 8);
1359    }
1360
1361    #[test]
1362    fn wtf8_slice() {
1363        assert_eq!(&Wtf8::from_str("aé 💩").slice(1, 4).bytes, b"\xC3\xA9 ");
1364    }
1365
1366    #[test]
1367    #[should_panic]
1368    fn wtf8_slice_not_code_point_boundary() {
1369        Wtf8::from_str("aé 💩").slice(2, 4);
1370    }
1371
1372    #[test]
1373    fn wtf8_slice_from() {
1374        assert_eq!(
1375            &Wtf8::from_str("aé 💩").slice_from(1).bytes,
1376            b"\xC3\xA9 \xF0\x9F\x92\xA9"
1377        );
1378    }
1379
1380    #[test]
1381    #[should_panic]
1382    fn wtf8_slice_from_not_code_point_boundary() {
1383        Wtf8::from_str("aé 💩").slice_from(2);
1384    }
1385
1386    #[test]
1387    fn wtf8_slice_to() {
1388        assert_eq!(&Wtf8::from_str("aé 💩").slice_to(4).bytes, b"a\xC3\xA9 ");
1389    }
1390
1391    #[test]
1392    #[should_panic]
1393    fn wtf8_slice_to_not_code_point_boundary() {
1394        Wtf8::from_str("aé 💩").slice_from(5);
1395    }
1396
1397    #[test]
1398    fn wtf8_ascii_byte_at() {
1399        let slice = Wtf8::from_str("aé 💩");
1400        assert_eq!(slice.ascii_byte_at(0), b'a');
1401        assert_eq!(slice.ascii_byte_at(1), b'\xFF');
1402        assert_eq!(slice.ascii_byte_at(2), b'\xFF');
1403        assert_eq!(slice.ascii_byte_at(3), b' ');
1404        assert_eq!(slice.ascii_byte_at(4), b'\xFF');
1405    }
1406
1407    #[test]
1408    fn wtf8_code_points() {
1409        fn c(value: u32) -> CodePoint {
1410            CodePoint::from_u32(value).unwrap()
1411        }
1412        fn cp(string: &Wtf8Buf) -> Vec<Option<char>> {
1413            string
1414                .code_points()
1415                .map(|c| c.to_char())
1416                .collect::<Vec<_>>()
1417        }
1418        let mut string = Wtf8Buf::from_str("é ");
1419        assert_eq!(cp(&string), vec![Some('é'), Some(' ')]);
1420        string.push(c(0xd83d));
1421        assert_eq!(cp(&string), vec![Some('é'), Some(' '), None]);
1422        string.push(c(0xdca9));
1423        assert_eq!(cp(&string), vec![Some('é'), Some(' '), Some('💩')]);
1424    }
1425
1426    #[test]
1427    fn wtf8_as_str() {
1428        assert_eq!(Wtf8::from_str("").as_str(), Some(""));
1429        assert_eq!(Wtf8::from_str("aé 💩").as_str(), Some("aé 💩"));
1430        let mut string = Wtf8Buf::new();
1431        string.push(CodePoint::from_u32(0xd800).unwrap());
1432        assert_eq!(string.as_str(), None);
1433    }
1434
1435    #[test]
1436    fn wtf8_to_string_lossy() {
1437        assert_eq!(Wtf8::from_str("").to_string_lossy(), Cow::Borrowed(""));
1438        assert_eq!(
1439            Wtf8::from_str("aé 💩").to_string_lossy(),
1440            Cow::Borrowed("aé 💩")
1441        );
1442        let mut string = Wtf8Buf::from_str("aé 💩");
1443        string.push(CodePoint::from_u32(0xd800).unwrap());
1444        assert_eq!(string.to_string_lossy(), {
1445            let o: Cow<str> = Cow::Owned(String::from("aé 💩�"));
1446            o
1447        });
1448    }
1449
1450    #[test]
1451    fn wtf8_to_ill_formed_utf16() {
1452        let mut string = Wtf8Buf::from_str("aé ");
1453        string.push(CodePoint::from_u32(0xd83d).unwrap());
1454        string.push_char('💩');
1455        assert_eq!(
1456            string.to_ill_formed_utf16().collect::<Vec<_>>(),
1457            vec![0x61, 0xe9, 0x20, 0xd83d, 0xd83d, 0xdca9]
1458        );
1459    }
1460
1461    #[test]
1462    fn wtf8buf_wtf8_from_bytes_valid() {
1463        // Valid UTF-8
1464        assert!(Wtf8Buf::from_bytes(b"hello".to_vec()).is_ok());
1465        assert!(Wtf8Buf::from_bytes(b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec()).is_ok());
1466        assert!(Wtf8::from_bytes(b"hello").is_ok());
1467        assert!(Wtf8::from_bytes(b"a\xC3\xA9 \xF0\x9F\x92\xA9").is_ok());
1468
1469        // Valid WTF-8 with unpaired surrogates
1470        assert!(Wtf8Buf::from_bytes(b"\xED\xA0\x80".to_vec()).is_ok()); // lead surrogate
1471        assert!(Wtf8Buf::from_bytes(b"\xED\xB0\x80".to_vec()).is_ok()); // trail surrogate
1472        assert!(Wtf8Buf::from_bytes(b"a\xED\xA0\xBD".to_vec()).is_ok()); // text + lead
1473        assert!(Wtf8Buf::from_bytes(b"\xED\xB2\xA9z".to_vec()).is_ok()); // trail + text
1474        assert!(Wtf8Buf::from_bytes(b"\xED\xB2\xA9\xED\xA0\xBD".to_vec()).is_ok());
1475        // trail + lead
1476    }
1477
1478    #[test]
1479    fn wtf8buf_wtf8_from_bytes_invalid() {
1480        // Invalid: surrogate pair encoded as two 3-byte sequences
1481        assert!(Wtf8Buf::from_bytes(b"\xED\xA0\x80\xED\xB0\x80".to_vec()).is_err());
1482        assert!(Wtf8Buf::from_bytes(b"\xED\xA0\xBD\xED\xB2\xA9".to_vec()).is_err());
1483        assert!(Wtf8::from_bytes(b"\xED\xA0\x80\xED\xB0\x80").is_err());
1484        assert!(Wtf8::from_bytes(b"\xED\xA0\xBD\xED\xB2\xA9").is_err());
1485
1486        // Invalid UTF-8
1487        assert!(Wtf8Buf::from_bytes(vec![0xff]).is_err());
1488        assert!(Wtf8Buf::from_bytes(vec![0xc0, 0x80]).is_err()); // overlong
1489        assert!(Wtf8Buf::from_bytes(vec![0xed, 0xa0]).is_err()); // truncated lead surrogate
1490        assert!(Wtf8Buf::from_bytes(vec![0xf4, 0x90, 0x80, 0x80]).is_err()); // > U+10FFFF
1491
1492        // Verify we can recover the original bytes on failure
1493        let original = vec![0xff, 0xfe];
1494        let result = Wtf8Buf::from_bytes(original.clone());
1495        assert_eq!(result.unwrap_err(), original);
1496
1497        let result = Wtf8::from_bytes(&original);
1498        assert_eq!(result.unwrap_err(), original);
1499    }
1500}