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