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