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