1 //! Implementation of [the WTF-8 encoding](https://simonsapin.github.io/wtf-8/).
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.
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
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.
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.
18 use core::str::next_code_point;
20 use crate::borrow::Cow;
23 use crate::hash::{Hash, Hasher};
24 use crate::iter::FromIterator;
31 use crate::sys_common::AsInner;
33 const UTF8_REPLACEMENT_CHARACTER: &str = "\u{FFFD}";
35 /// A Unicode code point: from U+0000 to U+10FFFF.
37 /// Compares with the `char` type,
38 /// which represents a Unicode scalar value:
39 /// a code point that is not a surrogate (U+D800 to U+DFFF).
40 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
41 pub struct CodePoint {
45 /// Format the code point as `U+` followed by four to six hexadecimal digits.
46 /// Example: `U+1F4A9`
47 impl fmt::Debug for CodePoint {
49 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
50 write!(formatter, "U+{:04X}", self.value)
55 /// Unsafely creates a new `CodePoint` without checking the value.
57 /// Only use when `value` is known to be less than or equal to 0x10FFFF.
59 pub unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
63 /// Creates a new `CodePoint` if the value is a valid code point.
65 /// Returns `None` if `value` is above 0x10FFFF.
67 pub fn from_u32(value: u32) -> Option<CodePoint> {
69 0..=0x10FFFF => Some(CodePoint { value }),
74 /// Creates a new `CodePoint` from a `char`.
76 /// Since all Unicode scalar values are code points, this always succeeds.
78 pub fn from_char(value: char) -> CodePoint {
79 CodePoint { value: value as u32 }
82 /// Returns the numeric value of the code point.
84 pub fn to_u32(&self) -> u32 {
88 /// Optionally returns a Unicode scalar value for the code point.
90 /// Returns `None` if the code point is a surrogate (from U+D800 to U+DFFF).
92 pub fn to_char(&self) -> Option<char> {
94 0xD800..=0xDFFF => None,
95 _ => Some(unsafe { char::from_u32_unchecked(self.value) }),
99 /// Returns a Unicode scalar value for the code point.
101 /// Returns `'\u{FFFD}'` (the replacement character “�”)
102 /// if the code point is a surrogate (from U+D800 to U+DFFF).
104 pub fn to_char_lossy(&self) -> char {
105 self.to_char().unwrap_or('\u{FFFD}')
109 /// An owned, growable string of well-formed WTF-8 data.
111 /// Similar to `String`, but can additionally contain surrogate code points
112 /// if they’re not in a surrogate pair.
113 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
118 impl ops::Deref for Wtf8Buf {
121 fn deref(&self) -> &Wtf8 {
126 impl ops::DerefMut for Wtf8Buf {
127 fn deref_mut(&mut self) -> &mut Wtf8 {
132 /// Format the string with double quotes,
133 /// and surrogates as `\u` followed by four hexadecimal digits.
134 /// Example: `"a\u{D800}"` for a string with code points [U+0061, U+D800]
135 impl fmt::Debug for Wtf8Buf {
137 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
138 fmt::Debug::fmt(&**self, formatter)
143 /// Creates a new, empty WTF-8 string.
145 pub fn new() -> Wtf8Buf {
146 Wtf8Buf { bytes: Vec::new() }
149 /// Creates a new, empty WTF-8 string with pre-allocated capacity for `capacity` bytes.
151 pub fn with_capacity(capacity: usize) -> Wtf8Buf {
152 Wtf8Buf { bytes: Vec::with_capacity(capacity) }
155 /// Creates a WTF-8 string from a UTF-8 `String`.
157 /// This takes ownership of the `String` and does not copy.
159 /// Since WTF-8 is a superset of UTF-8, this always succeeds.
161 pub fn from_string(string: String) -> Wtf8Buf {
162 Wtf8Buf { bytes: string.into_bytes() }
165 /// Creates a WTF-8 string from a UTF-8 `&str` slice.
167 /// This copies the content of the slice.
169 /// Since WTF-8 is a superset of UTF-8, this always succeeds.
171 pub fn from_str(str: &str) -> Wtf8Buf {
172 Wtf8Buf { bytes: <[_]>::to_vec(str.as_bytes()) }
175 pub fn clear(&mut self) {
179 /// Creates a WTF-8 string from a potentially ill-formed UTF-16 slice of 16-bit code units.
181 /// This is lossless: calling `.encode_wide()` on the resulting string
182 /// will always return the original code units.
183 pub fn from_wide(v: &[u16]) -> Wtf8Buf {
184 let mut string = Wtf8Buf::with_capacity(v.len());
185 for item in char::decode_utf16(v.iter().cloned()) {
187 Ok(ch) => string.push_char(ch),
189 let surrogate = surrogate.unpaired_surrogate();
190 // Surrogates are known to be in the code point range.
191 let code_point = unsafe { CodePoint::from_u32_unchecked(surrogate as u32) };
192 // Skip the WTF-8 concatenation check,
193 // surrogate pairs are already decoded by decode_utf16
194 string.push_code_point_unchecked(code_point)
201 /// Copied from String::push
202 /// This does **not** include the WTF-8 concatenation check.
203 fn push_code_point_unchecked(&mut self, code_point: CodePoint) {
204 let c = unsafe { char::from_u32_unchecked(code_point.value) };
205 let mut bytes = [0; 4];
206 let bytes = c.encode_utf8(&mut bytes).as_bytes();
207 self.bytes.extend_from_slice(bytes)
211 pub fn as_slice(&self) -> &Wtf8 {
212 unsafe { Wtf8::from_bytes_unchecked(&self.bytes) }
216 pub fn as_mut_slice(&mut self) -> &mut Wtf8 {
217 unsafe { Wtf8::from_mut_bytes_unchecked(&mut self.bytes) }
220 /// Reserves capacity for at least `additional` more bytes to be inserted
221 /// in the given `Wtf8Buf`.
222 /// The collection may reserve more space to avoid frequent reallocations.
226 /// Panics if the new capacity overflows `usize`.
228 pub fn reserve(&mut self, additional: usize) {
229 self.bytes.reserve(additional)
233 pub fn reserve_exact(&mut self, additional: usize) {
234 self.bytes.reserve_exact(additional)
238 pub fn shrink_to_fit(&mut self) {
239 self.bytes.shrink_to_fit()
243 pub fn shrink_to(&mut self, min_capacity: usize) {
244 self.bytes.shrink_to(min_capacity)
247 /// Returns the number of bytes that this string buffer can hold without reallocating.
249 pub fn capacity(&self) -> usize {
250 self.bytes.capacity()
253 /// Append a UTF-8 slice at the end of the string.
255 pub fn push_str(&mut self, other: &str) {
256 self.bytes.extend_from_slice(other.as_bytes())
259 /// Append a WTF-8 slice at the end of the string.
261 /// This replaces newly paired surrogates at the boundary
262 /// with a supplementary code point,
263 /// like concatenating ill-formed UTF-16 strings effectively would.
265 pub fn push_wtf8(&mut self, other: &Wtf8) {
266 match ((&*self).final_lead_surrogate(), other.initial_trail_surrogate()) {
267 // Replace newly paired surrogates by a supplementary code point.
268 (Some(lead), Some(trail)) => {
269 let len_without_lead_surrogate = self.len() - 3;
270 self.bytes.truncate(len_without_lead_surrogate);
271 let other_without_trail_surrogate = &other.bytes[3..];
272 // 4 bytes for the supplementary code point
273 self.bytes.reserve(4 + other_without_trail_surrogate.len());
274 self.push_char(decode_surrogate_pair(lead, trail));
275 self.bytes.extend_from_slice(other_without_trail_surrogate);
277 _ => self.bytes.extend_from_slice(&other.bytes),
281 /// Append a Unicode scalar value at the end of the string.
283 pub fn push_char(&mut self, c: char) {
284 self.push_code_point_unchecked(CodePoint::from_char(c))
287 /// Append a code point at the end of the string.
289 /// This replaces newly paired surrogates at the boundary
290 /// with a supplementary code point,
291 /// like concatenating ill-formed UTF-16 strings effectively would.
293 pub fn push(&mut self, code_point: CodePoint) {
294 if let trail @ 0xDC00..=0xDFFF = code_point.to_u32() {
295 if let Some(lead) = (&*self).final_lead_surrogate() {
296 let len_without_lead_surrogate = self.len() - 3;
297 self.bytes.truncate(len_without_lead_surrogate);
298 self.push_char(decode_surrogate_pair(lead, trail as u16));
303 // No newly paired surrogates at the boundary.
304 self.push_code_point_unchecked(code_point)
307 /// Shortens a string to the specified length.
311 /// Panics if `new_len` > current length,
312 /// or if `new_len` is not a code point boundary.
314 pub fn truncate(&mut self, new_len: usize) {
315 assert!(is_code_point_boundary(self, new_len));
316 self.bytes.truncate(new_len)
319 /// Consumes the WTF-8 string and tries to convert it to UTF-8.
321 /// This does not copy the data.
323 /// If the contents are not well-formed UTF-8
324 /// (that is, if the string contains surrogates),
325 /// the original WTF-8 string is returned instead.
326 pub fn into_string(self) -> Result<String, Wtf8Buf> {
327 match self.next_surrogate(0) {
328 None => Ok(unsafe { String::from_utf8_unchecked(self.bytes) }),
329 Some(_) => Err(self),
333 /// Consumes the WTF-8 string and converts it lossily to UTF-8.
335 /// This does not copy the data (but may overwrite parts of it in place).
337 /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”)
338 pub fn into_string_lossy(mut self) -> String {
341 match self.next_surrogate(pos) {
342 Some((surrogate_pos, _)) => {
343 pos = surrogate_pos + 3;
344 self.bytes[surrogate_pos..pos]
345 .copy_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
347 None => return unsafe { String::from_utf8_unchecked(self.bytes) },
352 /// Converts this `Wtf8Buf` into a boxed `Wtf8`.
354 pub fn into_box(self) -> Box<Wtf8> {
355 unsafe { mem::transmute(self.bytes.into_boxed_slice()) }
358 /// Converts a `Box<Wtf8>` into a `Wtf8Buf`.
359 pub fn from_box(boxed: Box<Wtf8>) -> Wtf8Buf {
360 let bytes: Box<[u8]> = unsafe { mem::transmute(boxed) };
361 Wtf8Buf { bytes: bytes.into_vec() }
365 /// Creates a new WTF-8 string from an iterator of code points.
367 /// This replaces surrogate code point pairs with supplementary code points,
368 /// like concatenating ill-formed UTF-16 strings effectively would.
369 impl FromIterator<CodePoint> for Wtf8Buf {
370 fn from_iter<T: IntoIterator<Item = CodePoint>>(iter: T) -> Wtf8Buf {
371 let mut string = Wtf8Buf::new();
377 /// Append code points from an iterator to the string.
379 /// This replaces surrogate code point pairs with supplementary code points,
380 /// like concatenating ill-formed UTF-16 strings effectively would.
381 impl Extend<CodePoint> for Wtf8Buf {
382 fn extend<T: IntoIterator<Item = CodePoint>>(&mut self, iter: T) {
383 let iterator = iter.into_iter();
384 let (low, _high) = iterator.size_hint();
385 // Lower bound of one byte per code point (ASCII only)
386 self.bytes.reserve(low);
387 iterator.for_each(move |code_point| self.push(code_point));
391 /// A borrowed slice of well-formed WTF-8 data.
393 /// Similar to `&str`, but can additionally contain surrogate code points
394 /// if they’re not in a surrogate pair.
395 #[derive(Eq, Ord, PartialEq, PartialOrd)]
400 impl AsInner<[u8]> for Wtf8 {
401 fn as_inner(&self) -> &[u8] {
406 /// Format the slice with double quotes,
407 /// and surrogates as `\u` followed by four hexadecimal digits.
408 /// Example: `"a\u{D800}"` for a slice with code points [U+0061, U+D800]
409 impl fmt::Debug for Wtf8 {
410 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
411 fn write_str_escaped(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
412 use crate::fmt::Write;
413 for c in s.chars().flat_map(|c| c.escape_debug()) {
419 formatter.write_str("\"")?;
421 while let Some((surrogate_pos, surrogate)) = self.next_surrogate(pos) {
422 write_str_escaped(formatter, unsafe {
423 str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos])
425 write!(formatter, "\\u{{{:x}}}", surrogate)?;
426 pos = surrogate_pos + 3;
428 write_str_escaped(formatter, unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?;
429 formatter.write_str("\"")
433 impl fmt::Display for Wtf8 {
434 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
435 let wtf8_bytes = &self.bytes;
438 match self.next_surrogate(pos) {
439 Some((surrogate_pos, _)) => {
440 formatter.write_str(unsafe {
441 str::from_utf8_unchecked(&wtf8_bytes[pos..surrogate_pos])
443 formatter.write_str(UTF8_REPLACEMENT_CHARACTER)?;
444 pos = surrogate_pos + 3;
447 let s = unsafe { str::from_utf8_unchecked(&wtf8_bytes[pos..]) };
448 if pos == 0 { return s.fmt(formatter) } else { return formatter.write_str(s) }
456 /// Creates a WTF-8 slice from a UTF-8 `&str` slice.
458 /// Since WTF-8 is a superset of UTF-8, this always succeeds.
460 pub fn from_str(value: &str) -> &Wtf8 {
461 unsafe { Wtf8::from_bytes_unchecked(value.as_bytes()) }
464 /// Creates a WTF-8 slice from a WTF-8 byte slice.
466 /// Since the byte slice is not checked for valid WTF-8, this functions is
469 unsafe fn from_bytes_unchecked(value: &[u8]) -> &Wtf8 {
470 mem::transmute(value)
473 /// Creates a mutable WTF-8 slice from a mutable WTF-8 byte slice.
475 /// Since the byte slice is not checked for valid WTF-8, this functions is
478 unsafe fn from_mut_bytes_unchecked(value: &mut [u8]) -> &mut Wtf8 {
479 mem::transmute(value)
482 /// Returns the length, in WTF-8 bytes.
484 pub fn len(&self) -> usize {
489 pub fn is_empty(&self) -> bool {
490 self.bytes.is_empty()
493 /// Returns the code point at `position` if it is in the ASCII range,
494 /// or `b'\xFF' otherwise.
498 /// Panics if `position` is beyond the end of the string.
500 pub fn ascii_byte_at(&self, position: usize) -> u8 {
501 match self.bytes[position] {
502 ascii_byte @ 0x00..=0x7F => ascii_byte,
507 /// Returns an iterator for the string’s code points.
509 pub fn code_points(&self) -> Wtf8CodePoints<'_> {
510 Wtf8CodePoints { bytes: self.bytes.iter() }
513 /// Tries to convert the string to UTF-8 and return a `&str` slice.
515 /// Returns `None` if the string contains surrogates.
517 /// This does not copy the data.
519 pub fn as_str(&self) -> Option<&str> {
520 // Well-formed WTF-8 is also well-formed UTF-8
521 // if and only if it contains no surrogate.
522 match self.next_surrogate(0) {
523 None => Some(unsafe { str::from_utf8_unchecked(&self.bytes) }),
528 /// Lossily converts the string to UTF-8.
529 /// Returns a UTF-8 `&str` slice if the contents are well-formed in UTF-8.
531 /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”).
533 /// This only copies the data if necessary (if it contains any surrogate).
534 pub fn to_string_lossy(&self) -> Cow<'_, str> {
535 let surrogate_pos = match self.next_surrogate(0) {
536 None => return Cow::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) }),
537 Some((pos, _)) => pos,
539 let wtf8_bytes = &self.bytes;
540 let mut utf8_bytes = Vec::with_capacity(self.len());
541 utf8_bytes.extend_from_slice(&wtf8_bytes[..surrogate_pos]);
542 utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
543 let mut pos = surrogate_pos + 3;
545 match self.next_surrogate(pos) {
546 Some((surrogate_pos, _)) => {
547 utf8_bytes.extend_from_slice(&wtf8_bytes[pos..surrogate_pos]);
548 utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
549 pos = surrogate_pos + 3;
552 utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]);
553 return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) });
559 /// Converts the WTF-8 string to potentially ill-formed UTF-16
560 /// and return an iterator of 16-bit code units.
562 /// This is lossless:
563 /// calling `Wtf8Buf::from_ill_formed_utf16` on the resulting code units
564 /// would always return the original WTF-8 string.
566 pub fn encode_wide(&self) -> EncodeWide<'_> {
567 EncodeWide { code_points: self.code_points(), extra: 0 }
571 fn next_surrogate(&self, mut pos: usize) -> Option<(usize, u16)> {
572 let mut iter = self.bytes[pos..].iter();
574 let b = *iter.next()?;
580 } else if b == 0xED {
581 match (iter.next(), iter.next()) {
582 (Some(&b2), Some(&b3)) if b2 >= 0xA0 => {
583 return Some((pos, decode_surrogate(b2, b3)));
601 fn final_lead_surrogate(&self) -> Option<u16> {
602 let len = self.len();
606 match &self.bytes[(len - 3)..] {
607 &[0xED, b2 @ 0xA0..=0xAF, b3] => Some(decode_surrogate(b2, b3)),
613 fn initial_trail_surrogate(&self) -> Option<u16> {
614 let len = self.len();
618 match &self.bytes[..3] {
619 &[0xED, b2 @ 0xB0..=0xBF, b3] => Some(decode_surrogate(b2, b3)),
624 /// Boxes this `Wtf8`.
626 pub fn into_box(&self) -> Box<Wtf8> {
627 let boxed: Box<[u8]> = self.bytes.into();
628 unsafe { mem::transmute(boxed) }
631 /// Creates a boxed, empty `Wtf8`.
632 pub fn empty_box() -> Box<Wtf8> {
633 let boxed: Box<[u8]> = Default::default();
634 unsafe { mem::transmute(boxed) }
638 pub fn into_arc(&self) -> Arc<Wtf8> {
639 let arc: Arc<[u8]> = Arc::from(&self.bytes);
640 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Wtf8) }
644 pub fn into_rc(&self) -> Rc<Wtf8> {
645 let rc: Rc<[u8]> = Rc::from(&self.bytes);
646 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Wtf8) }
650 /// Returns a slice of the given string for the byte range [`begin`..`end`).
654 /// Panics when `begin` and `end` do not point to code point boundaries,
655 /// or point beyond the end of the string.
656 impl ops::Index<ops::Range<usize>> for Wtf8 {
660 fn index(&self, range: ops::Range<usize>) -> &Wtf8 {
661 // is_code_point_boundary checks that the index is in [0, .len()]
662 if range.start <= range.end
663 && is_code_point_boundary(self, range.start)
664 && is_code_point_boundary(self, range.end)
666 unsafe { slice_unchecked(self, range.start, range.end) }
668 slice_error_fail(self, range.start, range.end)
673 /// Returns a slice of the given string from byte `begin` to its end.
677 /// Panics when `begin` is not at a code point boundary,
678 /// or is beyond the end of the string.
679 impl ops::Index<ops::RangeFrom<usize>> for Wtf8 {
683 fn index(&self, range: ops::RangeFrom<usize>) -> &Wtf8 {
684 // is_code_point_boundary checks that the index is in [0, .len()]
685 if is_code_point_boundary(self, range.start) {
686 unsafe { slice_unchecked(self, range.start, self.len()) }
688 slice_error_fail(self, range.start, self.len())
693 /// Returns a slice of the given string from its beginning to byte `end`.
697 /// Panics when `end` is not at a code point boundary,
698 /// or is beyond the end of the string.
699 impl ops::Index<ops::RangeTo<usize>> for Wtf8 {
703 fn index(&self, range: ops::RangeTo<usize>) -> &Wtf8 {
704 // is_code_point_boundary checks that the index is in [0, .len()]
705 if is_code_point_boundary(self, range.end) {
706 unsafe { slice_unchecked(self, 0, range.end) }
708 slice_error_fail(self, 0, range.end)
713 impl ops::Index<ops::RangeFull> for Wtf8 {
717 fn index(&self, _range: ops::RangeFull) -> &Wtf8 {
723 fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 {
724 // The first byte is assumed to be 0xED
725 0xD800 | (second_byte as u16 & 0x3F) << 6 | third_byte as u16 & 0x3F
729 fn decode_surrogate_pair(lead: u16, trail: u16) -> char {
730 let code_point = 0x10000 + ((((lead - 0xD800) as u32) << 10) | (trail - 0xDC00) as u32);
731 unsafe { char::from_u32_unchecked(code_point) }
734 /// Copied from core::str::StrPrelude::is_char_boundary
736 pub fn is_code_point_boundary(slice: &Wtf8, index: usize) -> bool {
737 if index == slice.len() {
740 match slice.bytes.get(index) {
742 Some(&b) => b < 128 || b >= 192,
746 /// Copied from core::str::raw::slice_unchecked
748 pub unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 {
749 // memory layout of an &[u8] and &Wtf8 are the same
750 Wtf8::from_bytes_unchecked(slice::from_raw_parts(s.bytes.as_ptr().add(begin), end - begin))
753 /// Copied from core::str::raw::slice_error_fail
755 pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! {
756 assert!(begin <= end);
757 panic!("index {} and/or {} in `{:?}` do not lie on character boundary", begin, end, s);
760 /// Iterator for the code points of a WTF-8 string.
762 /// Created with the method `.code_points()`.
764 pub struct Wtf8CodePoints<'a> {
765 bytes: slice::Iter<'a, u8>,
768 impl<'a> Iterator for Wtf8CodePoints<'a> {
769 type Item = CodePoint;
772 fn next(&mut self) -> Option<CodePoint> {
773 next_code_point(&mut self.bytes).map(|c| CodePoint { value: c })
777 fn size_hint(&self) -> (usize, Option<usize>) {
778 let len = self.bytes.len();
779 (len.saturating_add(3) / 4, Some(len))
783 /// Generates a wide character sequence for potentially ill-formed UTF-16.
784 #[stable(feature = "rust1", since = "1.0.0")]
786 pub struct EncodeWide<'a> {
787 code_points: Wtf8CodePoints<'a>,
791 // Copied from libunicode/u_str.rs
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl<'a> Iterator for EncodeWide<'a> {
797 fn next(&mut self) -> Option<u16> {
799 let tmp = self.extra;
804 let mut buf = [0; 2];
805 self.code_points.next().map(|code_point| {
806 let c = unsafe { char::from_u32_unchecked(code_point.value) };
807 let n = c.encode_utf16(&mut buf).len();
816 fn size_hint(&self) -> (usize, Option<usize>) {
817 let (low, high) = self.code_points.size_hint();
818 // every code point gets either one u16 or two u16,
819 // so this iterator is between 1 or 2 times as
820 // long as the underlying iterator.
821 (low, high.and_then(|n| n.checked_mul(2)))
825 impl Hash for CodePoint {
827 fn hash<H: Hasher>(&self, state: &mut H) {
828 self.value.hash(state)
832 impl Hash for Wtf8Buf {
834 fn hash<H: Hasher>(&self, state: &mut H) {
835 state.write(&self.bytes);
842 fn hash<H: Hasher>(&self, state: &mut H) {
843 state.write(&self.bytes);
849 pub fn make_ascii_uppercase(&mut self) {
850 self.bytes.make_ascii_uppercase()
857 use crate::borrow::Cow;
860 fn code_point_from_u32() {
861 assert!(CodePoint::from_u32(0).is_some());
862 assert!(CodePoint::from_u32(0xD800).is_some());
863 assert!(CodePoint::from_u32(0x10FFFF).is_some());
864 assert!(CodePoint::from_u32(0x110000).is_none());
868 fn code_point_to_u32() {
869 fn c(value: u32) -> CodePoint {
870 CodePoint::from_u32(value).unwrap()
872 assert_eq!(c(0).to_u32(), 0);
873 assert_eq!(c(0xD800).to_u32(), 0xD800);
874 assert_eq!(c(0x10FFFF).to_u32(), 0x10FFFF);
878 fn code_point_from_char() {
879 assert_eq!(CodePoint::from_char('a').to_u32(), 0x61);
880 assert_eq!(CodePoint::from_char('💩').to_u32(), 0x1F4A9);
884 fn code_point_to_string() {
885 assert_eq!(format!("{:?}", CodePoint::from_char('a')), "U+0061");
886 assert_eq!(format!("{:?}", CodePoint::from_char('💩')), "U+1F4A9");
890 fn code_point_to_char() {
891 fn c(value: u32) -> CodePoint {
892 CodePoint::from_u32(value).unwrap()
894 assert_eq!(c(0x61).to_char(), Some('a'));
895 assert_eq!(c(0x1F4A9).to_char(), Some('💩'));
896 assert_eq!(c(0xD800).to_char(), None);
900 fn code_point_to_char_lossy() {
901 fn c(value: u32) -> CodePoint {
902 CodePoint::from_u32(value).unwrap()
904 assert_eq!(c(0x61).to_char_lossy(), 'a');
905 assert_eq!(c(0x1F4A9).to_char_lossy(), '💩');
906 assert_eq!(c(0xD800).to_char_lossy(), '\u{FFFD}');
911 assert_eq!(Wtf8Buf::new().bytes, b"");
915 fn wtf8buf_from_str() {
916 assert_eq!(Wtf8Buf::from_str("").bytes, b"");
917 assert_eq!(Wtf8Buf::from_str("aé 💩").bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
921 fn wtf8buf_from_string() {
922 assert_eq!(Wtf8Buf::from_string(String::from("")).bytes, b"");
924 Wtf8Buf::from_string(String::from("aé 💩")).bytes,
925 b"a\xC3\xA9 \xF0\x9F\x92\xA9"
930 fn wtf8buf_from_wide() {
931 assert_eq!(Wtf8Buf::from_wide(&[]).bytes, b"");
933 Wtf8Buf::from_wide(&[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes,
934 b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9"
939 fn wtf8buf_push_str() {
940 let mut string = Wtf8Buf::new();
941 assert_eq!(string.bytes, b"");
942 string.push_str("aé 💩");
943 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
947 fn wtf8buf_push_char() {
948 let mut string = Wtf8Buf::from_str("aé ");
949 assert_eq!(string.bytes, b"a\xC3\xA9 ");
950 string.push_char('💩');
951 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
956 let mut string = Wtf8Buf::from_str("aé ");
957 assert_eq!(string.bytes, b"a\xC3\xA9 ");
958 string.push(CodePoint::from_char('💩'));
959 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
961 fn c(value: u32) -> CodePoint {
962 CodePoint::from_u32(value).unwrap()
965 let mut string = Wtf8Buf::new();
966 string.push(c(0xD83D)); // lead
967 string.push(c(0xDCA9)); // trail
968 assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
970 let mut string = Wtf8Buf::new();
971 string.push(c(0xD83D)); // lead
972 string.push(c(0x20)); // not surrogate
973 string.push(c(0xDCA9)); // trail
974 assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
976 let mut string = Wtf8Buf::new();
977 string.push(c(0xD800)); // lead
978 string.push(c(0xDBFF)); // lead
979 assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
981 let mut string = Wtf8Buf::new();
982 string.push(c(0xD800)); // lead
983 string.push(c(0xE000)); // not surrogate
984 assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
986 let mut string = Wtf8Buf::new();
987 string.push(c(0xD7FF)); // not surrogate
988 string.push(c(0xDC00)); // trail
989 assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
991 let mut string = Wtf8Buf::new();
992 string.push(c(0x61)); // not surrogate, < 3 bytes
993 string.push(c(0xDC00)); // trail
994 assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
996 let mut string = Wtf8Buf::new();
997 string.push(c(0xDC00)); // trail
998 assert_eq!(string.bytes, b"\xED\xB0\x80");
1002 fn wtf8buf_push_wtf8() {
1003 let mut string = Wtf8Buf::from_str("aé");
1004 assert_eq!(string.bytes, b"a\xC3\xA9");
1005 string.push_wtf8(Wtf8::from_str(" 💩"));
1006 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1008 fn w(v: &[u8]) -> &Wtf8 {
1009 unsafe { Wtf8::from_bytes_unchecked(v) }
1012 let mut string = Wtf8Buf::new();
1013 string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
1014 string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
1015 assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1017 let mut string = Wtf8Buf::new();
1018 string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
1019 string.push_wtf8(w(b" ")); // not surrogate
1020 string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
1021 assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1023 let mut string = Wtf8Buf::new();
1024 string.push_wtf8(w(b"\xED\xA0\x80")); // lead
1025 string.push_wtf8(w(b"\xED\xAF\xBF")); // lead
1026 assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1028 let mut string = Wtf8Buf::new();
1029 string.push_wtf8(w(b"\xED\xA0\x80")); // lead
1030 string.push_wtf8(w(b"\xEE\x80\x80")); // not surrogate
1031 assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
1033 let mut string = Wtf8Buf::new();
1034 string.push_wtf8(w(b"\xED\x9F\xBF")); // not surrogate
1035 string.push_wtf8(w(b"\xED\xB0\x80")); // trail
1036 assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1038 let mut string = Wtf8Buf::new();
1039 string.push_wtf8(w(b"a")); // not surrogate, < 3 bytes
1040 string.push_wtf8(w(b"\xED\xB0\x80")); // trail
1041 assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
1043 let mut string = Wtf8Buf::new();
1044 string.push_wtf8(w(b"\xED\xB0\x80")); // trail
1045 assert_eq!(string.bytes, b"\xED\xB0\x80");
1049 fn wtf8buf_truncate() {
1050 let mut string = Wtf8Buf::from_str("aé");
1052 assert_eq!(string.bytes, b"a");
1057 fn wtf8buf_truncate_fail_code_point_boundary() {
1058 let mut string = Wtf8Buf::from_str("aé");
1064 fn wtf8buf_truncate_fail_longer() {
1065 let mut string = Wtf8Buf::from_str("aé");
1070 fn wtf8buf_into_string() {
1071 let mut string = Wtf8Buf::from_str("aé 💩");
1072 assert_eq!(string.clone().into_string(), Ok(String::from("aé 💩")));
1073 string.push(CodePoint::from_u32(0xD800).unwrap());
1074 assert_eq!(string.clone().into_string(), Err(string));
1078 fn wtf8buf_into_string_lossy() {
1079 let mut string = Wtf8Buf::from_str("aé 💩");
1080 assert_eq!(string.clone().into_string_lossy(), String::from("aé 💩"));
1081 string.push(CodePoint::from_u32(0xD800).unwrap());
1082 assert_eq!(string.clone().into_string_lossy(), String::from("aé 💩�"));
1086 fn wtf8buf_from_iterator() {
1087 fn f(values: &[u32]) -> Wtf8Buf {
1088 values.iter().map(|&c| CodePoint::from_u32(c).unwrap()).collect::<Wtf8Buf>()
1090 assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1092 assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1093 assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1094 assert_eq!(f(&[0xD800, 0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1095 assert_eq!(f(&[0xD800, 0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1096 assert_eq!(f(&[0xD7FF, 0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1097 assert_eq!(f(&[0x61, 0xDC00]).bytes, b"\x61\xED\xB0\x80");
1098 assert_eq!(f(&[0xDC00]).bytes, b"\xED\xB0\x80");
1102 fn wtf8buf_extend() {
1103 fn e(initial: &[u32], extended: &[u32]) -> Wtf8Buf {
1104 fn c(value: &u32) -> CodePoint {
1105 CodePoint::from_u32(*value).unwrap()
1107 let mut string = initial.iter().map(c).collect::<Wtf8Buf>();
1108 string.extend(extended.iter().map(c));
1112 assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1114 assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1115 assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1116 assert_eq!(e(&[0xD800], &[0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1117 assert_eq!(e(&[0xD800], &[0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1118 assert_eq!(e(&[0xD7FF], &[0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1119 assert_eq!(e(&[0x61], &[0xDC00]).bytes, b"\x61\xED\xB0\x80");
1120 assert_eq!(e(&[], &[0xDC00]).bytes, b"\xED\xB0\x80");
1125 let mut string = Wtf8Buf::from_str("a\té \u{7f}💩\r");
1126 string.push(CodePoint::from_u32(0xD800).unwrap());
1127 assert_eq!(format!("{:?}", string), "\"a\\té \\u{7f}\u{1f4a9}\\r\\u{d800}\"");
1131 fn wtf8buf_as_slice() {
1132 assert_eq!(Wtf8Buf::from_str("aé").as_slice(), Wtf8::from_str("aé"));
1136 fn wtf8buf_show_str() {
1137 let text = "a\té 💩\r";
1138 let string = Wtf8Buf::from_str(text);
1139 assert_eq!(format!("{:?}", text), format!("{:?}", string));
1143 fn wtf8_from_str() {
1144 assert_eq!(&Wtf8::from_str("").bytes, b"");
1145 assert_eq!(&Wtf8::from_str("aé 💩").bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1150 assert_eq!(Wtf8::from_str("").len(), 0);
1151 assert_eq!(Wtf8::from_str("aé 💩").len(), 8);
1156 assert_eq!(&Wtf8::from_str("aé 💩")[1..4].bytes, b"\xC3\xA9 ");
1161 fn wtf8_slice_not_code_point_boundary() {
1162 &Wtf8::from_str("aé 💩")[2..4];
1166 fn wtf8_slice_from() {
1167 assert_eq!(&Wtf8::from_str("aé 💩")[1..].bytes, b"\xC3\xA9 \xF0\x9F\x92\xA9");
1172 fn wtf8_slice_from_not_code_point_boundary() {
1173 &Wtf8::from_str("aé 💩")[2..];
1177 fn wtf8_slice_to() {
1178 assert_eq!(&Wtf8::from_str("aé 💩")[..4].bytes, b"a\xC3\xA9 ");
1183 fn wtf8_slice_to_not_code_point_boundary() {
1184 &Wtf8::from_str("aé 💩")[5..];
1188 fn wtf8_ascii_byte_at() {
1189 let slice = Wtf8::from_str("aé 💩");
1190 assert_eq!(slice.ascii_byte_at(0), b'a');
1191 assert_eq!(slice.ascii_byte_at(1), b'\xFF');
1192 assert_eq!(slice.ascii_byte_at(2), b'\xFF');
1193 assert_eq!(slice.ascii_byte_at(3), b' ');
1194 assert_eq!(slice.ascii_byte_at(4), b'\xFF');
1198 fn wtf8_code_points() {
1199 fn c(value: u32) -> CodePoint {
1200 CodePoint::from_u32(value).unwrap()
1202 fn cp(string: &Wtf8Buf) -> Vec<Option<char>> {
1203 string.code_points().map(|c| c.to_char()).collect::<Vec<_>>()
1205 let mut string = Wtf8Buf::from_str("é ");
1206 assert_eq!(cp(&string), [Some('é'), Some(' ')]);
1207 string.push(c(0xD83D));
1208 assert_eq!(cp(&string), [Some('é'), Some(' '), None]);
1209 string.push(c(0xDCA9));
1210 assert_eq!(cp(&string), [Some('é'), Some(' '), Some('💩')]);
1215 assert_eq!(Wtf8::from_str("").as_str(), Some(""));
1216 assert_eq!(Wtf8::from_str("aé 💩").as_str(), Some("aé 💩"));
1217 let mut string = Wtf8Buf::new();
1218 string.push(CodePoint::from_u32(0xD800).unwrap());
1219 assert_eq!(string.as_str(), None);
1223 fn wtf8_to_string_lossy() {
1224 assert_eq!(Wtf8::from_str("").to_string_lossy(), Cow::Borrowed(""));
1225 assert_eq!(Wtf8::from_str("aé 💩").to_string_lossy(), Cow::Borrowed("aé 💩"));
1226 let mut string = Wtf8Buf::from_str("aé 💩");
1227 string.push(CodePoint::from_u32(0xD800).unwrap());
1228 let expected: Cow<'_, str> = Cow::Owned(String::from("aé 💩�"));
1229 assert_eq!(string.to_string_lossy(), expected);
1234 fn d(b: &[u8]) -> String {
1235 (&unsafe { Wtf8::from_bytes_unchecked(b) }).to_string()
1238 assert_eq!("", d("".as_bytes()));
1239 assert_eq!("aé 💩", d("aé 💩".as_bytes()));
1241 let mut string = Wtf8Buf::from_str("aé 💩");
1242 string.push(CodePoint::from_u32(0xD800).unwrap());
1243 assert_eq!("aé 💩�", d(string.as_inner()));
1247 fn wtf8_encode_wide() {
1248 let mut string = Wtf8Buf::from_str("aé ");
1249 string.push(CodePoint::from_u32(0xD83D).unwrap());
1250 string.push_char('💩');
1252 string.encode_wide().collect::<Vec<_>>(),
1253 vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]