Skip to main content

core/
wtf8.rs

1//! Implementation of [the WTF-8 encoding](https://wtf-8.codeberg.page/).
2//!
3//! This library uses Rust’s type system to maintain
4//! [well-formedness](https://wtf-8.codeberg.page/#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://wtf-8.codeberg.page/#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#![unstable(
14    feature = "wtf8_internals",
15    issue = "none",
16    reason = "this is internal code for representing OsStr on some platforms and not a public API"
17)]
18// rustdoc bug: doc(hidden) on the module won't stop types in the module from showing up in trait
19// implementations, so, we'll have to add more doc(hidden)s anyway
20#![doc(hidden)]
21
22use crate::char::{EscapeDebugExtArgs, encode_utf16_raw};
23use crate::clone::CloneToUninit;
24use crate::fmt::{self, Write};
25use crate::hash::{Hash, Hasher};
26use crate::iter::FusedIterator;
27use crate::num::niche_types::CodePointInner;
28use crate::str::next_code_point;
29use crate::{ops, slice, str};
30
31/// A Unicode code point: from U+0000 to U+10FFFF.
32///
33/// Compares with the `char` type,
34/// which represents a Unicode scalar value:
35/// a code point that is not a surrogate (U+D800 to U+DFFF).
36#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
37#[doc(hidden)]
38pub struct CodePoint(CodePointInner);
39
40/// Format the code point as `U+` followed by four to six hexadecimal digits.
41/// Example: `U+1F4A9`
42impl fmt::Debug for CodePoint {
43    #[inline]
44    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
45        write!(formatter, "U+{:04X}", self.0.as_inner())
46    }
47}
48
49impl CodePoint {
50    /// Unsafely creates a new `CodePoint` without checking the value.
51    ///
52    /// # Safety
53    ///
54    /// `value` must be less than or equal to 0x10FFFF.
55    #[inline]
56    pub unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
57        // SAFETY: Guaranteed by caller.
58        CodePoint(unsafe { CodePointInner::new_unchecked(value) })
59    }
60
61    /// Creates a new `CodePoint` if the value is a valid code point.
62    ///
63    /// Returns `None` if `value` is above 0x10FFFF.
64    #[inline]
65    pub fn from_u32(value: u32) -> Option<CodePoint> {
66        Some(CodePoint(CodePointInner::new(value)?))
67    }
68
69    /// Creates a new `CodePoint` from a `char`.
70    ///
71    /// Since all Unicode scalar values are code points, this always succeeds.
72    #[inline]
73    pub fn from_char(value: char) -> CodePoint {
74        // SAFETY: All char are valid for this type.
75        unsafe { CodePoint::from_u32_unchecked(value as u32) }
76    }
77
78    /// Returns the numeric value of the code point.
79    #[inline]
80    pub fn to_u32(&self) -> u32 {
81        self.0.as_inner()
82    }
83
84    /// Returns the numeric value of the code point if it is a leading surrogate.
85    #[inline]
86    pub fn to_lead_surrogate(&self) -> Option<u16> {
87        match self.to_u32() {
88            lead @ 0xD800..=0xDBFF => Some(lead as u16),
89            _ => None,
90        }
91    }
92
93    /// Returns the numeric value of the code point if it is a trailing surrogate.
94    #[inline]
95    pub fn to_trail_surrogate(&self) -> Option<u16> {
96        match self.to_u32() {
97            trail @ 0xDC00..=0xDFFF => Some(trail as u16),
98            _ => None,
99        }
100    }
101
102    /// Optionally returns a Unicode scalar value for the code point.
103    ///
104    /// Returns `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.to_u32() {
108            0xD800..=0xDFFF => None,
109            // SAFETY: We explicitly check that the char is valid.
110            valid => Some(unsafe { char::from_u32_unchecked(valid) }),
111        }
112    }
113
114    /// Returns a Unicode scalar value for the code point.
115    ///
116    /// Returns `'\u{FFFD}'` (the replacement character “�”)
117    /// if the code point is a surrogate (from U+D800 to U+DFFF).
118    #[inline]
119    pub fn to_char_lossy(&self) -> char {
120        self.to_char().unwrap_or(char::REPLACEMENT_CHARACTER)
121    }
122}
123
124/// A borrowed slice of well-formed WTF-8 data.
125///
126/// Similar to `&str`, but can additionally contain surrogate code points
127/// if they’re not in a surrogate pair.
128#[derive(Eq, Ord, PartialEq, PartialOrd)]
129#[repr(transparent)]
130#[rustc_has_incoherent_inherent_impls]
131#[doc(hidden)]
132pub struct Wtf8 {
133    bytes: [u8],
134}
135
136impl AsRef<[u8]> for Wtf8 {
137    #[inline]
138    fn as_ref(&self) -> &[u8] {
139        &self.bytes
140    }
141}
142
143/// Formats the string in double quotes, with characters escaped according to
144/// [`char::escape_debug`] and unpaired surrogates represented as `\u{xxxx}`,
145/// where each `x` is a hexadecimal digit.
146impl fmt::Debug for Wtf8 {
147    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
148        fn write_str_escaped(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
149            use crate::fmt::Write as _;
150            for c in s.chars().flat_map(|c| {
151                c.escape_debug_ext(EscapeDebugExtArgs {
152                    escape_grapheme_extender: true,
153                    escape_single_quote: false,
154                    escape_double_quote: true,
155                })
156            }) {
157                f.write_char(c)?
158            }
159            Ok(())
160        }
161
162        formatter.write_char('"')?;
163        let mut pos = 0;
164        while let Some((surrogate_pos, surrogate)) = self.next_surrogate(pos) {
165            // SAFETY: next_surrogate provides an index for a range of valid UTF-8 bytes.
166            write_str_escaped(formatter, unsafe {
167                str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos])
168            })?;
169            write!(formatter, "\\u{{{:x}}}", surrogate)?;
170            pos = surrogate_pos + 3;
171        }
172
173        // SAFETY: after next_surrogate returns None, the remainder is valid UTF-8.
174        write_str_escaped(formatter, unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?;
175        formatter.write_char('"')
176    }
177}
178
179/// Formats the string with unpaired surrogates substituted with the replacement
180/// character, U+FFFD.
181impl fmt::Display for Wtf8 {
182    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
183        let wtf8_bytes = &self.bytes;
184        let mut pos = 0;
185        loop {
186            match self.next_surrogate(pos) {
187                Some((surrogate_pos, _)) => {
188                    // SAFETY: next_surrogate provides an index for a range of valid UTF-8 bytes.
189                    formatter.write_str(unsafe {
190                        str::from_utf8_unchecked(&wtf8_bytes[pos..surrogate_pos])
191                    })?;
192                    formatter.write_char(char::REPLACEMENT_CHARACTER)?;
193                    pos = surrogate_pos + 3;
194                }
195                None => {
196                    // SAFETY: after next_surrogate returns None, the remainder is valid UTF-8.
197                    let s = unsafe { str::from_utf8_unchecked(&wtf8_bytes[pos..]) };
198                    if pos == 0 { return s.fmt(formatter) } else { return formatter.write_str(s) }
199                }
200            }
201        }
202    }
203}
204
205impl Wtf8 {
206    /// Creates a WTF-8 slice from a UTF-8 `&str` slice.
207    #[inline]
208    pub fn from_str(value: &str) -> &Wtf8 {
209        // SAFETY: Since WTF-8 is a superset of UTF-8, this always is valid.
210        unsafe { Wtf8::from_bytes_unchecked(value.as_bytes()) }
211    }
212
213    /// Creates a WTF-8 slice from a WTF-8 byte slice.
214    ///
215    /// # Safety
216    ///
217    /// `value` must contain well-formed WTF-8.
218    #[inline]
219    pub unsafe fn from_bytes_unchecked(value: &[u8]) -> &Wtf8 {
220        // SAFETY: start with &[u8], end with fancy &[u8]
221        unsafe { &*(value as *const [u8] as *const Wtf8) }
222    }
223
224    /// Creates a mutable WTF-8 slice from a mutable WTF-8 byte slice.
225    ///
226    /// # Safety
227    ///
228    /// `value` must contain well-formed WTF-8.
229    #[inline]
230    pub unsafe fn from_mut_bytes_unchecked(value: &mut [u8]) -> &mut Wtf8 {
231        // SAFETY: start with &mut [u8], end with fancy &mut [u8]
232        unsafe { &mut *(value as *mut [u8] as *mut Wtf8) }
233    }
234
235    /// Returns the length, in WTF-8 bytes.
236    #[inline]
237    pub fn len(&self) -> usize {
238        self.bytes.len()
239    }
240
241    #[inline]
242    pub fn is_empty(&self) -> bool {
243        self.bytes.is_empty()
244    }
245
246    /// Returns the code point at `position` if it is in the ASCII range,
247    /// or `b'\xFF'` otherwise.
248    ///
249    /// # Panics
250    ///
251    /// Panics if `position` is beyond the end of the string.
252    #[inline]
253    pub fn ascii_byte_at(&self, position: usize) -> u8 {
254        match self.bytes[position] {
255            ascii_byte @ 0x00..=0x7F => ascii_byte,
256            _ => 0xFF,
257        }
258    }
259
260    /// Returns an iterator for the string’s code points.
261    #[inline]
262    pub fn code_points(&self) -> Wtf8CodePoints<'_> {
263        Wtf8CodePoints { bytes: self.bytes.iter() }
264    }
265
266    /// Access raw bytes of WTF-8 data
267    #[inline]
268    pub fn as_bytes(&self) -> &[u8] {
269        &self.bytes
270    }
271
272    /// Tries to convert the string to UTF-8 and return a `&str` slice.
273    ///
274    /// Returns `None` if the string contains surrogates.
275    ///
276    /// This does not copy the data.
277    #[inline]
278    pub fn as_str(&self) -> Result<&str, str::Utf8Error> {
279        str::from_utf8(&self.bytes)
280    }
281
282    /// Converts the WTF-8 string to potentially ill-formed UTF-16
283    /// and return an iterator of 16-bit code units.
284    ///
285    /// This is lossless:
286    /// calling `Wtf8Buf::from_ill_formed_utf16` on the resulting code units
287    /// would always return the original WTF-8 string.
288    #[inline]
289    pub fn encode_wide(&self) -> EncodeWide<'_> {
290        EncodeWide { code_points: self.code_points(), extra: 0 }
291    }
292
293    #[inline]
294    pub fn next_surrogate(&self, mut pos: usize) -> Option<(usize, u16)> {
295        let mut iter = self.bytes[pos..].iter();
296        loop {
297            let b = *iter.next()?;
298            if b < 0x80 {
299                pos += 1;
300            } else if b < 0xE0 {
301                iter.next();
302                pos += 2;
303            } else if b == 0xED {
304                match (iter.next(), iter.next()) {
305                    (Some(&b2), Some(&b3)) if b2 >= 0xA0 => {
306                        return Some((pos, decode_surrogate(b2, b3)));
307                    }
308                    _ => pos += 3,
309                }
310            } else if b < 0xF0 {
311                iter.next();
312                iter.next();
313                pos += 3;
314            } else {
315                iter.next();
316                iter.next();
317                iter.next();
318                pos += 4;
319            }
320        }
321    }
322
323    #[inline]
324    pub fn final_lead_surrogate(&self) -> Option<u16> {
325        match self.bytes {
326            [.., 0xED, b2 @ 0xA0..=0xAF, b3] => Some(decode_surrogate(b2, b3)),
327            _ => None,
328        }
329    }
330
331    #[inline]
332    pub fn initial_trail_surrogate(&self) -> Option<u16> {
333        match self.bytes {
334            [0xED, b2 @ 0xB0..=0xBF, b3, ..] => Some(decode_surrogate(b2, b3)),
335            _ => None,
336        }
337    }
338
339    #[inline]
340    pub fn make_ascii_lowercase(&mut self) {
341        self.bytes.make_ascii_lowercase()
342    }
343
344    #[inline]
345    pub fn make_ascii_uppercase(&mut self) {
346        self.bytes.make_ascii_uppercase()
347    }
348
349    #[inline]
350    pub fn is_ascii(&self) -> bool {
351        self.bytes.is_ascii()
352    }
353
354    #[inline]
355    pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
356        self.bytes.eq_ignore_ascii_case(&other.bytes)
357    }
358}
359
360/// Returns a slice of the given string for the byte range \[`begin`..`end`).
361///
362/// # Panics
363///
364/// Panics when `begin` and `end` do not point to code point boundaries,
365/// or point beyond the end of the string.
366impl ops::Index<ops::Range<usize>> for Wtf8 {
367    type Output = Wtf8;
368
369    #[inline]
370    fn index(&self, range: ops::Range<usize>) -> &Wtf8 {
371        if range.start <= range.end
372            && self.is_code_point_boundary(range.start)
373            && self.is_code_point_boundary(range.end)
374        {
375            // SAFETY: is_code_point_boundary checks that the index is valid
376            unsafe { slice_unchecked(self, range.start, range.end) }
377        } else {
378            slice_error_fail(self, range.start, range.end)
379        }
380    }
381}
382
383/// Returns a slice of the given string from byte `begin` to its end.
384///
385/// # Panics
386///
387/// Panics when `begin` is not at a code point boundary,
388/// or is beyond the end of the string.
389impl ops::Index<ops::RangeFrom<usize>> for Wtf8 {
390    type Output = Wtf8;
391
392    #[inline]
393    fn index(&self, range: ops::RangeFrom<usize>) -> &Wtf8 {
394        if self.is_code_point_boundary(range.start) {
395            // SAFETY: is_code_point_boundary checks that the index is valid
396            unsafe { slice_unchecked(self, range.start, self.len()) }
397        } else {
398            slice_error_fail(self, range.start, self.len())
399        }
400    }
401}
402
403/// Returns a slice of the given string from its beginning to byte `end`.
404///
405/// # Panics
406///
407/// Panics when `end` is not at a code point boundary,
408/// or is beyond the end of the string.
409impl ops::Index<ops::RangeTo<usize>> for Wtf8 {
410    type Output = Wtf8;
411
412    #[inline]
413    fn index(&self, range: ops::RangeTo<usize>) -> &Wtf8 {
414        if self.is_code_point_boundary(range.end) {
415            // SAFETY: is_code_point_boundary checks that the index is valid
416            unsafe { slice_unchecked(self, 0, range.end) }
417        } else {
418            slice_error_fail(self, 0, range.end)
419        }
420    }
421}
422
423impl ops::Index<ops::RangeFull> for Wtf8 {
424    type Output = Wtf8;
425
426    #[inline]
427    fn index(&self, _range: ops::RangeFull) -> &Wtf8 {
428        self
429    }
430}
431
432#[inline]
433fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 {
434    // The first byte is assumed to be 0xED
435    0xD800 | (second_byte as u16 & 0x3F) << 6 | third_byte as u16 & 0x3F
436}
437
438impl Wtf8 {
439    /// Copied from str::is_char_boundary
440    #[inline]
441    pub fn is_code_point_boundary(&self, index: usize) -> bool {
442        if index == 0 {
443            return true;
444        }
445        match self.bytes.get(index) {
446            None => index == self.len(),
447            Some(&b) => (b as i8) >= -0x40,
448        }
449    }
450
451    /// Verify that `index` is at the edge of either a valid UTF-8 codepoint
452    /// (i.e. a codepoint that's not a surrogate) or of the whole string.
453    ///
454    /// These are the cases currently permitted by `OsStr::self_encoded_bytes`.
455    /// Splitting between surrogates is valid as far as WTF-8 is concerned, but
456    /// we do not permit it in the public API because WTF-8 is considered an
457    /// implementation detail.
458    #[track_caller]
459    #[inline]
460    pub fn check_utf8_boundary(&self, index: usize) {
461        let Err(err) = self.try_check_utf8_boundary(index) else { return };
462        match err {
463            Utf8BoundaryError::NotABoundary => {
464                panic!("byte index {index} is not a codepoint boundary")
465            }
466            Utf8BoundaryError::OutOfBounds => panic!("byte index {index} is out of bounds"),
467            Utf8BoundaryError::BetweenSurrogates => {
468                panic!("byte index {index} lies between surrogate codepoints")
469            }
470        }
471    }
472
473    #[track_caller]
474    #[inline]
475    pub fn try_check_utf8_boundary(&self, index: usize) -> Result<(), Utf8BoundaryError> {
476        if index == 0 {
477            return Ok(());
478        }
479        match self.bytes.get(index) {
480            Some(0xED) => (), // Might be a surrogate
481            Some(&b) if (b as i8) >= -0x40 => return Ok(()),
482            Some(_) => return Err(Utf8BoundaryError::NotABoundary),
483            None if index == self.len() => return Ok(()),
484            None => return Err(Utf8BoundaryError::OutOfBounds),
485        }
486        if self.bytes[index + 1] >= 0xA0 {
487            // There's a surrogate after index. Now check before index.
488            if index >= 3 && self.bytes[index - 3] == 0xED && self.bytes[index - 2] >= 0xA0 {
489                return Err(Utf8BoundaryError::BetweenSurrogates);
490            }
491        }
492        Ok(())
493    }
494}
495
496// This error type is only used temporarily to provide better panic messages
497// It does not implement Error.
498#[derive(Debug)]
499pub enum Utf8BoundaryError {
500    NotABoundary,
501    OutOfBounds,
502    BetweenSurrogates,
503}
504
505/// Copied from core::str::raw::slice_unchecked
506#[inline]
507unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 {
508    // SAFETY: memory layout of a &[u8] and &Wtf8 are the same
509    unsafe {
510        let len = end - begin;
511        let start = s.as_bytes().as_ptr().add(begin);
512        Wtf8::from_bytes_unchecked(slice::from_raw_parts(start, len))
513    }
514}
515
516#[inline(never)]
517fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! {
518    let len = s.len();
519    if begin > len {
520        panic!("start byte index {begin} is out of bounds for string of length {len}");
521    }
522    if end > len {
523        panic!("end byte index {end} is out of bounds for string of length {len}");
524    }
525    if begin > end {
526        panic!("byte range starts at {begin} but ends at {end}");
527    }
528    if !s.is_code_point_boundary(begin) {
529        panic!("byte index {begin} is not a code point boundary");
530    }
531    panic!("byte index {end} is not a code point boundary");
532}
533
534/// Iterator for the code points of a WTF-8 string.
535///
536/// Created with the method `.code_points()`.
537#[derive(Clone)]
538#[doc(hidden)]
539pub struct Wtf8CodePoints<'a> {
540    bytes: slice::Iter<'a, u8>,
541}
542
543impl Iterator for Wtf8CodePoints<'_> {
544    type Item = CodePoint;
545
546    #[inline]
547    fn next(&mut self) -> Option<CodePoint> {
548        // SAFETY: `self.bytes` has been created from a WTF-8 string
549        unsafe { next_code_point(&mut self.bytes).map(|c| CodePoint::from_u32_unchecked(c)) }
550    }
551
552    #[inline]
553    fn size_hint(&self) -> (usize, Option<usize>) {
554        let len = self.bytes.len();
555        (len.saturating_add(3) / 4, Some(len))
556    }
557}
558
559impl fmt::Debug for Wtf8CodePoints<'_> {
560    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561        f.debug_tuple("Wtf8CodePoints")
562            // SAFETY: We always leave the string in a valid state after each iteration.
563            .field(&unsafe { Wtf8::from_bytes_unchecked(self.bytes.as_slice()) })
564            .finish()
565    }
566}
567
568/// Generates a wide character sequence for potentially ill-formed UTF-16.
569#[stable(feature = "rust1", since = "1.0.0")]
570#[derive(Clone)]
571#[doc(hidden)]
572pub struct EncodeWide<'a> {
573    code_points: Wtf8CodePoints<'a>,
574    extra: u16,
575}
576
577// Copied from libunicode/u_str.rs
578#[stable(feature = "rust1", since = "1.0.0")]
579impl Iterator for EncodeWide<'_> {
580    type Item = u16;
581
582    #[inline]
583    fn next(&mut self) -> Option<u16> {
584        if self.extra != 0 {
585            let tmp = self.extra;
586            self.extra = 0;
587            return Some(tmp);
588        }
589
590        let mut buf = [0; char::MAX_LEN_UTF16];
591        self.code_points.next().map(|code_point| {
592            let n = encode_utf16_raw(code_point.to_u32(), &mut buf).len();
593            if n == 2 {
594                self.extra = buf[1];
595            }
596            buf[0]
597        })
598    }
599
600    #[inline]
601    fn size_hint(&self) -> (usize, Option<usize>) {
602        let (low, high) = self.code_points.size_hint();
603        let ext = (self.extra != 0) as usize;
604        // every code point gets either one u16 or two u16,
605        // so this iterator is between 1 or 2 times as
606        // long as the underlying iterator.
607        (low + ext, high.and_then(|n| n.checked_mul(2)).and_then(|n| n.checked_add(ext)))
608    }
609}
610
611#[stable(feature = "encode_wide_fused_iterator", since = "1.62.0")]
612impl FusedIterator for EncodeWide<'_> {}
613
614#[stable(feature = "encode_wide_debug", since = "1.92.0")]
615impl fmt::Debug for EncodeWide<'_> {
616    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
617        struct CodeUnit(u16);
618        impl fmt::Debug for CodeUnit {
619            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620                // This output attempts to balance readability with precision.
621                // Render characters which take only one WTF-16 code unit using
622                // `char` syntax and everything else as code units with hex
623                // integer syntax (including paired and unpaired surrogate
624                // halves). Since Rust has no `char`-like type for WTF-16, this
625                // isn't perfect, so if this output isn't suitable, it is open
626                // to being changed (see #140153).
627                match char::from_u32(self.0 as u32) {
628                    Some(c) => write!(f, "{c:?}"),
629                    None => write!(f, "0x{:04X}", self.0),
630                }
631            }
632        }
633
634        write!(f, "EncodeWide(")?;
635        f.debug_list().entries(self.clone().map(CodeUnit)).finish()?;
636        write!(f, ")")?;
637        Ok(())
638    }
639}
640
641impl Hash for CodePoint {
642    #[inline]
643    fn hash<H: Hasher>(&self, state: &mut H) {
644        self.0.hash(state)
645    }
646}
647
648impl Hash for Wtf8 {
649    #[inline]
650    fn hash<H: Hasher>(&self, state: &mut H) {
651        state.write(&self.bytes);
652        0xfeu8.hash(state)
653    }
654}
655
656#[unstable(feature = "clone_to_uninit", issue = "126799")]
657unsafe impl CloneToUninit for Wtf8 {
658    #[inline]
659    #[cfg_attr(debug_assertions, track_caller)]
660    unsafe fn clone_to_uninit(&self, dst: *mut u8) {
661        // SAFETY: we're just a transparent wrapper around [u8]
662        unsafe { self.bytes.clone_to_uninit(dst) }
663    }
664}