std/sys_common/
wtf8.rs

1//! Implementation of [the WTF-8 encoding](https://simonsapin.github.io/wtf-8/).
2//!
3//! This library uses Rust’s type system to maintain
4//! [well-formedness](https://simonsapin.github.io/wtf-8/#well-formed),
5//! like the `String` and `&str` types do for UTF-8.
6//!
7//! Since [WTF-8 must not be used
8//! for interchange](https://simonsapin.github.io/wtf-8/#intended-audience),
9//! this library deliberately does not provide access to the underlying bytes
10//! of WTF-8 strings,
11//! nor can it decode WTF-8 from arbitrary bytes.
12//! WTF-8 strings can be obtained from UTF-8, UTF-16, or code points.
13
14// this module is imported from @SimonSapin's repo and has tons of dead code on
15// unix (it's mostly used on windows), so don't worry about dead code here.
16#![allow(dead_code)]
17
18#[cfg(test)]
19mod tests;
20
21use core::char::{encode_utf8_raw, encode_utf16_raw};
22use core::clone::CloneToUninit;
23use core::str::next_code_point;
24
25use crate::borrow::Cow;
26use crate::collections::TryReserveError;
27use crate::hash::{Hash, Hasher};
28use crate::iter::FusedIterator;
29use crate::rc::Rc;
30use crate::sync::Arc;
31use crate::sys_common::AsInner;
32use crate::{fmt, mem, ops, slice, str};
33
34const UTF8_REPLACEMENT_CHARACTER: &str = "\u{FFFD}";
35
36/// A Unicode code point: from U+0000 to U+10FFFF.
37///
38/// Compares with the `char` type,
39/// which represents a Unicode scalar value:
40/// a code point that is not a surrogate (U+D800 to U+DFFF).
41#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
42pub struct CodePoint {
43    value: u32,
44}
45
46/// Format the code point as `U+` followed by four to six hexadecimal digits.
47/// Example: `U+1F4A9`
48impl fmt::Debug for CodePoint {
49    #[inline]
50    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
51        write!(formatter, "U+{:04X}", self.value)
52    }
53}
54
55impl CodePoint {
56    /// Unsafely creates a new `CodePoint` without checking the value.
57    ///
58    /// Only use when `value` is known to be less than or equal to 0x10FFFF.
59    #[inline]
60    pub unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
61        CodePoint { value }
62    }
63
64    /// Creates a new `CodePoint` if the value is a valid code point.
65    ///
66    /// Returns `None` if `value` is above 0x10FFFF.
67    #[inline]
68    pub fn from_u32(value: u32) -> Option<CodePoint> {
69        match value {
70            0..=0x10FFFF => Some(CodePoint { value }),
71            _ => None,
72        }
73    }
74
75    /// Creates a new `CodePoint` from a `char`.
76    ///
77    /// Since all Unicode scalar values are code points, this always succeeds.
78    #[inline]
79    pub fn from_char(value: char) -> CodePoint {
80        CodePoint { value: value as u32 }
81    }
82
83    /// Returns the numeric value of the code point.
84    #[inline]
85    pub fn to_u32(&self) -> u32 {
86        self.value
87    }
88
89    /// Returns the numeric value of the code point if it is a leading surrogate.
90    #[inline]
91    pub fn to_lead_surrogate(&self) -> Option<u16> {
92        match self.value {
93            lead @ 0xD800..=0xDBFF => Some(lead as u16),
94            _ => None,
95        }
96    }
97
98    /// Returns the numeric value of the code point if it is a trailing surrogate.
99    #[inline]
100    pub fn to_trail_surrogate(&self) -> Option<u16> {
101        match self.value {
102            trail @ 0xDC00..=0xDFFF => Some(trail as u16),
103            _ => None,
104        }
105    }
106
107    /// Optionally returns a Unicode scalar value for the code point.
108    ///
109    /// Returns `None` if the code point is a surrogate (from U+D800 to U+DFFF).
110    #[inline]
111    pub fn to_char(&self) -> Option<char> {
112        match self.value {
113            0xD800..=0xDFFF => None,
114            _ => Some(unsafe { char::from_u32_unchecked(self.value) }),
115        }
116    }
117
118    /// Returns a Unicode scalar value for the code point.
119    ///
120    /// Returns `'\u{FFFD}'` (the replacement character “�”)
121    /// if the code point is a surrogate (from U+D800 to U+DFFF).
122    #[inline]
123    pub fn to_char_lossy(&self) -> char {
124        self.to_char().unwrap_or('\u{FFFD}')
125    }
126}
127
128/// An owned, growable string of well-formed WTF-8 data.
129///
130/// Similar to `String`, but can additionally contain surrogate code points
131/// if they’re not in a surrogate pair.
132#[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
133pub struct Wtf8Buf {
134    bytes: Vec<u8>,
135
136    /// Do we know that `bytes` holds a valid UTF-8 encoding? We can easily
137    /// know this if we're constructed from a `String` or `&str`.
138    ///
139    /// It is possible for `bytes` to have valid UTF-8 without this being
140    /// set, such as when we're concatenating `&Wtf8`'s and surrogates become
141    /// paired, as we don't bother to rescan the entire string.
142    is_known_utf8: bool,
143}
144
145impl ops::Deref for Wtf8Buf {
146    type Target = Wtf8;
147
148    fn deref(&self) -> &Wtf8 {
149        self.as_slice()
150    }
151}
152
153impl ops::DerefMut for Wtf8Buf {
154    fn deref_mut(&mut self) -> &mut Wtf8 {
155        self.as_mut_slice()
156    }
157}
158
159/// Format the string with double quotes,
160/// and surrogates as `\u` followed by four hexadecimal digits.
161/// Example: `"a\u{D800}"` for a string with code points [U+0061, U+D800]
162impl fmt::Debug for Wtf8Buf {
163    #[inline]
164    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
165        fmt::Debug::fmt(&**self, formatter)
166    }
167}
168
169impl Wtf8Buf {
170    /// Creates a new, empty WTF-8 string.
171    #[inline]
172    pub fn new() -> Wtf8Buf {
173        Wtf8Buf { bytes: Vec::new(), is_known_utf8: true }
174    }
175
176    /// Creates a new, empty WTF-8 string with pre-allocated capacity for `capacity` bytes.
177    #[inline]
178    pub fn with_capacity(capacity: usize) -> Wtf8Buf {
179        Wtf8Buf { bytes: Vec::with_capacity(capacity), is_known_utf8: true }
180    }
181
182    /// Creates a WTF-8 string from a WTF-8 byte vec.
183    ///
184    /// Since the byte vec is not checked for valid WTF-8, this functions is
185    /// marked unsafe.
186    #[inline]
187    pub unsafe fn from_bytes_unchecked(value: Vec<u8>) -> Wtf8Buf {
188        Wtf8Buf { bytes: value, is_known_utf8: false }
189    }
190
191    /// Creates a WTF-8 string from a UTF-8 `String`.
192    ///
193    /// This takes ownership of the `String` and does not copy.
194    ///
195    /// Since WTF-8 is a superset of UTF-8, this always succeeds.
196    #[inline]
197    pub fn from_string(string: String) -> Wtf8Buf {
198        Wtf8Buf { bytes: string.into_bytes(), is_known_utf8: true }
199    }
200
201    /// Creates a WTF-8 string from a UTF-8 `&str` slice.
202    ///
203    /// This copies the content of the slice.
204    ///
205    /// Since WTF-8 is a superset of UTF-8, this always succeeds.
206    #[inline]
207    pub fn from_str(s: &str) -> Wtf8Buf {
208        Wtf8Buf { bytes: <[_]>::to_vec(s.as_bytes()), is_known_utf8: true }
209    }
210
211    pub fn clear(&mut self) {
212        self.bytes.clear();
213        self.is_known_utf8 = true;
214    }
215
216    /// Creates a WTF-8 string from a potentially ill-formed UTF-16 slice of 16-bit code units.
217    ///
218    /// This is lossless: calling `.encode_wide()` on the resulting string
219    /// will always return the original code units.
220    pub fn from_wide(v: &[u16]) -> Wtf8Buf {
221        let mut string = Wtf8Buf::with_capacity(v.len());
222        for item in char::decode_utf16(v.iter().cloned()) {
223            match item {
224                Ok(ch) => string.push_char(ch),
225                Err(surrogate) => {
226                    let surrogate = surrogate.unpaired_surrogate();
227                    // Surrogates are known to be in the code point range.
228                    let code_point = unsafe { CodePoint::from_u32_unchecked(surrogate as u32) };
229                    // The string will now contain an unpaired surrogate.
230                    string.is_known_utf8 = false;
231                    // Skip the WTF-8 concatenation check,
232                    // surrogate pairs are already decoded by decode_utf16
233                    string.push_code_point_unchecked(code_point);
234                }
235            }
236        }
237        string
238    }
239
240    /// Copied from String::push
241    /// This does **not** include the WTF-8 concatenation check or `is_known_utf8` check.
242    fn push_code_point_unchecked(&mut self, code_point: CodePoint) {
243        let mut bytes = [0; 4];
244        let bytes = encode_utf8_raw(code_point.value, &mut bytes);
245        self.bytes.extend_from_slice(bytes)
246    }
247
248    #[inline]
249    pub fn as_slice(&self) -> &Wtf8 {
250        unsafe { Wtf8::from_bytes_unchecked(&self.bytes) }
251    }
252
253    #[inline]
254    pub fn as_mut_slice(&mut self) -> &mut Wtf8 {
255        // Safety: `Wtf8` doesn't expose any way to mutate the bytes that would
256        // cause them to change from well-formed UTF-8 to ill-formed UTF-8,
257        // which would break the assumptions of the `is_known_utf8` field.
258        unsafe { Wtf8::from_mut_bytes_unchecked(&mut self.bytes) }
259    }
260
261    /// Reserves capacity for at least `additional` more bytes to be inserted
262    /// in the given `Wtf8Buf`.
263    /// The collection may reserve more space to avoid frequent reallocations.
264    ///
265    /// # Panics
266    ///
267    /// Panics if the new capacity overflows `usize`.
268    #[inline]
269    pub fn reserve(&mut self, additional: usize) {
270        self.bytes.reserve(additional)
271    }
272
273    /// Tries to reserve capacity for at least `additional` more length units
274    /// in the given `Wtf8Buf`. The `Wtf8Buf` may reserve more space to avoid
275    /// frequent reallocations. After calling `try_reserve`, capacity will be
276    /// greater than or equal to `self.len() + additional`. Does nothing if
277    /// capacity is already sufficient. This method preserves the contents even
278    /// if an error occurs.
279    ///
280    /// # Errors
281    ///
282    /// If the capacity overflows, or the allocator reports a failure, then an error
283    /// is returned.
284    #[inline]
285    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
286        self.bytes.try_reserve(additional)
287    }
288
289    #[inline]
290    pub fn reserve_exact(&mut self, additional: usize) {
291        self.bytes.reserve_exact(additional)
292    }
293
294    /// Tries to reserve the minimum capacity for exactly `additional`
295    /// length units in the given `Wtf8Buf`. After calling
296    /// `try_reserve_exact`, capacity will be greater than or equal to
297    /// `self.len() + additional` if it returns `Ok(())`.
298    /// Does nothing if the capacity is already sufficient.
299    ///
300    /// Note that the allocator may give the `Wtf8Buf` more space than it
301    /// requests. Therefore, capacity can not be relied upon to be precisely
302    /// minimal. Prefer [`try_reserve`] if future insertions are expected.
303    ///
304    /// [`try_reserve`]: Wtf8Buf::try_reserve
305    ///
306    /// # Errors
307    ///
308    /// If the capacity overflows, or the allocator reports a failure, then an error
309    /// is returned.
310    #[inline]
311    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
312        self.bytes.try_reserve_exact(additional)
313    }
314
315    #[inline]
316    pub fn shrink_to_fit(&mut self) {
317        self.bytes.shrink_to_fit()
318    }
319
320    #[inline]
321    pub fn shrink_to(&mut self, min_capacity: usize) {
322        self.bytes.shrink_to(min_capacity)
323    }
324
325    #[inline]
326    pub fn leak<'a>(self) -> &'a mut Wtf8 {
327        unsafe { Wtf8::from_mut_bytes_unchecked(self.bytes.leak()) }
328    }
329
330    /// Returns the number of bytes that this string buffer can hold without reallocating.
331    #[inline]
332    pub fn capacity(&self) -> usize {
333        self.bytes.capacity()
334    }
335
336    /// Append a UTF-8 slice at the end of the string.
337    #[inline]
338    pub fn push_str(&mut self, other: &str) {
339        self.bytes.extend_from_slice(other.as_bytes())
340    }
341
342    /// Append a WTF-8 slice at the end of the string.
343    ///
344    /// This replaces newly paired surrogates at the boundary
345    /// with a supplementary code point,
346    /// like concatenating ill-formed UTF-16 strings effectively would.
347    #[inline]
348    pub fn push_wtf8(&mut self, other: &Wtf8) {
349        match ((&*self).final_lead_surrogate(), other.initial_trail_surrogate()) {
350            // Replace newly paired surrogates by a supplementary code point.
351            (Some(lead), Some(trail)) => {
352                let len_without_lead_surrogate = self.len() - 3;
353                self.bytes.truncate(len_without_lead_surrogate);
354                let other_without_trail_surrogate = &other.bytes[3..];
355                // 4 bytes for the supplementary code point
356                self.bytes.reserve(4 + other_without_trail_surrogate.len());
357                self.push_char(decode_surrogate_pair(lead, trail));
358                self.bytes.extend_from_slice(other_without_trail_surrogate);
359            }
360            _ => {
361                // If we'll be pushing a string containing a surrogate, we may
362                // no longer have UTF-8.
363                if other.next_surrogate(0).is_some() {
364                    self.is_known_utf8 = false;
365                }
366
367                self.bytes.extend_from_slice(&other.bytes);
368            }
369        }
370    }
371
372    /// Append a Unicode scalar value at the end of the string.
373    #[inline]
374    pub fn push_char(&mut self, c: char) {
375        self.push_code_point_unchecked(CodePoint::from_char(c))
376    }
377
378    /// Append a code point at the end of the string.
379    ///
380    /// This replaces newly paired surrogates at the boundary
381    /// with a supplementary code point,
382    /// like concatenating ill-formed UTF-16 strings effectively would.
383    #[inline]
384    pub fn push(&mut self, code_point: CodePoint) {
385        if let Some(trail) = code_point.to_trail_surrogate() {
386            if let Some(lead) = (&*self).final_lead_surrogate() {
387                let len_without_lead_surrogate = self.len() - 3;
388                self.bytes.truncate(len_without_lead_surrogate);
389                self.push_char(decode_surrogate_pair(lead, trail));
390                return;
391            }
392
393            // We're pushing a trailing surrogate.
394            self.is_known_utf8 = false;
395        } else if code_point.to_lead_surrogate().is_some() {
396            // We're pushing a leading surrogate.
397            self.is_known_utf8 = false;
398        }
399
400        // No newly paired surrogates at the boundary.
401        self.push_code_point_unchecked(code_point)
402    }
403
404    /// Shortens a string to the specified length.
405    ///
406    /// # Panics
407    ///
408    /// Panics if `new_len` > current length,
409    /// or if `new_len` is not a code point boundary.
410    #[inline]
411    pub fn truncate(&mut self, new_len: usize) {
412        assert!(is_code_point_boundary(self, new_len));
413        self.bytes.truncate(new_len)
414    }
415
416    /// Consumes the WTF-8 string and tries to convert it to a vec of bytes.
417    #[inline]
418    pub fn into_bytes(self) -> Vec<u8> {
419        self.bytes
420    }
421
422    /// Consumes the WTF-8 string and tries to convert it to UTF-8.
423    ///
424    /// This does not copy the data.
425    ///
426    /// If the contents are not well-formed UTF-8
427    /// (that is, if the string contains surrogates),
428    /// the original WTF-8 string is returned instead.
429    pub fn into_string(self) -> Result<String, Wtf8Buf> {
430        if self.is_known_utf8 || self.next_surrogate(0).is_none() {
431            Ok(unsafe { String::from_utf8_unchecked(self.bytes) })
432        } else {
433            Err(self)
434        }
435    }
436
437    /// Consumes the WTF-8 string and converts it lossily to UTF-8.
438    ///
439    /// This does not copy the data (but may overwrite parts of it in place).
440    ///
441    /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”)
442    pub fn into_string_lossy(mut self) -> String {
443        // Fast path: If we already have UTF-8, we can return it immediately.
444        if self.is_known_utf8 {
445            return unsafe { String::from_utf8_unchecked(self.bytes) };
446        }
447
448        let mut pos = 0;
449        loop {
450            match self.next_surrogate(pos) {
451                Some((surrogate_pos, _)) => {
452                    pos = surrogate_pos + 3;
453                    self.bytes[surrogate_pos..pos]
454                        .copy_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
455                }
456                None => return unsafe { String::from_utf8_unchecked(self.bytes) },
457            }
458        }
459    }
460
461    /// Converts this `Wtf8Buf` into a boxed `Wtf8`.
462    #[inline]
463    pub fn into_box(self) -> Box<Wtf8> {
464        // SAFETY: relies on `Wtf8` being `repr(transparent)`.
465        unsafe { mem::transmute(self.bytes.into_boxed_slice()) }
466    }
467
468    /// Converts a `Box<Wtf8>` into a `Wtf8Buf`.
469    pub fn from_box(boxed: Box<Wtf8>) -> Wtf8Buf {
470        let bytes: Box<[u8]> = unsafe { mem::transmute(boxed) };
471        Wtf8Buf { bytes: bytes.into_vec(), is_known_utf8: false }
472    }
473
474    /// Provides plumbing to core `Vec::extend_from_slice`.
475    /// More well behaving alternative to allowing outer types
476    /// full mutable access to the core `Vec`.
477    #[inline]
478    pub(crate) fn extend_from_slice(&mut self, other: &[u8]) {
479        self.bytes.extend_from_slice(other);
480        self.is_known_utf8 = false;
481    }
482}
483
484/// Creates a new WTF-8 string from an iterator of code points.
485///
486/// This replaces surrogate code point pairs with supplementary code points,
487/// like concatenating ill-formed UTF-16 strings effectively would.
488impl FromIterator<CodePoint> for Wtf8Buf {
489    fn from_iter<T: IntoIterator<Item = CodePoint>>(iter: T) -> Wtf8Buf {
490        let mut string = Wtf8Buf::new();
491        string.extend(iter);
492        string
493    }
494}
495
496/// Append code points from an iterator to the string.
497///
498/// This replaces surrogate code point pairs with supplementary code points,
499/// like concatenating ill-formed UTF-16 strings effectively would.
500impl Extend<CodePoint> for Wtf8Buf {
501    fn extend<T: IntoIterator<Item = CodePoint>>(&mut self, iter: T) {
502        let iterator = iter.into_iter();
503        let (low, _high) = iterator.size_hint();
504        // Lower bound of one byte per code point (ASCII only)
505        self.bytes.reserve(low);
506        iterator.for_each(move |code_point| self.push(code_point));
507    }
508
509    #[inline]
510    fn extend_one(&mut self, code_point: CodePoint) {
511        self.push(code_point);
512    }
513
514    #[inline]
515    fn extend_reserve(&mut self, additional: usize) {
516        // Lower bound of one byte per code point (ASCII only)
517        self.bytes.reserve(additional);
518    }
519}
520
521/// A borrowed slice of well-formed WTF-8 data.
522///
523/// Similar to `&str`, but can additionally contain surrogate code points
524/// if they’re not in a surrogate pair.
525#[derive(Eq, Ord, PartialEq, PartialOrd)]
526#[repr(transparent)]
527pub struct Wtf8 {
528    bytes: [u8],
529}
530
531impl AsInner<[u8]> for Wtf8 {
532    #[inline]
533    fn as_inner(&self) -> &[u8] {
534        &self.bytes
535    }
536}
537
538/// Format the slice with double quotes,
539/// and surrogates as `\u` followed by four hexadecimal digits.
540/// Example: `"a\u{D800}"` for a slice with code points [U+0061, U+D800]
541impl fmt::Debug for Wtf8 {
542    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
543        fn write_str_escaped(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
544            use crate::fmt::Write;
545            for c in s.chars().flat_map(|c| c.escape_debug()) {
546                f.write_char(c)?
547            }
548            Ok(())
549        }
550
551        formatter.write_str("\"")?;
552        let mut pos = 0;
553        while let Some((surrogate_pos, surrogate)) = self.next_surrogate(pos) {
554            write_str_escaped(formatter, unsafe {
555                str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos])
556            })?;
557            write!(formatter, "\\u{{{:x}}}", surrogate)?;
558            pos = surrogate_pos + 3;
559        }
560        write_str_escaped(formatter, unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?;
561        formatter.write_str("\"")
562    }
563}
564
565impl fmt::Display for Wtf8 {
566    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
567        let wtf8_bytes = &self.bytes;
568        let mut pos = 0;
569        loop {
570            match self.next_surrogate(pos) {
571                Some((surrogate_pos, _)) => {
572                    formatter.write_str(unsafe {
573                        str::from_utf8_unchecked(&wtf8_bytes[pos..surrogate_pos])
574                    })?;
575                    formatter.write_str(UTF8_REPLACEMENT_CHARACTER)?;
576                    pos = surrogate_pos + 3;
577                }
578                None => {
579                    let s = unsafe { str::from_utf8_unchecked(&wtf8_bytes[pos..]) };
580                    if pos == 0 { return s.fmt(formatter) } else { return formatter.write_str(s) }
581                }
582            }
583        }
584    }
585}
586
587impl Wtf8 {
588    /// Creates a WTF-8 slice from a UTF-8 `&str` slice.
589    ///
590    /// Since WTF-8 is a superset of UTF-8, this always succeeds.
591    #[inline]
592    pub fn from_str(value: &str) -> &Wtf8 {
593        unsafe { Wtf8::from_bytes_unchecked(value.as_bytes()) }
594    }
595
596    /// Creates a WTF-8 slice from a WTF-8 byte slice.
597    ///
598    /// Since the byte slice is not checked for valid WTF-8, this functions is
599    /// marked unsafe.
600    #[inline]
601    pub unsafe fn from_bytes_unchecked(value: &[u8]) -> &Wtf8 {
602        // SAFETY: start with &[u8], end with fancy &[u8]
603        unsafe { &*(value as *const [u8] as *const Wtf8) }
604    }
605
606    /// Creates a mutable WTF-8 slice from a mutable WTF-8 byte slice.
607    ///
608    /// Since the byte slice is not checked for valid WTF-8, this functions is
609    /// marked unsafe.
610    #[inline]
611    unsafe fn from_mut_bytes_unchecked(value: &mut [u8]) -> &mut Wtf8 {
612        // SAFETY: start with &mut [u8], end with fancy &mut [u8]
613        unsafe { &mut *(value as *mut [u8] as *mut Wtf8) }
614    }
615
616    /// Returns the length, in WTF-8 bytes.
617    #[inline]
618    pub fn len(&self) -> usize {
619        self.bytes.len()
620    }
621
622    #[inline]
623    pub fn is_empty(&self) -> bool {
624        self.bytes.is_empty()
625    }
626
627    /// Returns the code point at `position` if it is in the ASCII range,
628    /// or `b'\xFF'` otherwise.
629    ///
630    /// # Panics
631    ///
632    /// Panics if `position` is beyond the end of the string.
633    #[inline]
634    pub fn ascii_byte_at(&self, position: usize) -> u8 {
635        match self.bytes[position] {
636            ascii_byte @ 0x00..=0x7F => ascii_byte,
637            _ => 0xFF,
638        }
639    }
640
641    /// Returns an iterator for the string’s code points.
642    #[inline]
643    pub fn code_points(&self) -> Wtf8CodePoints<'_> {
644        Wtf8CodePoints { bytes: self.bytes.iter() }
645    }
646
647    /// Access raw bytes of WTF-8 data
648    #[inline]
649    pub fn as_bytes(&self) -> &[u8] {
650        &self.bytes
651    }
652
653    /// Tries to convert the string to UTF-8 and return a `&str` slice.
654    ///
655    /// Returns `None` if the string contains surrogates.
656    ///
657    /// This does not copy the data.
658    #[inline]
659    pub fn as_str(&self) -> Result<&str, str::Utf8Error> {
660        str::from_utf8(&self.bytes)
661    }
662
663    /// Creates an owned `Wtf8Buf` from a borrowed `Wtf8`.
664    pub fn to_owned(&self) -> Wtf8Buf {
665        Wtf8Buf { bytes: self.bytes.to_vec(), is_known_utf8: false }
666    }
667
668    /// Lossily converts the string to UTF-8.
669    /// Returns a UTF-8 `&str` slice if the contents are well-formed in UTF-8.
670    ///
671    /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”).
672    ///
673    /// This only copies the data if necessary (if it contains any surrogate).
674    pub fn to_string_lossy(&self) -> Cow<'_, str> {
675        let surrogate_pos = match self.next_surrogate(0) {
676            None => return Cow::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) }),
677            Some((pos, _)) => pos,
678        };
679        let wtf8_bytes = &self.bytes;
680        let mut utf8_bytes = Vec::with_capacity(self.len());
681        utf8_bytes.extend_from_slice(&wtf8_bytes[..surrogate_pos]);
682        utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
683        let mut pos = surrogate_pos + 3;
684        loop {
685            match self.next_surrogate(pos) {
686                Some((surrogate_pos, _)) => {
687                    utf8_bytes.extend_from_slice(&wtf8_bytes[pos..surrogate_pos]);
688                    utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
689                    pos = surrogate_pos + 3;
690                }
691                None => {
692                    utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]);
693                    return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) });
694                }
695            }
696        }
697    }
698
699    /// Converts the WTF-8 string to potentially ill-formed UTF-16
700    /// and return an iterator of 16-bit code units.
701    ///
702    /// This is lossless:
703    /// calling `Wtf8Buf::from_ill_formed_utf16` on the resulting code units
704    /// would always return the original WTF-8 string.
705    #[inline]
706    pub fn encode_wide(&self) -> EncodeWide<'_> {
707        EncodeWide { code_points: self.code_points(), extra: 0 }
708    }
709
710    #[inline]
711    fn next_surrogate(&self, mut pos: usize) -> Option<(usize, u16)> {
712        let mut iter = self.bytes[pos..].iter();
713        loop {
714            let b = *iter.next()?;
715            if b < 0x80 {
716                pos += 1;
717            } else if b < 0xE0 {
718                iter.next();
719                pos += 2;
720            } else if b == 0xED {
721                match (iter.next(), iter.next()) {
722                    (Some(&b2), Some(&b3)) if b2 >= 0xA0 => {
723                        return Some((pos, decode_surrogate(b2, b3)));
724                    }
725                    _ => pos += 3,
726                }
727            } else if b < 0xF0 {
728                iter.next();
729                iter.next();
730                pos += 3;
731            } else {
732                iter.next();
733                iter.next();
734                iter.next();
735                pos += 4;
736            }
737        }
738    }
739
740    #[inline]
741    fn final_lead_surrogate(&self) -> Option<u16> {
742        match self.bytes {
743            [.., 0xED, b2 @ 0xA0..=0xAF, b3] => Some(decode_surrogate(b2, b3)),
744            _ => None,
745        }
746    }
747
748    #[inline]
749    fn initial_trail_surrogate(&self) -> Option<u16> {
750        match self.bytes {
751            [0xED, b2 @ 0xB0..=0xBF, b3, ..] => Some(decode_surrogate(b2, b3)),
752            _ => None,
753        }
754    }
755
756    pub fn clone_into(&self, buf: &mut Wtf8Buf) {
757        buf.is_known_utf8 = false;
758        self.bytes.clone_into(&mut buf.bytes);
759    }
760
761    /// Boxes this `Wtf8`.
762    #[inline]
763    pub fn into_box(&self) -> Box<Wtf8> {
764        let boxed: Box<[u8]> = self.bytes.into();
765        unsafe { mem::transmute(boxed) }
766    }
767
768    /// Creates a boxed, empty `Wtf8`.
769    pub fn empty_box() -> Box<Wtf8> {
770        let boxed: Box<[u8]> = Default::default();
771        unsafe { mem::transmute(boxed) }
772    }
773
774    #[inline]
775    pub fn into_arc(&self) -> Arc<Wtf8> {
776        let arc: Arc<[u8]> = Arc::from(&self.bytes);
777        unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Wtf8) }
778    }
779
780    #[inline]
781    pub fn into_rc(&self) -> Rc<Wtf8> {
782        let rc: Rc<[u8]> = Rc::from(&self.bytes);
783        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Wtf8) }
784    }
785
786    #[inline]
787    pub fn make_ascii_lowercase(&mut self) {
788        self.bytes.make_ascii_lowercase()
789    }
790
791    #[inline]
792    pub fn make_ascii_uppercase(&mut self) {
793        self.bytes.make_ascii_uppercase()
794    }
795
796    #[inline]
797    pub fn to_ascii_lowercase(&self) -> Wtf8Buf {
798        Wtf8Buf { bytes: self.bytes.to_ascii_lowercase(), is_known_utf8: false }
799    }
800
801    #[inline]
802    pub fn to_ascii_uppercase(&self) -> Wtf8Buf {
803        Wtf8Buf { bytes: self.bytes.to_ascii_uppercase(), is_known_utf8: false }
804    }
805
806    #[inline]
807    pub fn is_ascii(&self) -> bool {
808        self.bytes.is_ascii()
809    }
810
811    #[inline]
812    pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
813        self.bytes.eq_ignore_ascii_case(&other.bytes)
814    }
815}
816
817/// Returns a slice of the given string for the byte range \[`begin`..`end`).
818///
819/// # Panics
820///
821/// Panics when `begin` and `end` do not point to code point boundaries,
822/// or point beyond the end of the string.
823impl ops::Index<ops::Range<usize>> for Wtf8 {
824    type Output = Wtf8;
825
826    #[inline]
827    fn index(&self, range: ops::Range<usize>) -> &Wtf8 {
828        // is_code_point_boundary checks that the index is in [0, .len()]
829        if range.start <= range.end
830            && is_code_point_boundary(self, range.start)
831            && is_code_point_boundary(self, range.end)
832        {
833            unsafe { slice_unchecked(self, range.start, range.end) }
834        } else {
835            slice_error_fail(self, range.start, range.end)
836        }
837    }
838}
839
840/// Returns a slice of the given string from byte `begin` to its end.
841///
842/// # Panics
843///
844/// Panics when `begin` is not at a code point boundary,
845/// or is beyond the end of the string.
846impl ops::Index<ops::RangeFrom<usize>> for Wtf8 {
847    type Output = Wtf8;
848
849    #[inline]
850    fn index(&self, range: ops::RangeFrom<usize>) -> &Wtf8 {
851        // is_code_point_boundary checks that the index is in [0, .len()]
852        if is_code_point_boundary(self, range.start) {
853            unsafe { slice_unchecked(self, range.start, self.len()) }
854        } else {
855            slice_error_fail(self, range.start, self.len())
856        }
857    }
858}
859
860/// Returns a slice of the given string from its beginning to byte `end`.
861///
862/// # Panics
863///
864/// Panics when `end` is not at a code point boundary,
865/// or is beyond the end of the string.
866impl ops::Index<ops::RangeTo<usize>> for Wtf8 {
867    type Output = Wtf8;
868
869    #[inline]
870    fn index(&self, range: ops::RangeTo<usize>) -> &Wtf8 {
871        // is_code_point_boundary checks that the index is in [0, .len()]
872        if is_code_point_boundary(self, range.end) {
873            unsafe { slice_unchecked(self, 0, range.end) }
874        } else {
875            slice_error_fail(self, 0, range.end)
876        }
877    }
878}
879
880impl ops::Index<ops::RangeFull> for Wtf8 {
881    type Output = Wtf8;
882
883    #[inline]
884    fn index(&self, _range: ops::RangeFull) -> &Wtf8 {
885        self
886    }
887}
888
889#[inline]
890fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 {
891    // The first byte is assumed to be 0xED
892    0xD800 | (second_byte as u16 & 0x3F) << 6 | third_byte as u16 & 0x3F
893}
894
895#[inline]
896fn decode_surrogate_pair(lead: u16, trail: u16) -> char {
897    let code_point = 0x10000 + ((((lead - 0xD800) as u32) << 10) | (trail - 0xDC00) as u32);
898    unsafe { char::from_u32_unchecked(code_point) }
899}
900
901/// Copied from str::is_char_boundary
902#[inline]
903pub fn is_code_point_boundary(slice: &Wtf8, index: usize) -> bool {
904    if index == 0 {
905        return true;
906    }
907    match slice.bytes.get(index) {
908        None => index == slice.len(),
909        Some(&b) => (b as i8) >= -0x40,
910    }
911}
912
913/// Verify that `index` is at the edge of either a valid UTF-8 codepoint
914/// (i.e. a codepoint that's not a surrogate) or of the whole string.
915///
916/// These are the cases currently permitted by `OsStr::slice_encoded_bytes`.
917/// Splitting between surrogates is valid as far as WTF-8 is concerned, but
918/// we do not permit it in the public API because WTF-8 is considered an
919/// implementation detail.
920#[track_caller]
921#[inline]
922pub fn check_utf8_boundary(slice: &Wtf8, index: usize) {
923    if index == 0 {
924        return;
925    }
926    match slice.bytes.get(index) {
927        Some(0xED) => (), // Might be a surrogate
928        Some(&b) if (b as i8) >= -0x40 => return,
929        Some(_) => panic!("byte index {index} is not a codepoint boundary"),
930        None if index == slice.len() => return,
931        None => panic!("byte index {index} is out of bounds"),
932    }
933    if slice.bytes[index + 1] >= 0xA0 {
934        // There's a surrogate after index. Now check before index.
935        if index >= 3 && slice.bytes[index - 3] == 0xED && slice.bytes[index - 2] >= 0xA0 {
936            panic!("byte index {index} lies between surrogate codepoints");
937        }
938    }
939}
940
941/// Copied from core::str::raw::slice_unchecked
942#[inline]
943pub unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 {
944    // SAFETY: memory layout of a &[u8] and &Wtf8 are the same
945    unsafe {
946        let len = end - begin;
947        let start = s.as_bytes().as_ptr().add(begin);
948        Wtf8::from_bytes_unchecked(slice::from_raw_parts(start, len))
949    }
950}
951
952/// Copied from core::str::raw::slice_error_fail
953#[inline(never)]
954pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! {
955    assert!(begin <= end);
956    panic!("index {begin} and/or {end} in `{s:?}` do not lie on character boundary");
957}
958
959/// Iterator for the code points of a WTF-8 string.
960///
961/// Created with the method `.code_points()`.
962#[derive(Clone)]
963pub struct Wtf8CodePoints<'a> {
964    bytes: slice::Iter<'a, u8>,
965}
966
967impl<'a> Iterator for Wtf8CodePoints<'a> {
968    type Item = CodePoint;
969
970    #[inline]
971    fn next(&mut self) -> Option<CodePoint> {
972        // SAFETY: `self.bytes` has been created from a WTF-8 string
973        unsafe { next_code_point(&mut self.bytes).map(|c| CodePoint { value: c }) }
974    }
975
976    #[inline]
977    fn size_hint(&self) -> (usize, Option<usize>) {
978        let len = self.bytes.len();
979        (len.saturating_add(3) / 4, Some(len))
980    }
981}
982
983/// Generates a wide character sequence for potentially ill-formed UTF-16.
984#[stable(feature = "rust1", since = "1.0.0")]
985#[derive(Clone)]
986pub struct EncodeWide<'a> {
987    code_points: Wtf8CodePoints<'a>,
988    extra: u16,
989}
990
991// Copied from libunicode/u_str.rs
992#[stable(feature = "rust1", since = "1.0.0")]
993impl<'a> Iterator for EncodeWide<'a> {
994    type Item = u16;
995
996    #[inline]
997    fn next(&mut self) -> Option<u16> {
998        if self.extra != 0 {
999            let tmp = self.extra;
1000            self.extra = 0;
1001            return Some(tmp);
1002        }
1003
1004        let mut buf = [0; 2];
1005        self.code_points.next().map(|code_point| {
1006            let n = encode_utf16_raw(code_point.value, &mut buf).len();
1007            if n == 2 {
1008                self.extra = buf[1];
1009            }
1010            buf[0]
1011        })
1012    }
1013
1014    #[inline]
1015    fn size_hint(&self) -> (usize, Option<usize>) {
1016        let (low, high) = self.code_points.size_hint();
1017        let ext = (self.extra != 0) as usize;
1018        // every code point gets either one u16 or two u16,
1019        // so this iterator is between 1 or 2 times as
1020        // long as the underlying iterator.
1021        (low + ext, high.and_then(|n| n.checked_mul(2)).and_then(|n| n.checked_add(ext)))
1022    }
1023}
1024
1025#[stable(feature = "encode_wide_fused_iterator", since = "1.62.0")]
1026impl FusedIterator for EncodeWide<'_> {}
1027
1028impl Hash for CodePoint {
1029    #[inline]
1030    fn hash<H: Hasher>(&self, state: &mut H) {
1031        self.value.hash(state)
1032    }
1033}
1034
1035impl Hash for Wtf8Buf {
1036    #[inline]
1037    fn hash<H: Hasher>(&self, state: &mut H) {
1038        state.write(&self.bytes);
1039        0xfeu8.hash(state)
1040    }
1041}
1042
1043impl Hash for Wtf8 {
1044    #[inline]
1045    fn hash<H: Hasher>(&self, state: &mut H) {
1046        state.write(&self.bytes);
1047        0xfeu8.hash(state)
1048    }
1049}
1050
1051#[unstable(feature = "clone_to_uninit", issue = "126799")]
1052unsafe impl CloneToUninit for Wtf8 {
1053    #[inline]
1054    #[cfg_attr(debug_assertions, track_caller)]
1055    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
1056        // SAFETY: we're just a transparent wrapper around [u8]
1057        unsafe { self.bytes.clone_to_uninit(dst) }
1058    }
1059}