]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/wtf8.rs
Auto merge of #43651 - petrochenkov:foreign-life, r=eddyb
[rust.git] / src / libstd / sys_common / wtf8.rs
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.
4 //
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.
10
11 //! Implementation of [the WTF-8 encoding](https://simonsapin.github.io/wtf-8/).
12 //!
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.
16 //!
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
20 //! of WTF-8 strings,
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.
23
24 // this module is imported from @SimonSapin's repo and has tons of dead code on
25 // unix (it's mostly used on windows), so don't worry about dead code here.
26 #![allow(dead_code)]
27
28 use core::str::next_code_point;
29
30 use ascii::*;
31 use borrow::Cow;
32 use char;
33 use fmt;
34 use hash::{Hash, Hasher};
35 use iter::FromIterator;
36 use mem;
37 use ops;
38 use slice;
39 use str;
40 use sys_common::AsInner;
41
42 const UTF8_REPLACEMENT_CHARACTER: &'static str = "\u{FFFD}";
43
44 /// A Unicode code point: from U+0000 to U+10FFFF.
45 ///
46 /// Compare with the `char` type,
47 /// which represents a Unicode scalar value:
48 /// a code point that is not a surrogate (U+D800 to U+DFFF).
49 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
50 pub struct CodePoint {
51     value: u32
52 }
53
54 /// Format the code point as `U+` followed by four to six hexadecimal digits.
55 /// Example: `U+1F4A9`
56 impl fmt::Debug for CodePoint {
57     #[inline]
58     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
59         write!(formatter, "U+{:04X}", self.value)
60     }
61 }
62
63 impl CodePoint {
64     /// Unsafely creates a new `CodePoint` without checking the value.
65     ///
66     /// Only use when `value` is known to be less than or equal to 0x10FFFF.
67     #[inline]
68     pub unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
69         CodePoint { value: value }
70     }
71
72     /// Creates a new `CodePoint` if the value is a valid code point.
73     ///
74     /// Returns `None` if `value` is above 0x10FFFF.
75     #[inline]
76     pub fn from_u32(value: u32) -> Option<CodePoint> {
77         match value {
78             0 ... 0x10FFFF => Some(CodePoint { value: value }),
79             _ => None
80         }
81     }
82
83     /// Creates a new `CodePoint` from a `char`.
84     ///
85     /// Since all Unicode scalar values are code points, this always succeeds.
86     #[inline]
87     pub fn from_char(value: char) -> CodePoint {
88         CodePoint { value: value as u32 }
89     }
90
91     /// Returns the numeric value of the code point.
92     #[inline]
93     pub fn to_u32(&self) -> u32 {
94         self.value
95     }
96
97     /// Optionally returns a Unicode scalar value for the code point.
98     ///
99     /// Returns `None` if the code point is a surrogate (from U+D800 to U+DFFF).
100     #[inline]
101     pub fn to_char(&self) -> Option<char> {
102         match self.value {
103             0xD800 ... 0xDFFF => None,
104             _ => Some(unsafe { char::from_u32_unchecked(self.value) })
105         }
106     }
107
108     /// Returns a Unicode scalar value for the code point.
109     ///
110     /// Returns `'\u{FFFD}'` (the replacement character “�”)
111     /// if the code point is a surrogate (from U+D800 to U+DFFF).
112     #[inline]
113     pub fn to_char_lossy(&self) -> char {
114         self.to_char().unwrap_or('\u{FFFD}')
115     }
116 }
117
118 /// An owned, growable string of well-formed WTF-8 data.
119 ///
120 /// Similar to `String`, but can additionally contain surrogate code points
121 /// if they’re not in a surrogate pair.
122 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
123 pub struct Wtf8Buf {
124     bytes: Vec<u8>
125 }
126
127 impl ops::Deref for Wtf8Buf {
128     type Target = Wtf8;
129
130     fn deref(&self) -> &Wtf8 {
131         self.as_slice()
132     }
133 }
134
135 /// Format the string with double quotes,
136 /// and surrogates as `\u` followed by four hexadecimal digits.
137 /// Example: `"a\u{D800}"` for a string with code points [U+0061, U+D800]
138 impl fmt::Debug for Wtf8Buf {
139     #[inline]
140     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
141         fmt::Debug::fmt(&**self, formatter)
142     }
143 }
144
145 impl Wtf8Buf {
146     /// Creates a new, empty WTF-8 string.
147     #[inline]
148     pub fn new() -> Wtf8Buf {
149         Wtf8Buf { bytes: Vec::new() }
150     }
151
152     /// Creates a new, empty WTF-8 string with pre-allocated capacity for `n` bytes.
153     #[inline]
154     pub fn with_capacity(n: usize) -> Wtf8Buf {
155         Wtf8Buf { bytes: Vec::with_capacity(n) }
156     }
157
158     /// Creates a WTF-8 string from a UTF-8 `String`.
159     ///
160     /// This takes ownership of the `String` and does not copy.
161     ///
162     /// Since WTF-8 is a superset of UTF-8, this always succeeds.
163     #[inline]
164     pub fn from_string(string: String) -> Wtf8Buf {
165         Wtf8Buf { bytes: string.into_bytes() }
166     }
167
168     /// Creates a WTF-8 string from a UTF-8 `&str` slice.
169     ///
170     /// This copies the content of the slice.
171     ///
172     /// Since WTF-8 is a superset of UTF-8, this always succeeds.
173     #[inline]
174     pub fn from_str(str: &str) -> Wtf8Buf {
175         Wtf8Buf { bytes: <[_]>::to_vec(str.as_bytes()) }
176     }
177
178     pub fn clear(&mut self) {
179         self.bytes.clear()
180     }
181
182     /// Creates a WTF-8 string from a potentially ill-formed UTF-16 slice of 16-bit code units.
183     ///
184     /// This is lossless: calling `.encode_wide()` on the resulting string
185     /// will always return the original code units.
186     pub fn from_wide(v: &[u16]) -> Wtf8Buf {
187         let mut string = Wtf8Buf::with_capacity(v.len());
188         for item in char::decode_utf16(v.iter().cloned()) {
189             match item {
190                 Ok(ch) => string.push_char(ch),
191                 Err(surrogate) => {
192                     let surrogate = surrogate.unpaired_surrogate();
193                     // Surrogates are known to be in the code point range.
194                     let code_point = unsafe {
195                         CodePoint::from_u32_unchecked(surrogate as u32)
196                     };
197                     // Skip the WTF-8 concatenation check,
198                     // surrogate pairs are already decoded by decode_utf16
199                     string.push_code_point_unchecked(code_point)
200                 }
201             }
202         }
203         string
204     }
205
206     /// Copied from String::push
207     /// This does **not** include the WTF-8 concatenation check.
208     fn push_code_point_unchecked(&mut self, code_point: CodePoint) {
209         let c = unsafe {
210             char::from_u32_unchecked(code_point.value)
211         };
212         let mut bytes = [0; 4];
213         let bytes = c.encode_utf8(&mut bytes).as_bytes();
214         self.bytes.extend_from_slice(bytes)
215     }
216
217     #[inline]
218     pub fn as_slice(&self) -> &Wtf8 {
219         unsafe { Wtf8::from_bytes_unchecked(&self.bytes) }
220     }
221
222     /// Reserves capacity for at least `additional` more bytes to be inserted
223     /// in the given `Wtf8Buf`.
224     /// The collection may reserve more space to avoid frequent reallocations.
225     ///
226     /// # Panics
227     ///
228     /// Panics if the new capacity overflows `usize`.
229     #[inline]
230     pub fn reserve(&mut self, additional: usize) {
231         self.bytes.reserve(additional)
232     }
233
234     #[inline]
235     pub fn reserve_exact(&mut self, additional: usize) {
236         self.bytes.reserve_exact(additional)
237     }
238
239     #[inline]
240     pub fn shrink_to_fit(&mut self) {
241         self.bytes.shrink_to_fit()
242     }
243
244     /// Returns the number of bytes that this string buffer can hold without reallocating.
245     #[inline]
246     pub fn capacity(&self) -> usize {
247         self.bytes.capacity()
248     }
249
250     /// Append a UTF-8 slice at the end of the string.
251     #[inline]
252     pub fn push_str(&mut self, other: &str) {
253         self.bytes.extend_from_slice(other.as_bytes())
254     }
255
256     /// Append a WTF-8 slice at the end of the string.
257     ///
258     /// This replaces newly paired surrogates at the boundary
259     /// with a supplementary code point,
260     /// like concatenating ill-formed UTF-16 strings effectively would.
261     #[inline]
262     pub fn push_wtf8(&mut self, other: &Wtf8) {
263         match ((&*self).final_lead_surrogate(), other.initial_trail_surrogate()) {
264             // Replace newly paired surrogates by a supplementary code point.
265             (Some(lead), Some(trail)) => {
266                 let len_without_lead_surrogate = self.len() - 3;
267                 self.bytes.truncate(len_without_lead_surrogate);
268                 let other_without_trail_surrogate = &other.bytes[3..];
269                 // 4 bytes for the supplementary code point
270                 self.bytes.reserve(4 + other_without_trail_surrogate.len());
271                 self.push_char(decode_surrogate_pair(lead, trail));
272                 self.bytes.extend_from_slice(other_without_trail_surrogate);
273             }
274             _ => self.bytes.extend_from_slice(&other.bytes)
275         }
276     }
277
278     /// Append a Unicode scalar value at the end of the string.
279     #[inline]
280     pub fn push_char(&mut self, c: char) {
281         self.push_code_point_unchecked(CodePoint::from_char(c))
282     }
283
284     /// Append a code point at the end of the string.
285     ///
286     /// This replaces newly paired surrogates at the boundary
287     /// with a supplementary code point,
288     /// like concatenating ill-formed UTF-16 strings effectively would.
289     #[inline]
290     pub fn push(&mut self, code_point: CodePoint) {
291         if let trail @ 0xDC00...0xDFFF = code_point.to_u32() {
292             if let Some(lead) = (&*self).final_lead_surrogate() {
293                 let len_without_lead_surrogate = self.len() - 3;
294                 self.bytes.truncate(len_without_lead_surrogate);
295                 self.push_char(decode_surrogate_pair(lead, trail as u16));
296                 return
297             }
298         }
299
300         // No newly paired surrogates at the boundary.
301         self.push_code_point_unchecked(code_point)
302     }
303
304     /// Shortens a string to the specified length.
305     ///
306     /// # Panics
307     ///
308     /// Panics if `new_len` > current length,
309     /// or if `new_len` is not a code point boundary.
310     #[inline]
311     pub fn truncate(&mut self, new_len: usize) {
312         assert!(is_code_point_boundary(self, new_len));
313         self.bytes.truncate(new_len)
314     }
315
316     /// Consumes the WTF-8 string and tries to convert it to UTF-8.
317     ///
318     /// This does not copy the data.
319     ///
320     /// If the contents are not well-formed UTF-8
321     /// (that is, if the string contains surrogates),
322     /// the original WTF-8 string is returned instead.
323     pub fn into_string(self) -> Result<String, Wtf8Buf> {
324         match self.next_surrogate(0) {
325             None => Ok(unsafe { String::from_utf8_unchecked(self.bytes) }),
326             Some(_) => Err(self),
327         }
328     }
329
330     /// Consumes the WTF-8 string and converts it lossily to UTF-8.
331     ///
332     /// This does not copy the data (but may overwrite parts of it in place).
333     ///
334     /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”)
335     pub fn into_string_lossy(mut self) -> String {
336         let mut pos = 0;
337         loop {
338             match self.next_surrogate(pos) {
339                 Some((surrogate_pos, _)) => {
340                     pos = surrogate_pos + 3;
341                     self.bytes[surrogate_pos..pos]
342                         .copy_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
343                 },
344                 None => return unsafe { String::from_utf8_unchecked(self.bytes) }
345             }
346         }
347     }
348
349     /// Converts this `Wtf8Buf` into a boxed `Wtf8`.
350     #[inline]
351     pub fn into_box(self) -> Box<Wtf8> {
352         unsafe { mem::transmute(self.bytes.into_boxed_slice()) }
353     }
354
355     /// Converts a `Box<Wtf8>` into a `Wtf8Buf`.
356     pub fn from_box(boxed: Box<Wtf8>) -> Wtf8Buf {
357         let bytes: Box<[u8]> = unsafe { mem::transmute(boxed) };
358         Wtf8Buf { bytes: bytes.into_vec() }
359     }
360 }
361
362 /// Create a new WTF-8 string from an iterator of code points.
363 ///
364 /// This replaces surrogate code point pairs with supplementary code points,
365 /// like concatenating ill-formed UTF-16 strings effectively would.
366 impl FromIterator<CodePoint> for Wtf8Buf {
367     fn from_iter<T: IntoIterator<Item=CodePoint>>(iter: T) -> Wtf8Buf {
368         let mut string = Wtf8Buf::new();
369         string.extend(iter);
370         string
371     }
372 }
373
374 /// Append code points from an iterator to the string.
375 ///
376 /// This replaces surrogate code point pairs with supplementary code points,
377 /// like concatenating ill-formed UTF-16 strings effectively would.
378 impl Extend<CodePoint> for Wtf8Buf {
379     fn extend<T: IntoIterator<Item=CodePoint>>(&mut self, iter: T) {
380         let iterator = iter.into_iter();
381         let (low, _high) = iterator.size_hint();
382         // Lower bound of one byte per code point (ASCII only)
383         self.bytes.reserve(low);
384         for code_point in iterator {
385             self.push(code_point);
386         }
387     }
388 }
389
390 /// A borrowed slice of well-formed WTF-8 data.
391 ///
392 /// Similar to `&str`, but can additionally contain surrogate code points
393 /// if they’re not in a surrogate pair.
394 #[derive(Eq, Ord, PartialEq, PartialOrd)]
395 pub struct Wtf8 {
396     bytes: [u8]
397 }
398
399 impl AsInner<[u8]> for Wtf8 {
400     fn as_inner(&self) -> &[u8] { &self.bytes }
401 }
402
403 /// Format the slice with double quotes,
404 /// and surrogates as `\u` followed by four hexadecimal digits.
405 /// Example: `"a\u{D800}"` for a slice with code points [U+0061, U+D800]
406 impl fmt::Debug for Wtf8 {
407     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
408         fn write_str_escaped(f: &mut fmt::Formatter, s: &str) -> fmt::Result {
409             use fmt::Write;
410             for c in s.chars().flat_map(|c| c.escape_debug()) {
411                 f.write_char(c)?
412             }
413             Ok(())
414         }
415
416         formatter.write_str("\"")?;
417         let mut pos = 0;
418         loop {
419             match self.next_surrogate(pos) {
420                 None => break,
421                 Some((surrogate_pos, surrogate)) => {
422                     write_str_escaped(
423                         formatter,
424                         unsafe { str::from_utf8_unchecked(
425                             &self.bytes[pos .. surrogate_pos]
426                         )},
427                     )?;
428                     write!(formatter, "\\u{{{:x}}}", surrogate)?;
429                     pos = surrogate_pos + 3;
430                 }
431             }
432         }
433         write_str_escaped(
434             formatter,
435             unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) },
436         )?;
437         formatter.write_str("\"")
438     }
439 }
440
441 impl fmt::Display for Wtf8 {
442     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
443         let wtf8_bytes = &self.bytes;
444         let mut pos = 0;
445         loop {
446             match self.next_surrogate(pos) {
447                 Some((surrogate_pos, _)) => {
448                     formatter.write_str(unsafe {
449                         str::from_utf8_unchecked(&wtf8_bytes[pos .. surrogate_pos])
450                     })?;
451                     formatter.write_str(UTF8_REPLACEMENT_CHARACTER)?;
452                     pos = surrogate_pos + 3;
453                 },
454                 None => {
455                     formatter.write_str(unsafe {
456                         str::from_utf8_unchecked(&wtf8_bytes[pos..])
457                     })?;
458                     return Ok(());
459                 }
460             }
461         }
462     }
463 }
464
465 impl Wtf8 {
466     /// Creates a WTF-8 slice from a UTF-8 `&str` slice.
467     ///
468     /// Since WTF-8 is a superset of UTF-8, this always succeeds.
469     #[inline]
470     pub fn from_str(value: &str) -> &Wtf8 {
471         unsafe { Wtf8::from_bytes_unchecked(value.as_bytes()) }
472     }
473
474     /// Creates a WTF-8 slice from a WTF-8 byte slice.
475     ///
476     /// Since the byte slice is not checked for valid WTF-8, this functions is
477     /// marked unsafe.
478     #[inline]
479     unsafe fn from_bytes_unchecked(value: &[u8]) -> &Wtf8 {
480         mem::transmute(value)
481     }
482
483     /// Returns the length, in WTF-8 bytes.
484     #[inline]
485     pub fn len(&self) -> usize {
486         self.bytes.len()
487     }
488
489     #[inline]
490     pub fn is_empty(&self) -> bool {
491         self.bytes.is_empty()
492     }
493
494     /// Returns the code point at `position` if it is in the ASCII range,
495     /// or `b'\xFF' otherwise.
496     ///
497     /// # Panics
498     ///
499     /// Panics if `position` is beyond the end of the string.
500     #[inline]
501     pub fn ascii_byte_at(&self, position: usize) -> u8 {
502         match self.bytes[position] {
503             ascii_byte @ 0x00 ... 0x7F => ascii_byte,
504             _ => 0xFF
505         }
506     }
507
508     /// Returns an iterator for the string’s code points.
509     #[inline]
510     pub fn code_points(&self) -> Wtf8CodePoints {
511         Wtf8CodePoints { bytes: self.bytes.iter() }
512     }
513
514     /// Tries to convert the string to UTF-8 and return a `&str` slice.
515     ///
516     /// Returns `None` if the string contains surrogates.
517     ///
518     /// This does not copy the data.
519     #[inline]
520     pub fn as_str(&self) -> Option<&str> {
521         // Well-formed WTF-8 is also well-formed UTF-8
522         // if and only if it contains no surrogate.
523         match self.next_surrogate(0) {
524             None => Some(unsafe { str::from_utf8_unchecked(&self.bytes) }),
525             Some(_) => None,
526         }
527     }
528
529     /// Lossily converts the string to UTF-8.
530     /// Returns a UTF-8 `&str` slice if the contents are well-formed in UTF-8.
531     ///
532     /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”).
533     ///
534     /// This only copies the data if necessary (if it contains any surrogate).
535     pub fn to_string_lossy(&self) -> Cow<str> {
536         let surrogate_pos = match self.next_surrogate(0) {
537             None => return Cow::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) }),
538             Some((pos, _)) => pos,
539         };
540         let wtf8_bytes = &self.bytes;
541         let mut utf8_bytes = Vec::with_capacity(self.len());
542         utf8_bytes.extend_from_slice(&wtf8_bytes[..surrogate_pos]);
543         utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
544         let mut pos = surrogate_pos + 3;
545         loop {
546             match self.next_surrogate(pos) {
547                 Some((surrogate_pos, _)) => {
548                     utf8_bytes.extend_from_slice(&wtf8_bytes[pos .. surrogate_pos]);
549                     utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
550                     pos = surrogate_pos + 3;
551                 },
552                 None => {
553                     utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]);
554                     return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) })
555                 }
556             }
557         }
558     }
559
560     /// Converts the WTF-8 string to potentially ill-formed UTF-16
561     /// and return an iterator of 16-bit code units.
562     ///
563     /// This is lossless:
564     /// calling `Wtf8Buf::from_ill_formed_utf16` on the resulting code units
565     /// would always return the original WTF-8 string.
566     #[inline]
567     pub fn encode_wide(&self) -> EncodeWide {
568         EncodeWide { code_points: self.code_points(), extra: 0 }
569     }
570
571     #[inline]
572     fn next_surrogate(&self, mut pos: usize) -> Option<(usize, u16)> {
573         let mut iter = self.bytes[pos..].iter();
574         loop {
575             let b = match iter.next() {
576                 None => return None,
577                 Some(&b) => b,
578             };
579             if b < 0x80 {
580                 pos += 1;
581             } else if b < 0xE0 {
582                 iter.next();
583                 pos += 2;
584             } else if b == 0xED {
585                 match (iter.next(), iter.next()) {
586                     (Some(&b2), Some(&b3)) if b2 >= 0xA0 => {
587                         return Some((pos, decode_surrogate(b2, b3)))
588                     }
589                     _ => pos += 3
590                 }
591             } else if b < 0xF0 {
592                 iter.next();
593                 iter.next();
594                 pos += 3;
595             } else {
596                 iter.next();
597                 iter.next();
598                 iter.next();
599                 pos += 4;
600             }
601         }
602     }
603
604     #[inline]
605     fn final_lead_surrogate(&self) -> Option<u16> {
606         let len = self.len();
607         if len < 3 {
608             return None
609         }
610         match &self.bytes[(len - 3)..] {
611             &[0xED, b2 @ 0xA0...0xAF, b3] => Some(decode_surrogate(b2, b3)),
612             _ => None
613         }
614     }
615
616     #[inline]
617     fn initial_trail_surrogate(&self) -> Option<u16> {
618         let len = self.len();
619         if len < 3 {
620             return None
621         }
622         match &self.bytes[..3] {
623             &[0xED, b2 @ 0xB0...0xBF, b3] => Some(decode_surrogate(b2, b3)),
624             _ => None
625         }
626     }
627
628     /// Boxes this `Wtf8`.
629     #[inline]
630     pub fn into_box(&self) -> Box<Wtf8> {
631         let boxed: Box<[u8]> = self.bytes.into();
632         unsafe { mem::transmute(boxed) }
633     }
634
635     /// Creates a boxed, empty `Wtf8`.
636     pub fn empty_box() -> Box<Wtf8> {
637         let boxed: Box<[u8]> = Default::default();
638         unsafe { mem::transmute(boxed) }
639     }
640 }
641
642
643 /// Return a slice of the given string for the byte range [`begin`..`end`).
644 ///
645 /// # Panics
646 ///
647 /// Panics when `begin` and `end` do not point to code point boundaries,
648 /// or point beyond the end of the string.
649 impl ops::Index<ops::Range<usize>> for Wtf8 {
650     type Output = Wtf8;
651
652     #[inline]
653     fn index(&self, range: ops::Range<usize>) -> &Wtf8 {
654         // is_code_point_boundary checks that the index is in [0, .len()]
655         if range.start <= range.end &&
656            is_code_point_boundary(self, range.start) &&
657            is_code_point_boundary(self, range.end) {
658             unsafe { slice_unchecked(self, range.start, range.end) }
659         } else {
660             slice_error_fail(self, range.start, range.end)
661         }
662     }
663 }
664
665 /// Return a slice of the given string from byte `begin` to its end.
666 ///
667 /// # Panics
668 ///
669 /// Panics when `begin` is not at a code point boundary,
670 /// or is beyond the end of the string.
671 impl ops::Index<ops::RangeFrom<usize>> for Wtf8 {
672     type Output = Wtf8;
673
674     #[inline]
675     fn index(&self, range: ops::RangeFrom<usize>) -> &Wtf8 {
676         // is_code_point_boundary checks that the index is in [0, .len()]
677         if is_code_point_boundary(self, range.start) {
678             unsafe { slice_unchecked(self, range.start, self.len()) }
679         } else {
680             slice_error_fail(self, range.start, self.len())
681         }
682     }
683 }
684
685 /// Return a slice of the given string from its beginning to byte `end`.
686 ///
687 /// # Panics
688 ///
689 /// Panics when `end` is not at a code point boundary,
690 /// or is beyond the end of the string.
691 impl ops::Index<ops::RangeTo<usize>> for Wtf8 {
692     type Output = Wtf8;
693
694     #[inline]
695     fn index(&self, range: ops::RangeTo<usize>) -> &Wtf8 {
696         // is_code_point_boundary checks that the index is in [0, .len()]
697         if is_code_point_boundary(self, range.end) {
698             unsafe { slice_unchecked(self, 0, range.end) }
699         } else {
700             slice_error_fail(self, 0, range.end)
701         }
702     }
703 }
704
705 impl ops::Index<ops::RangeFull> for Wtf8 {
706     type Output = Wtf8;
707
708     #[inline]
709     fn index(&self, _range: ops::RangeFull) -> &Wtf8 {
710         self
711     }
712 }
713
714 #[inline]
715 fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 {
716     // The first byte is assumed to be 0xED
717     0xD800 | (second_byte as u16 & 0x3F) << 6 | third_byte as u16 & 0x3F
718 }
719
720 #[inline]
721 fn decode_surrogate_pair(lead: u16, trail: u16) -> char {
722     let code_point = 0x10000 + ((((lead - 0xD800) as u32) << 10) | (trail - 0xDC00) as u32);
723     unsafe { char::from_u32_unchecked(code_point) }
724 }
725
726 /// Copied from core::str::StrPrelude::is_char_boundary
727 #[inline]
728 pub fn is_code_point_boundary(slice: &Wtf8, index: usize) -> bool {
729     if index == slice.len() { return true; }
730     match slice.bytes.get(index) {
731         None => false,
732         Some(&b) => b < 128 || b >= 192,
733     }
734 }
735
736 /// Copied from core::str::raw::slice_unchecked
737 #[inline]
738 pub unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 {
739     // memory layout of an &[u8] and &Wtf8 are the same
740     Wtf8::from_bytes_unchecked(slice::from_raw_parts(
741         s.bytes.as_ptr().offset(begin as isize),
742         end - begin
743     ))
744 }
745
746 /// Copied from core::str::raw::slice_error_fail
747 #[inline(never)]
748 pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! {
749     assert!(begin <= end);
750     panic!("index {} and/or {} in `{:?}` do not lie on character boundary",
751           begin, end, s);
752 }
753
754 /// Iterator for the code points of a WTF-8 string.
755 ///
756 /// Created with the method `.code_points()`.
757 #[derive(Clone)]
758 pub struct Wtf8CodePoints<'a> {
759     bytes: slice::Iter<'a, u8>
760 }
761
762 impl<'a> Iterator for Wtf8CodePoints<'a> {
763     type Item = CodePoint;
764
765     #[inline]
766     fn next(&mut self) -> Option<CodePoint> {
767         next_code_point(&mut self.bytes).map(|c| CodePoint { value: c })
768     }
769
770     #[inline]
771     fn size_hint(&self) -> (usize, Option<usize>) {
772         let len = self.bytes.len();
773         (len.saturating_add(3) / 4, Some(len))
774     }
775 }
776
777 /// Generates a wide character sequence for potentially ill-formed UTF-16.
778 #[stable(feature = "rust1", since = "1.0.0")]
779 #[derive(Clone)]
780 pub struct EncodeWide<'a> {
781     code_points: Wtf8CodePoints<'a>,
782     extra: u16
783 }
784
785 // Copied from libunicode/u_str.rs
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl<'a> Iterator for EncodeWide<'a> {
788     type Item = u16;
789
790     #[inline]
791     fn next(&mut self) -> Option<u16> {
792         if self.extra != 0 {
793             let tmp = self.extra;
794             self.extra = 0;
795             return Some(tmp);
796         }
797
798         let mut buf = [0; 2];
799         self.code_points.next().map(|code_point| {
800             let c = unsafe {
801                 char::from_u32_unchecked(code_point.value)
802             };
803             let n = c.encode_utf16(&mut buf).len();
804             if n == 2 {
805                 self.extra = buf[1];
806             }
807             buf[0]
808         })
809     }
810
811     #[inline]
812     fn size_hint(&self) -> (usize, Option<usize>) {
813         let (low, high) = self.code_points.size_hint();
814         // every code point gets either one u16 or two u16,
815         // so this iterator is between 1 or 2 times as
816         // long as the underlying iterator.
817         (low, high.and_then(|n| n.checked_mul(2)))
818     }
819 }
820
821 impl Hash for CodePoint {
822     #[inline]
823     fn hash<H: Hasher>(&self, state: &mut H) {
824         self.value.hash(state)
825     }
826 }
827
828 impl Hash for Wtf8Buf {
829     #[inline]
830     fn hash<H: Hasher>(&self, state: &mut H) {
831         state.write(&self.bytes);
832         0xfeu8.hash(state)
833     }
834 }
835
836 impl Hash for Wtf8 {
837     #[inline]
838     fn hash<H: Hasher>(&self, state: &mut H) {
839         state.write(&self.bytes);
840         0xfeu8.hash(state)
841     }
842 }
843
844 impl AsciiExt for Wtf8 {
845     type Owned = Wtf8Buf;
846
847     fn is_ascii(&self) -> bool {
848         self.bytes.is_ascii()
849     }
850     fn to_ascii_uppercase(&self) -> Wtf8Buf {
851         Wtf8Buf { bytes: self.bytes.to_ascii_uppercase() }
852     }
853     fn to_ascii_lowercase(&self) -> Wtf8Buf {
854         Wtf8Buf { bytes: self.bytes.to_ascii_lowercase() }
855     }
856     fn eq_ignore_ascii_case(&self, other: &Wtf8) -> bool {
857         self.bytes.eq_ignore_ascii_case(&other.bytes)
858     }
859
860     fn make_ascii_uppercase(&mut self) { self.bytes.make_ascii_uppercase() }
861     fn make_ascii_lowercase(&mut self) { self.bytes.make_ascii_lowercase() }
862 }
863
864 #[cfg(test)]
865 mod tests {
866     use borrow::Cow;
867     use super::*;
868
869     #[test]
870     fn code_point_from_u32() {
871         assert!(CodePoint::from_u32(0).is_some());
872         assert!(CodePoint::from_u32(0xD800).is_some());
873         assert!(CodePoint::from_u32(0x10FFFF).is_some());
874         assert!(CodePoint::from_u32(0x110000).is_none());
875     }
876
877     #[test]
878     fn code_point_to_u32() {
879         fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
880         assert_eq!(c(0).to_u32(), 0);
881         assert_eq!(c(0xD800).to_u32(), 0xD800);
882         assert_eq!(c(0x10FFFF).to_u32(), 0x10FFFF);
883     }
884
885     #[test]
886     fn code_point_from_char() {
887         assert_eq!(CodePoint::from_char('a').to_u32(), 0x61);
888         assert_eq!(CodePoint::from_char('💩').to_u32(), 0x1F4A9);
889     }
890
891     #[test]
892     fn code_point_to_string() {
893         assert_eq!(format!("{:?}", CodePoint::from_char('a')), "U+0061");
894         assert_eq!(format!("{:?}", CodePoint::from_char('💩')), "U+1F4A9");
895     }
896
897     #[test]
898     fn code_point_to_char() {
899         fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
900         assert_eq!(c(0x61).to_char(), Some('a'));
901         assert_eq!(c(0x1F4A9).to_char(), Some('💩'));
902         assert_eq!(c(0xD800).to_char(), None);
903     }
904
905     #[test]
906     fn code_point_to_char_lossy() {
907         fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
908         assert_eq!(c(0x61).to_char_lossy(), 'a');
909         assert_eq!(c(0x1F4A9).to_char_lossy(), '💩');
910         assert_eq!(c(0xD800).to_char_lossy(), '\u{FFFD}');
911     }
912
913     #[test]
914     fn wtf8buf_new() {
915         assert_eq!(Wtf8Buf::new().bytes, b"");
916     }
917
918     #[test]
919     fn wtf8buf_from_str() {
920         assert_eq!(Wtf8Buf::from_str("").bytes, b"");
921         assert_eq!(Wtf8Buf::from_str("aé 💩").bytes,
922                    b"a\xC3\xA9 \xF0\x9F\x92\xA9");
923     }
924
925     #[test]
926     fn wtf8buf_from_string() {
927         assert_eq!(Wtf8Buf::from_string(String::from("")).bytes, b"");
928         assert_eq!(Wtf8Buf::from_string(String::from("aé 💩")).bytes,
929                    b"a\xC3\xA9 \xF0\x9F\x92\xA9");
930     }
931
932     #[test]
933     fn wtf8buf_from_wide() {
934         assert_eq!(Wtf8Buf::from_wide(&[]).bytes, b"");
935         assert_eq!(Wtf8Buf::from_wide(
936                       &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes,
937                    b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9");
938     }
939
940     #[test]
941     fn wtf8buf_push_str() {
942         let mut string = Wtf8Buf::new();
943         assert_eq!(string.bytes, b"");
944         string.push_str("aé 💩");
945         assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
946     }
947
948     #[test]
949     fn wtf8buf_push_char() {
950         let mut string = Wtf8Buf::from_str("aé ");
951         assert_eq!(string.bytes, b"a\xC3\xA9 ");
952         string.push_char('💩');
953         assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
954     }
955
956     #[test]
957     fn wtf8buf_push() {
958         let mut string = Wtf8Buf::from_str("aé ");
959         assert_eq!(string.bytes, b"a\xC3\xA9 ");
960         string.push(CodePoint::from_char('💩'));
961         assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
962
963         fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
964
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!
969
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");
975
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");
980
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");
985
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");
990
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");
995
996         let mut string = Wtf8Buf::new();
997         string.push(c(0xDC00));  // trail
998         assert_eq!(string.bytes, b"\xED\xB0\x80");
999     }
1000
1001     #[test]
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");
1007
1008         fn w(v: &[u8]) -> &Wtf8 { unsafe { Wtf8::from_bytes_unchecked(v) } }
1009
1010         let mut string = Wtf8Buf::new();
1011         string.push_wtf8(w(b"\xED\xA0\xBD"));  // lead
1012         string.push_wtf8(w(b"\xED\xB2\xA9"));  // trail
1013         assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9");  // Magic!
1014
1015         let mut string = Wtf8Buf::new();
1016         string.push_wtf8(w(b"\xED\xA0\xBD"));  // lead
1017         string.push_wtf8(w(b" "));  // not surrogate
1018         string.push_wtf8(w(b"\xED\xB2\xA9"));  // trail
1019         assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1020
1021         let mut string = Wtf8Buf::new();
1022         string.push_wtf8(w(b"\xED\xA0\x80"));  // lead
1023         string.push_wtf8(w(b"\xED\xAF\xBF"));  // lead
1024         assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1025
1026         let mut string = Wtf8Buf::new();
1027         string.push_wtf8(w(b"\xED\xA0\x80"));  // lead
1028         string.push_wtf8(w(b"\xEE\x80\x80"));  // not surrogate
1029         assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
1030
1031         let mut string = Wtf8Buf::new();
1032         string.push_wtf8(w(b"\xED\x9F\xBF"));  // not surrogate
1033         string.push_wtf8(w(b"\xED\xB0\x80"));  // trail
1034         assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1035
1036         let mut string = Wtf8Buf::new();
1037         string.push_wtf8(w(b"a"));  // not surrogate, < 3 bytes
1038         string.push_wtf8(w(b"\xED\xB0\x80"));  // trail
1039         assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
1040
1041         let mut string = Wtf8Buf::new();
1042         string.push_wtf8(w(b"\xED\xB0\x80"));  // trail
1043         assert_eq!(string.bytes, b"\xED\xB0\x80");
1044     }
1045
1046     #[test]
1047     fn wtf8buf_truncate() {
1048         let mut string = Wtf8Buf::from_str("aé");
1049         string.truncate(1);
1050         assert_eq!(string.bytes, b"a");
1051     }
1052
1053     #[test]
1054     #[should_panic]
1055     fn wtf8buf_truncate_fail_code_point_boundary() {
1056         let mut string = Wtf8Buf::from_str("aé");
1057         string.truncate(2);
1058     }
1059
1060     #[test]
1061     #[should_panic]
1062     fn wtf8buf_truncate_fail_longer() {
1063         let mut string = Wtf8Buf::from_str("aé");
1064         string.truncate(4);
1065     }
1066
1067     #[test]
1068     fn wtf8buf_into_string() {
1069         let mut string = Wtf8Buf::from_str("aé 💩");
1070         assert_eq!(string.clone().into_string(), Ok(String::from("aé 💩")));
1071         string.push(CodePoint::from_u32(0xD800).unwrap());
1072         assert_eq!(string.clone().into_string(), Err(string));
1073     }
1074
1075     #[test]
1076     fn wtf8buf_into_string_lossy() {
1077         let mut string = Wtf8Buf::from_str("aé 💩");
1078         assert_eq!(string.clone().into_string_lossy(), String::from("aé 💩"));
1079         string.push(CodePoint::from_u32(0xD800).unwrap());
1080         assert_eq!(string.clone().into_string_lossy(), String::from("aé 💩�"));
1081     }
1082
1083     #[test]
1084     fn wtf8buf_from_iterator() {
1085         fn f(values: &[u32]) -> Wtf8Buf {
1086             values.iter().map(|&c| CodePoint::from_u32(c).unwrap()).collect::<Wtf8Buf>()
1087         }
1088         assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1089
1090         assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9");  // Magic!
1091         assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1092         assert_eq!(f(&[0xD800, 0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1093         assert_eq!(f(&[0xD800, 0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1094         assert_eq!(f(&[0xD7FF, 0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1095         assert_eq!(f(&[0x61, 0xDC00]).bytes, b"\x61\xED\xB0\x80");
1096         assert_eq!(f(&[0xDC00]).bytes, b"\xED\xB0\x80");
1097     }
1098
1099     #[test]
1100     fn wtf8buf_extend() {
1101         fn e(initial: &[u32], extended: &[u32]) -> Wtf8Buf {
1102             fn c(value: &u32) -> CodePoint { CodePoint::from_u32(*value).unwrap() }
1103             let mut string = initial.iter().map(c).collect::<Wtf8Buf>();
1104             string.extend(extended.iter().map(c));
1105             string
1106         }
1107
1108         assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes,
1109                    b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1110
1111         assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9");  // Magic!
1112         assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1113         assert_eq!(e(&[0xD800], &[0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1114         assert_eq!(e(&[0xD800], &[0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1115         assert_eq!(e(&[0xD7FF], &[0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1116         assert_eq!(e(&[0x61], &[0xDC00]).bytes, b"\x61\xED\xB0\x80");
1117         assert_eq!(e(&[], &[0xDC00]).bytes, b"\xED\xB0\x80");
1118     }
1119
1120     #[test]
1121     fn wtf8buf_show() {
1122         let mut string = Wtf8Buf::from_str("a\té \u{7f}💩\r");
1123         string.push(CodePoint::from_u32(0xD800).unwrap());
1124         assert_eq!(format!("{:?}", string), "\"a\\té \\u{7f}\u{1f4a9}\\r\\u{d800}\"");
1125     }
1126
1127     #[test]
1128     fn wtf8buf_as_slice() {
1129         assert_eq!(Wtf8Buf::from_str("aé").as_slice(), Wtf8::from_str("aé"));
1130     }
1131
1132     #[test]
1133     fn wtf8buf_show_str() {
1134         let text = "a\té 💩\r";
1135         let string = Wtf8Buf::from_str(text);
1136         assert_eq!(format!("{:?}", text), format!("{:?}", string));
1137     }
1138
1139     #[test]
1140     fn wtf8_from_str() {
1141         assert_eq!(&Wtf8::from_str("").bytes, b"");
1142         assert_eq!(&Wtf8::from_str("aé 💩").bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1143     }
1144
1145     #[test]
1146     fn wtf8_len() {
1147         assert_eq!(Wtf8::from_str("").len(), 0);
1148         assert_eq!(Wtf8::from_str("aé 💩").len(), 8);
1149     }
1150
1151     #[test]
1152     fn wtf8_slice() {
1153         assert_eq!(&Wtf8::from_str("aé 💩")[1.. 4].bytes, b"\xC3\xA9 ");
1154     }
1155
1156     #[test]
1157     #[should_panic]
1158     fn wtf8_slice_not_code_point_boundary() {
1159         &Wtf8::from_str("aé 💩")[2.. 4];
1160     }
1161
1162     #[test]
1163     fn wtf8_slice_from() {
1164         assert_eq!(&Wtf8::from_str("aé 💩")[1..].bytes, b"\xC3\xA9 \xF0\x9F\x92\xA9");
1165     }
1166
1167     #[test]
1168     #[should_panic]
1169     fn wtf8_slice_from_not_code_point_boundary() {
1170         &Wtf8::from_str("aé 💩")[2..];
1171     }
1172
1173     #[test]
1174     fn wtf8_slice_to() {
1175         assert_eq!(&Wtf8::from_str("aé 💩")[..4].bytes, b"a\xC3\xA9 ");
1176     }
1177
1178     #[test]
1179     #[should_panic]
1180     fn wtf8_slice_to_not_code_point_boundary() {
1181         &Wtf8::from_str("aé 💩")[5..];
1182     }
1183
1184     #[test]
1185     fn wtf8_ascii_byte_at() {
1186         let slice = Wtf8::from_str("aé 💩");
1187         assert_eq!(slice.ascii_byte_at(0), b'a');
1188         assert_eq!(slice.ascii_byte_at(1), b'\xFF');
1189         assert_eq!(slice.ascii_byte_at(2), b'\xFF');
1190         assert_eq!(slice.ascii_byte_at(3), b' ');
1191         assert_eq!(slice.ascii_byte_at(4), b'\xFF');
1192     }
1193
1194     #[test]
1195     fn wtf8_code_points() {
1196         fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
1197         fn cp(string: &Wtf8Buf) -> Vec<Option<char>> {
1198             string.code_points().map(|c| c.to_char()).collect::<Vec<_>>()
1199         }
1200         let mut string = Wtf8Buf::from_str("é ");
1201         assert_eq!(cp(&string), [Some('é'), Some(' ')]);
1202         string.push(c(0xD83D));
1203         assert_eq!(cp(&string), [Some('é'), Some(' '), None]);
1204         string.push(c(0xDCA9));
1205         assert_eq!(cp(&string), [Some('é'), Some(' '), Some('💩')]);
1206     }
1207
1208     #[test]
1209     fn wtf8_as_str() {
1210         assert_eq!(Wtf8::from_str("").as_str(), Some(""));
1211         assert_eq!(Wtf8::from_str("aé 💩").as_str(), Some("aé 💩"));
1212         let mut string = Wtf8Buf::new();
1213         string.push(CodePoint::from_u32(0xD800).unwrap());
1214         assert_eq!(string.as_str(), None);
1215     }
1216
1217     #[test]
1218     fn wtf8_to_string_lossy() {
1219         assert_eq!(Wtf8::from_str("").to_string_lossy(), Cow::Borrowed(""));
1220         assert_eq!(Wtf8::from_str("aé 💩").to_string_lossy(), Cow::Borrowed("aé 💩"));
1221         let mut string = Wtf8Buf::from_str("aé 💩");
1222         string.push(CodePoint::from_u32(0xD800).unwrap());
1223         let expected: Cow<str> = Cow::Owned(String::from("aé 💩�"));
1224         assert_eq!(string.to_string_lossy(), expected);
1225     }
1226
1227     #[test]
1228     fn wtf8_display() {
1229         fn d(b: &[u8]) -> String {
1230             format!("{}", &unsafe { Wtf8::from_bytes_unchecked(b) })
1231         }
1232
1233         assert_eq!("", d("".as_bytes()));
1234         assert_eq!("aé 💩", d("aé 💩".as_bytes()));
1235
1236         let mut string = Wtf8Buf::from_str("aé 💩");
1237         string.push(CodePoint::from_u32(0xD800).unwrap());
1238         assert_eq!("aé 💩�", d(string.as_inner()));
1239     }
1240
1241     #[test]
1242     fn wtf8_encode_wide() {
1243         let mut string = Wtf8Buf::from_str("aé ");
1244         string.push(CodePoint::from_u32(0xD83D).unwrap());
1245         string.push_char('💩');
1246         assert_eq!(string.encode_wide().collect::<Vec<_>>(),
1247                    vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]);
1248     }
1249 }