1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Implementation of [the WTF-8 encoding](https://simonsapin.github.io/wtf-8/).
13 //! This library uses Rust’s type system to maintain
14 //! [well-formedness](https://simonsapin.github.io/wtf-8/#well-formed),
15 //! like the `String` and `&str` types do for UTF-8.
17 //! Since [WTF-8 must not be used
18 //! for interchange](https://simonsapin.github.io/wtf-8/#intended-audience),
19 //! this library deliberately does not provide access to the underlying bytes
21 //! nor can it decode WTF-8 from arbitrary bytes.
22 //! WTF-8 strings can be obtained from UTF-8, UTF-16, or code points.
26 use core::char::{encode_utf8_raw, encode_utf16_raw};
27 use core::str::{char_range_at_raw, next_code_point};
28 use core::raw::Slice as RawSlice;
34 use hash::{Hash, Hasher};
35 #[cfg(stage0)] use hash::Writer;
36 use iter::{FromIterator, IntoIterator};
42 use string::{String, CowString};
43 use sys_common::AsInner;
44 use unicode::str::{Utf16Item, utf16_items};
47 static UTF8_REPLACEMENT_CHARACTER: &'static [u8] = b"\xEF\xBF\xBD";
49 /// A Unicode code point: from U+0000 to U+10FFFF.
51 /// Compare with the `char` type,
52 /// which represents a Unicode scalar value:
53 /// a code point that is not a surrogate (U+D800 to U+DFFF).
54 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
55 pub struct CodePoint {
59 /// Format the code point as `U+` followed by four to six hexadecimal digits.
60 /// Example: `U+1F4A9`
61 impl fmt::Debug for CodePoint {
63 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
64 write!(formatter, "U+{:04X}", self.value)
69 /// Unsafely create a new `CodePoint` without checking the value.
71 /// Only use when `value` is known to be less than or equal to 0x10FFFF.
73 pub unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
74 CodePoint { value: value }
77 /// Create a new `CodePoint` if the value is a valid code point.
79 /// Return `None` if `value` is above 0x10FFFF.
81 pub fn from_u32(value: u32) -> Option<CodePoint> {
83 0 ... 0x10FFFF => Some(CodePoint { value: value }),
88 /// Create a new `CodePoint` from a `char`.
90 /// Since all Unicode scalar values are code points, this always succeeds.
92 pub fn from_char(value: char) -> CodePoint {
93 CodePoint { value: value as u32 }
96 /// Return the numeric value of the code point.
98 pub fn to_u32(&self) -> u32 {
102 /// Optionally return a Unicode scalar value for the code point.
104 /// Return `None` if the code point is a surrogate (from U+D800 to U+DFFF).
106 pub fn to_char(&self) -> Option<char> {
108 0xD800 ... 0xDFFF => None,
109 _ => Some(unsafe { mem::transmute(self.value) })
113 /// Return a Unicode scalar value for the code point.
115 /// Return `'\u{FFFD}'` (the replacement character “�”)
116 /// if the code point is a surrogate (from U+D800 to U+DFFF).
118 pub fn to_char_lossy(&self) -> char {
119 self.to_char().unwrap_or('\u{FFFD}')
123 /// An owned, growable string of well-formed WTF-8 data.
125 /// Similar to `String`, but can additionally contain surrogate code points
126 /// if they’re not in a surrogate pair.
127 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
132 impl ops::Deref for Wtf8Buf {
135 fn deref(&self) -> &Wtf8 {
140 /// Format the string with double quotes,
141 /// and surrogates as `\u` followed by four hexadecimal digits.
142 /// Example: `"a\u{D800}"` for a string with code points [U+0061, U+D800]
143 impl fmt::Debug for Wtf8Buf {
145 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
146 fmt::Debug::fmt(&**self, formatter)
151 /// Create an new, empty WTF-8 string.
153 pub fn new() -> Wtf8Buf {
154 Wtf8Buf { bytes: Vec::new() }
157 /// Create an new, empty WTF-8 string with pre-allocated capacity for `n` bytes.
159 pub fn with_capacity(n: uint) -> Wtf8Buf {
160 Wtf8Buf { bytes: Vec::with_capacity(n) }
163 /// Create a WTF-8 string from an UTF-8 `String`.
165 /// This takes ownership of the `String` and does not copy.
167 /// Since WTF-8 is a superset of UTF-8, this always succeeds.
169 pub fn from_string(string: String) -> Wtf8Buf {
170 Wtf8Buf { bytes: string.into_bytes() }
173 /// Create a WTF-8 string from an UTF-8 `&str` slice.
175 /// This copies the content of the slice.
177 /// Since WTF-8 is a superset of UTF-8, this always succeeds.
179 pub fn from_str(str: &str) -> Wtf8Buf {
180 Wtf8Buf { bytes: slice::SliceExt::to_vec(str.as_bytes()) }
183 /// Create a WTF-8 string from a potentially ill-formed UTF-16 slice of 16-bit code units.
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 utf16_items(v) {
191 Utf16Item::ScalarValue(c) => string.push_char(c),
192 Utf16Item::LoneSurrogate(s) => {
193 // Surrogates are known to be in the code point range.
194 let code_point = unsafe { CodePoint::from_u32_unchecked(s as u32) };
195 // Skip the WTF-8 concatenation check,
196 // surrogate pairs are already decoded by utf16_items
197 string.push_code_point_unchecked(code_point)
204 /// Copied from String::push
205 /// This does **not** include the WTF-8 concatenation check.
206 fn push_code_point_unchecked(&mut self, code_point: CodePoint) {
207 let cur_len = self.len();
208 // This may use up to 4 bytes.
212 // Attempt to not use an intermediate buffer by just pushing bytes
213 // directly onto this string.
214 let slice = RawSlice {
215 data: self.bytes.as_ptr().offset(cur_len as int),
218 let used = encode_utf8_raw(code_point.value, mem::transmute(slice))
220 self.bytes.set_len(cur_len + used);
225 pub fn as_slice(&self) -> &Wtf8 {
226 unsafe { mem::transmute(&*self.bytes) }
229 /// Reserves capacity for at least `additional` more bytes to be inserted
230 /// in the given `Wtf8Buf`.
231 /// The collection may reserve more space to avoid frequent reallocations.
235 /// Panics if the new capacity overflows `uint`.
237 pub fn reserve(&mut self, additional: uint) {
238 self.bytes.reserve(additional)
241 /// Returns the number of bytes that this string buffer can hold without reallocating.
243 pub fn capacity(&self) -> uint {
244 self.bytes.capacity()
247 /// Append an UTF-8 slice at the end of the string.
249 pub fn push_str(&mut self, other: &str) {
250 self.bytes.push_all(other.as_bytes())
253 /// Append a WTF-8 slice at the end of the string.
255 /// This replaces newly paired surrogates at the boundary
256 /// with a supplementary code point,
257 /// like concatenating ill-formed UTF-16 strings effectively would.
259 pub fn push_wtf8(&mut self, other: &Wtf8) {
260 match ((&*self).final_lead_surrogate(), other.initial_trail_surrogate()) {
261 // Replace newly paired surrogates by a supplementary code point.
262 (Some(lead), Some(trail)) => {
263 let len_without_lead_surrogate = self.len() - 3;
264 self.bytes.truncate(len_without_lead_surrogate);
265 let other_without_trail_surrogate = &other.bytes[3..];
266 // 4 bytes for the supplementary code point
267 self.bytes.reserve(4 + other_without_trail_surrogate.len());
268 self.push_char(decode_surrogate_pair(lead, trail));
269 self.bytes.push_all(other_without_trail_surrogate);
271 _ => self.bytes.push_all(&other.bytes)
275 /// Append a Unicode scalar value at the end of the string.
277 pub fn push_char(&mut self, c: char) {
278 self.push_code_point_unchecked(CodePoint::from_char(c))
281 /// Append a code point at the end of the string.
283 /// This replaces newly paired surrogates at the boundary
284 /// with a supplementary code point,
285 /// like concatenating ill-formed UTF-16 strings effectively would.
287 pub fn push(&mut self, code_point: CodePoint) {
288 match code_point.to_u32() {
289 trail @ 0xDC00...0xDFFF => {
290 match (&*self).final_lead_surrogate() {
292 let len_without_lead_surrogate = self.len() - 3;
293 self.bytes.truncate(len_without_lead_surrogate);
294 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: uint) {
315 assert!(is_code_point_boundary(self, new_len));
316 self.bytes.truncate(new_len)
319 /// Consume the WTF-8 string and try 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 /// Consume the WTF-8 string and convert 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 slice::bytes::copy_memory(
345 &mut self.bytes[surrogate_pos .. pos],
346 UTF8_REPLACEMENT_CHARACTER
349 None => return unsafe { String::from_utf8_unchecked(self.bytes) }
355 /// Create a new WTF-8 string from an iterator of code points.
357 /// This replaces surrogate code point pairs with supplementary code points,
358 /// like concatenating ill-formed UTF-16 strings effectively would.
359 impl FromIterator<CodePoint> for Wtf8Buf {
360 fn from_iter<T: IntoIterator<Item=CodePoint>>(iter: T) -> Wtf8Buf {
361 let mut string = Wtf8Buf::new();
367 /// Append code points from an iterator to the string.
369 /// This replaces surrogate code point pairs with supplementary code points,
370 /// like concatenating ill-formed UTF-16 strings effectively would.
371 impl Extend<CodePoint> for Wtf8Buf {
372 fn extend<T: IntoIterator<Item=CodePoint>>(&mut self, iterable: T) {
373 let iterator = iterable.into_iter();
374 let (low, _high) = iterator.size_hint();
375 // Lower bound of one byte per code point (ASCII only)
376 self.bytes.reserve(low);
377 for code_point in iterator {
378 self.push(code_point);
383 /// A borrowed slice of well-formed WTF-8 data.
385 /// Similar to `&str`, but can additionally contain surrogate code points
386 /// if they’re not in a surrogate pair.
391 impl AsInner<[u8]> for Wtf8 {
392 fn as_inner(&self) -> &[u8] { &self.bytes }
395 // FIXME: https://github.com/rust-lang/rust/issues/18805
396 impl PartialEq for Wtf8 {
397 fn eq(&self, other: &Wtf8) -> bool { self.bytes.eq(&other.bytes) }
400 // FIXME: https://github.com/rust-lang/rust/issues/18805
403 // FIXME: https://github.com/rust-lang/rust/issues/18738
404 impl PartialOrd for Wtf8 {
406 fn partial_cmp(&self, other: &Wtf8) -> Option<cmp::Ordering> {
407 self.bytes.partial_cmp(&other.bytes)
410 fn lt(&self, other: &Wtf8) -> bool { self.bytes.lt(&other.bytes) }
412 fn le(&self, other: &Wtf8) -> bool { self.bytes.le(&other.bytes) }
414 fn gt(&self, other: &Wtf8) -> bool { self.bytes.gt(&other.bytes) }
416 fn ge(&self, other: &Wtf8) -> bool { self.bytes.ge(&other.bytes) }
419 // FIXME: https://github.com/rust-lang/rust/issues/18738
422 fn cmp(&self, other: &Wtf8) -> cmp::Ordering { self.bytes.cmp(&other.bytes) }
425 /// Format the slice with double quotes,
426 /// and surrogates as `\u` followed by four hexadecimal digits.
427 /// Example: `"a\u{D800}"` for a slice with code points [U+0061, U+D800]
428 impl fmt::Debug for Wtf8 {
429 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
430 try!(formatter.write_str("\""));
433 match self.next_surrogate(pos) {
435 Some((surrogate_pos, surrogate)) => {
436 try!(formatter.write_str(unsafe {
437 // the data in this slice is valid UTF-8, transmute to &str
438 mem::transmute(&self.bytes[pos .. surrogate_pos])
440 try!(write!(formatter, "\\u{{{:X}}}", surrogate));
441 pos = surrogate_pos + 3;
445 try!(formatter.write_str(unsafe {
446 // the data in this slice is valid UTF-8, transmute to &str
447 mem::transmute(&self.bytes[pos..])
449 formatter.write_str("\"")
454 /// Create a WTF-8 slice from a UTF-8 `&str` slice.
456 /// Since WTF-8 is a superset of UTF-8, this always succeeds.
458 pub fn from_str(value: &str) -> &Wtf8 {
459 unsafe { mem::transmute(value.as_bytes()) }
462 /// Return the length, in WTF-8 bytes.
464 pub fn len(&self) -> uint {
468 /// Return the code point at `position` if it is in the ASCII range,
469 /// or `b'\xFF' otherwise.
473 /// Panics if `position` is beyond the end of the string.
475 pub fn ascii_byte_at(&self, position: uint) -> u8 {
476 match self.bytes[position] {
477 ascii_byte @ 0x00 ... 0x7F => ascii_byte,
482 /// Return the code point at `position`.
486 /// Panics if `position` is not at a code point boundary,
487 /// or is beyond the end of the string.
489 pub fn code_point_at(&self, position: uint) -> CodePoint {
490 let (code_point, _) = self.code_point_range_at(position);
494 /// Return the code point at `position`
495 /// and the position of the next code point.
499 /// Panics if `position` is not at a code point boundary,
500 /// or is beyond the end of the string.
502 pub fn code_point_range_at(&self, position: uint) -> (CodePoint, uint) {
503 let (c, n) = char_range_at_raw(&self.bytes, position);
504 (CodePoint { value: c }, n)
507 /// Return an iterator for the string’s code points.
509 pub fn code_points(&self) -> Wtf8CodePoints {
510 Wtf8CodePoints { bytes: self.bytes.iter() }
513 /// Try to convert the string to UTF-8 and return a `&str` slice.
515 /// Return `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 convert the string to UTF-8.
529 /// Return an 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) -> CowString {
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.push_all(&wtf8_bytes[..surrogate_pos]);
542 utf8_bytes.push_all(UTF8_REPLACEMENT_CHARACTER);
543 let mut pos = surrogate_pos + 3;
545 match self.next_surrogate(pos) {
546 Some((surrogate_pos, _)) => {
547 utf8_bytes.push_all(&wtf8_bytes[pos .. surrogate_pos]);
548 utf8_bytes.push_all(UTF8_REPLACEMENT_CHARACTER);
549 pos = surrogate_pos + 3;
552 utf8_bytes.push_all(&wtf8_bytes[pos..]);
553 return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) })
559 /// Convert 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: uint) -> Option<(uint, u16)> {
572 let mut iter = self.bytes[pos..].iter();
574 let b = match iter.next() {
583 } else if b == 0xED {
584 match (iter.next(), iter.next()) {
585 (Some(&b2), Some(&b3)) if b2 >= 0xA0 => {
586 return Some((pos, decode_surrogate(b2, b3)))
604 fn final_lead_surrogate(&self) -> Option<u16> {
605 let len = self.len();
609 match &self.bytes[(len - 3)..] {
610 [0xED, b2 @ 0xA0...0xAF, b3] => Some(decode_surrogate(b2, b3)),
616 fn initial_trail_surrogate(&self) -> Option<u16> {
617 let len = self.len();
621 match &self.bytes[..3] {
622 [0xED, b2 @ 0xB0...0xBF, b3] => Some(decode_surrogate(b2, b3)),
629 /// Return a slice of the given string for the byte range [`begin`..`end`).
633 /// Panics when `begin` and `end` do not point to code point boundaries,
634 /// or point beyond the end of the string.
635 impl ops::Index<ops::Range<usize>> for Wtf8 {
639 fn index(&self, range: &ops::Range<usize>) -> &Wtf8 {
640 // is_code_point_boundary checks that the index is in [0, .len()]
641 if range.start <= range.end &&
642 is_code_point_boundary(self, range.start) &&
643 is_code_point_boundary(self, range.end) {
644 unsafe { slice_unchecked(self, range.start, range.end) }
646 slice_error_fail(self, range.start, range.end)
651 /// Return a slice of the given string from byte `begin` to its end.
655 /// Panics when `begin` is not at a code point boundary,
656 /// or is beyond the end of the string.
657 impl ops::Index<ops::RangeFrom<usize>> for Wtf8 {
661 fn index(&self, range: &ops::RangeFrom<usize>) -> &Wtf8 {
662 // is_code_point_boundary checks that the index is in [0, .len()]
663 if is_code_point_boundary(self, range.start) {
664 unsafe { slice_unchecked(self, range.start, self.len()) }
666 slice_error_fail(self, range.start, self.len())
671 /// Return a slice of the given string from its beginning to byte `end`.
675 /// Panics when `end` is not at a code point boundary,
676 /// or is beyond the end of the string.
677 impl ops::Index<ops::RangeTo<usize>> for Wtf8 {
681 fn index(&self, range: &ops::RangeTo<usize>) -> &Wtf8 {
682 // is_code_point_boundary checks that the index is in [0, .len()]
683 if is_code_point_boundary(self, range.end) {
684 unsafe { slice_unchecked(self, 0, range.end) }
686 slice_error_fail(self, 0, range.end)
691 impl ops::Index<ops::RangeFull> for Wtf8 {
695 fn index(&self, _range: &ops::RangeFull) -> &Wtf8 {
701 fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 {
702 // The first byte is assumed to be 0xED
703 0xD800 | (second_byte as u16 & 0x3F) << 6 | third_byte as u16 & 0x3F
707 fn decode_surrogate_pair(lead: u16, trail: u16) -> char {
708 let code_point = 0x10000 + ((((lead - 0xD800) as u32) << 10) | (trail - 0xDC00) as u32);
709 unsafe { mem::transmute(code_point) }
712 /// Copied from core::str::StrPrelude::is_char_boundary
714 pub fn is_code_point_boundary(slice: &Wtf8, index: uint) -> bool {
715 if index == slice.len() { return true; }
716 match slice.bytes.get(index) {
718 Some(&b) => b < 128u8 || b >= 192u8,
722 /// Copied from core::str::raw::slice_unchecked
724 pub unsafe fn slice_unchecked(s: &Wtf8, begin: uint, end: uint) -> &Wtf8 {
725 mem::transmute(RawSlice {
726 data: s.bytes.as_ptr().offset(begin as int),
731 /// Copied from core::str::raw::slice_error_fail
733 pub fn slice_error_fail(s: &Wtf8, begin: uint, end: uint) -> ! {
734 assert!(begin <= end);
735 panic!("index {} and/or {} in `{:?}` do not lie on character boundary",
739 /// Iterator for the code points of a WTF-8 string.
741 /// Created with the method `.code_points()`.
743 pub struct Wtf8CodePoints<'a> {
744 bytes: slice::Iter<'a, u8>
747 impl<'a> Iterator for Wtf8CodePoints<'a> {
748 type Item = CodePoint;
751 fn next(&mut self) -> Option<CodePoint> {
752 next_code_point(&mut self.bytes).map(|c| CodePoint { value: c })
756 fn size_hint(&self) -> (uint, Option<uint>) {
757 let (len, _) = self.bytes.size_hint();
758 (len.saturating_add(3) / 4, Some(len))
763 pub struct EncodeWide<'a> {
764 code_points: Wtf8CodePoints<'a>,
768 // Copied from libunicode/u_str.rs
769 impl<'a> Iterator for EncodeWide<'a> {
773 fn next(&mut self) -> Option<u16> {
775 let tmp = self.extra;
780 let mut buf = [0u16; 2];
781 self.code_points.next().map(|code_point| {
782 let n = encode_utf16_raw(code_point.value, &mut buf)
784 if n == 2 { self.extra = buf[1]; }
790 fn size_hint(&self) -> (uint, Option<uint>) {
791 let (low, high) = self.code_points.size_hint();
792 // every code point gets either one u16 or two u16,
793 // so this iterator is between 1 or 2 times as
794 // long as the underlying iterator.
795 (low, high.and_then(|n| n.checked_mul(2)))
800 impl<S: Writer + Hasher> Hash<S> for CodePoint {
802 fn hash(&self, state: &mut S) {
803 self.value.hash(state)
807 impl Hash for CodePoint {
809 fn hash<H: Hasher>(&self, state: &mut H) {
810 self.value.hash(state)
815 impl<S: Writer + Hasher> Hash<S> for Wtf8Buf {
817 fn hash(&self, state: &mut S) {
818 state.write(&self.bytes);
823 impl Hash for Wtf8Buf {
825 fn hash<H: Hasher>(&self, state: &mut H) {
826 state.write(&self.bytes);
832 impl<'a, S: Writer + Hasher> Hash<S> for Wtf8 {
834 fn hash(&self, state: &mut S) {
835 state.write(&self.bytes);
842 fn hash<H: Hasher>(&self, state: &mut H) {
843 state.write(&self.bytes);
848 impl AsciiExt for Wtf8 {
849 type Owned = Wtf8Buf;
851 fn is_ascii(&self) -> bool {
852 self.bytes.is_ascii()
854 fn to_ascii_uppercase(&self) -> Wtf8Buf {
855 Wtf8Buf { bytes: self.bytes.to_ascii_uppercase() }
857 fn to_ascii_lowercase(&self) -> Wtf8Buf {
858 Wtf8Buf { bytes: self.bytes.to_ascii_lowercase() }
860 fn eq_ignore_ascii_case(&self, other: &Wtf8) -> bool {
861 self.bytes.eq_ignore_ascii_case(&other.bytes)
864 fn make_ascii_uppercase(&mut self) { self.bytes.make_ascii_uppercase() }
865 fn make_ascii_lowercase(&mut self) { self.bytes.make_ascii_lowercase() }
874 use string::CowString;
877 fn code_point_from_u32() {
878 assert!(CodePoint::from_u32(0).is_some());
879 assert!(CodePoint::from_u32(0xD800).is_some());
880 assert!(CodePoint::from_u32(0x10FFFF).is_some());
881 assert!(CodePoint::from_u32(0x110000).is_none());
885 fn code_point_to_u32() {
886 fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
887 assert_eq!(c(0).to_u32(), 0);
888 assert_eq!(c(0xD800).to_u32(), 0xD800);
889 assert_eq!(c(0x10FFFF).to_u32(), 0x10FFFF);
893 fn code_point_from_char() {
894 assert_eq!(CodePoint::from_char('a').to_u32(), 0x61);
895 assert_eq!(CodePoint::from_char('💩').to_u32(), 0x1F4A9);
899 fn code_point_to_string() {
900 assert_eq!(format!("{:?}", CodePoint::from_char('a')), "U+0061");
901 assert_eq!(format!("{:?}", CodePoint::from_char('💩')), "U+1F4A9");
905 fn code_point_to_char() {
906 fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
907 assert_eq!(c(0x61).to_char(), Some('a'));
908 assert_eq!(c(0x1F4A9).to_char(), Some('💩'));
909 assert_eq!(c(0xD800).to_char(), None);
913 fn code_point_to_char_lossy() {
914 fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
915 assert_eq!(c(0x61).to_char_lossy(), 'a');
916 assert_eq!(c(0x1F4A9).to_char_lossy(), '💩');
917 assert_eq!(c(0xD800).to_char_lossy(), '\u{FFFD}');
922 assert_eq!(Wtf8Buf::new().bytes, b"");
926 fn wtf8buf_from_str() {
927 assert_eq!(Wtf8Buf::from_str("").bytes, b"");
928 assert_eq!(Wtf8Buf::from_str("aé 💩").bytes,
929 b"a\xC3\xA9 \xF0\x9F\x92\xA9");
933 fn wtf8buf_from_string() {
934 assert_eq!(Wtf8Buf::from_string(String::from_str("")).bytes, b"");
935 assert_eq!(Wtf8Buf::from_string(String::from_str("aé 💩")).bytes,
936 b"a\xC3\xA9 \xF0\x9F\x92\xA9");
940 fn wtf8buf_from_wide() {
941 assert_eq!(Wtf8Buf::from_wide(&[]).bytes, b"");
942 assert_eq!(Wtf8Buf::from_wide(
943 &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes,
944 b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9");
948 fn wtf8buf_push_str() {
949 let mut string = Wtf8Buf::new();
950 assert_eq!(string.bytes, b"");
951 string.push_str("aé 💩");
952 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
956 fn wtf8buf_push_char() {
957 let mut string = Wtf8Buf::from_str("aé ");
958 assert_eq!(string.bytes, b"a\xC3\xA9 ");
959 string.push_char('💩');
960 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
965 let mut string = Wtf8Buf::from_str("aé ");
966 assert_eq!(string.bytes, b"a\xC3\xA9 ");
967 string.push(CodePoint::from_char('💩'));
968 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
970 fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
972 let mut string = Wtf8Buf::new();
973 string.push(c(0xD83D)); // lead
974 string.push(c(0xDCA9)); // trail
975 assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
977 let mut string = Wtf8Buf::new();
978 string.push(c(0xD83D)); // lead
979 string.push(c(0x20)); // not surrogate
980 string.push(c(0xDCA9)); // trail
981 assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
983 let mut string = Wtf8Buf::new();
984 string.push(c(0xD800)); // lead
985 string.push(c(0xDBFF)); // lead
986 assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
988 let mut string = Wtf8Buf::new();
989 string.push(c(0xD800)); // lead
990 string.push(c(0xE000)); // not surrogate
991 assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
993 let mut string = Wtf8Buf::new();
994 string.push(c(0xD7FF)); // not surrogate
995 string.push(c(0xDC00)); // trail
996 assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
998 let mut string = Wtf8Buf::new();
999 string.push(c(0x61)); // not surrogate, < 3 bytes
1000 string.push(c(0xDC00)); // trail
1001 assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
1003 let mut string = Wtf8Buf::new();
1004 string.push(c(0xDC00)); // trail
1005 assert_eq!(string.bytes, b"\xED\xB0\x80");
1009 fn wtf8buf_push_wtf8() {
1010 let mut string = Wtf8Buf::from_str("aé");
1011 assert_eq!(string.bytes, b"a\xC3\xA9");
1012 string.push_wtf8(Wtf8::from_str(" 💩"));
1013 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1015 fn w(value: &[u8]) -> &Wtf8 { unsafe { transmute(value) } }
1017 let mut string = Wtf8Buf::new();
1018 string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
1019 string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
1020 assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1022 let mut string = Wtf8Buf::new();
1023 string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
1024 string.push_wtf8(w(b" ")); // not surrogate
1025 string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
1026 assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1028 let mut string = Wtf8Buf::new();
1029 string.push_wtf8(w(b"\xED\xA0\x80")); // lead
1030 string.push_wtf8(w(b"\xED\xAF\xBF")); // lead
1031 assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1033 let mut string = Wtf8Buf::new();
1034 string.push_wtf8(w(b"\xED\xA0\x80")); // lead
1035 string.push_wtf8(w(b"\xEE\x80\x80")); // not surrogate
1036 assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
1038 let mut string = Wtf8Buf::new();
1039 string.push_wtf8(w(b"\xED\x9F\xBF")); // not surrogate
1040 string.push_wtf8(w(b"\xED\xB0\x80")); // trail
1041 assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1043 let mut string = Wtf8Buf::new();
1044 string.push_wtf8(w(b"a")); // not surrogate, < 3 bytes
1045 string.push_wtf8(w(b"\xED\xB0\x80")); // trail
1046 assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
1048 let mut string = Wtf8Buf::new();
1049 string.push_wtf8(w(b"\xED\xB0\x80")); // trail
1050 assert_eq!(string.bytes, b"\xED\xB0\x80");
1054 fn wtf8buf_truncate() {
1055 let mut string = Wtf8Buf::from_str("aé");
1057 assert_eq!(string.bytes, b"a");
1062 fn wtf8buf_truncate_fail_code_point_boundary() {
1063 let mut string = Wtf8Buf::from_str("aé");
1069 fn wtf8buf_truncate_fail_longer() {
1070 let mut string = Wtf8Buf::from_str("aé");
1075 fn wtf8buf_into_string() {
1076 let mut string = Wtf8Buf::from_str("aé 💩");
1077 assert_eq!(string.clone().into_string(), Ok(String::from_str("aé 💩")));
1078 string.push(CodePoint::from_u32(0xD800).unwrap());
1079 assert_eq!(string.clone().into_string(), Err(string));
1083 fn wtf8buf_into_string_lossy() {
1084 let mut string = Wtf8Buf::from_str("aé 💩");
1085 assert_eq!(string.clone().into_string_lossy(), String::from_str("aé 💩"));
1086 string.push(CodePoint::from_u32(0xD800).unwrap());
1087 assert_eq!(string.clone().into_string_lossy(), String::from_str("aé 💩�"));
1091 fn wtf8buf_from_iterator() {
1092 fn f(values: &[u32]) -> Wtf8Buf {
1093 values.iter().map(|&c| CodePoint::from_u32(c).unwrap()).collect::<Wtf8Buf>()
1095 assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1097 assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1098 assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1099 assert_eq!(f(&[0xD800, 0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1100 assert_eq!(f(&[0xD800, 0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1101 assert_eq!(f(&[0xD7FF, 0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1102 assert_eq!(f(&[0x61, 0xDC00]).bytes, b"\x61\xED\xB0\x80");
1103 assert_eq!(f(&[0xDC00]).bytes, b"\xED\xB0\x80");
1107 fn wtf8buf_extend() {
1108 fn e(initial: &[u32], extended: &[u32]) -> Wtf8Buf {
1109 fn c(value: &u32) -> CodePoint { CodePoint::from_u32(*value).unwrap() }
1110 let mut string = initial.iter().map(c).collect::<Wtf8Buf>();
1111 string.extend(extended.iter().map(c));
1115 assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes,
1116 b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1118 assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
1119 assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1120 assert_eq!(e(&[0xD800], &[0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1121 assert_eq!(e(&[0xD800], &[0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1122 assert_eq!(e(&[0xD7FF], &[0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1123 assert_eq!(e(&[0x61], &[0xDC00]).bytes, b"\x61\xED\xB0\x80");
1124 assert_eq!(e(&[], &[0xDC00]).bytes, b"\xED\xB0\x80");
1129 let mut string = Wtf8Buf::from_str("aé 💩");
1130 string.push(CodePoint::from_u32(0xD800).unwrap());
1131 assert_eq!(format!("{:?}", string), r#""aé 💩\u{D800}""#);
1135 fn wtf8buf_as_slice() {
1136 assert_eq!(Wtf8Buf::from_str("aé").as_slice(), Wtf8::from_str("aé"));
1141 let mut string = Wtf8Buf::from_str("aé 💩");
1142 string.push(CodePoint::from_u32(0xD800).unwrap());
1143 assert_eq!(format!("{:?}", string), r#""aé 💩\u{D800}""#);
1147 fn wtf8_from_str() {
1148 assert_eq!(&Wtf8::from_str("").bytes, b"");
1149 assert_eq!(&Wtf8::from_str("aé 💩").bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1154 assert_eq!(Wtf8::from_str("").len(), 0);
1155 assert_eq!(Wtf8::from_str("aé 💩").len(), 8);
1160 assert_eq!(&Wtf8::from_str("aé 💩")[1.. 4].bytes, b"\xC3\xA9 ");
1165 fn wtf8_slice_not_code_point_boundary() {
1166 &Wtf8::from_str("aé 💩")[2.. 4];
1170 fn wtf8_slice_from() {
1171 assert_eq!(&Wtf8::from_str("aé 💩")[1..].bytes, b"\xC3\xA9 \xF0\x9F\x92\xA9");
1176 fn wtf8_slice_from_not_code_point_boundary() {
1177 &Wtf8::from_str("aé 💩")[2..];
1181 fn wtf8_slice_to() {
1182 assert_eq!(&Wtf8::from_str("aé 💩")[..4].bytes, b"a\xC3\xA9 ");
1187 fn wtf8_slice_to_not_code_point_boundary() {
1188 &Wtf8::from_str("aé 💩")[5..];
1192 fn wtf8_ascii_byte_at() {
1193 let slice = Wtf8::from_str("aé 💩");
1194 assert_eq!(slice.ascii_byte_at(0), b'a');
1195 assert_eq!(slice.ascii_byte_at(1), b'\xFF');
1196 assert_eq!(slice.ascii_byte_at(2), b'\xFF');
1197 assert_eq!(slice.ascii_byte_at(3), b' ');
1198 assert_eq!(slice.ascii_byte_at(4), b'\xFF');
1202 fn wtf8_code_point_at() {
1203 let mut string = Wtf8Buf::from_str("aé ");
1204 string.push(CodePoint::from_u32(0xD83D).unwrap());
1205 string.push_char('💩');
1206 assert_eq!(string.code_point_at(0), CodePoint::from_char('a'));
1207 assert_eq!(string.code_point_at(1), CodePoint::from_char('é'));
1208 assert_eq!(string.code_point_at(3), CodePoint::from_char(' '));
1209 assert_eq!(string.code_point_at(4), CodePoint::from_u32(0xD83D).unwrap());
1210 assert_eq!(string.code_point_at(7), CodePoint::from_char('💩'));
1214 fn wtf8_code_point_range_at() {
1215 let mut string = Wtf8Buf::from_str("aé ");
1216 string.push(CodePoint::from_u32(0xD83D).unwrap());
1217 string.push_char('💩');
1218 assert_eq!(string.code_point_range_at(0), (CodePoint::from_char('a'), 1));
1219 assert_eq!(string.code_point_range_at(1), (CodePoint::from_char('é'), 3));
1220 assert_eq!(string.code_point_range_at(3), (CodePoint::from_char(' '), 4));
1221 assert_eq!(string.code_point_range_at(4), (CodePoint::from_u32(0xD83D).unwrap(), 7));
1222 assert_eq!(string.code_point_range_at(7), (CodePoint::from_char('💩'), 11));
1226 fn wtf8_code_points() {
1227 fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
1228 fn cp(string: &Wtf8Buf) -> Vec<Option<char>> {
1229 string.code_points().map(|c| c.to_char()).collect::<Vec<_>>()
1231 let mut string = Wtf8Buf::from_str("é ");
1232 assert_eq!(cp(&string), vec![Some('é'), Some(' ')]);
1233 string.push(c(0xD83D));
1234 assert_eq!(cp(&string), vec![Some('é'), Some(' '), None]);
1235 string.push(c(0xDCA9));
1236 assert_eq!(cp(&string), vec![Some('é'), Some(' '), Some('💩')]);
1241 assert_eq!(Wtf8::from_str("").as_str(), Some(""));
1242 assert_eq!(Wtf8::from_str("aé 💩").as_str(), Some("aé 💩"));
1243 let mut string = Wtf8Buf::new();
1244 string.push(CodePoint::from_u32(0xD800).unwrap());
1245 assert_eq!(string.as_str(), None);
1249 fn wtf8_to_string_lossy() {
1250 assert_eq!(Wtf8::from_str("").to_string_lossy(), Cow::Borrowed(""));
1251 assert_eq!(Wtf8::from_str("aé 💩").to_string_lossy(), Cow::Borrowed("aé 💩"));
1252 let mut string = Wtf8Buf::from_str("aé 💩");
1253 string.push(CodePoint::from_u32(0xD800).unwrap());
1254 let expected: CowString = Cow::Owned(String::from_str("aé 💩�"));
1255 assert_eq!(string.to_string_lossy(), expected);
1259 fn wtf8_encode_wide() {
1260 let mut string = Wtf8Buf::from_str("aé ");
1261 string.push(CodePoint::from_u32(0xD83D).unwrap());
1262 string.push_char('💩');
1263 assert_eq!(string.encode_wide().collect::<Vec<_>>(),
1264 vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]);