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.
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.
28 use core
::str::next_code_point
;
33 use hash
::{Hash, Hasher}
;
34 use iter
::FromIterator
;
41 use sys_common
::AsInner
;
43 const UTF8_REPLACEMENT_CHARACTER
: &'
static str = "\u{FFFD}";
45 /// A Unicode code point: from U+0000 to U+10FFFF.
47 /// Compare with the `char` type,
48 /// which represents a Unicode scalar value:
49 /// a code point that is not a surrogate (U+D800 to U+DFFF).
50 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
51 pub struct CodePoint
{
55 /// Format the code point as `U+` followed by four to six hexadecimal digits.
56 /// Example: `U+1F4A9`
57 impl fmt
::Debug
for CodePoint
{
59 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> Result
<(), fmt
::Error
> {
60 write
!(formatter
, "U+{:04X}", self.value
)
65 /// Unsafely creates a new `CodePoint` without checking the value.
67 /// Only use when `value` is known to be less than or equal to 0x10FFFF.
69 pub unsafe fn from_u32_unchecked(value
: u32) -> CodePoint
{
70 CodePoint { value: value }
73 /// Creates a new `CodePoint` if the value is a valid code point.
75 /// Returns `None` if `value` is above 0x10FFFF.
77 pub fn from_u32(value
: u32) -> Option
<CodePoint
> {
79 0 ... 0x10FFFF => Some(CodePoint { value: value }
),
84 /// Creates a new `CodePoint` from a `char`.
86 /// Since all Unicode scalar values are code points, this always succeeds.
88 pub fn from_char(value
: char) -> CodePoint
{
89 CodePoint { value: value as u32 }
92 /// Returns the numeric value of the code point.
94 pub fn to_u32(&self) -> u32 {
98 /// Optionally returns a Unicode scalar value for the code point.
100 /// Returns `None` if the code point is a surrogate (from U+D800 to U+DFFF).
102 pub fn to_char(&self) -> Option
<char> {
104 0xD800 ... 0xDFFF => None
,
105 _
=> Some(unsafe { char::from_u32_unchecked(self.value) }
)
109 /// Returns a Unicode scalar value for the code point.
111 /// Returns `'\u{FFFD}'` (the replacement character “�”)
112 /// if the code point is a surrogate (from U+D800 to U+DFFF).
114 pub fn to_char_lossy(&self) -> char {
115 self.to_char().unwrap_or('
\u{FFFD}'
)
119 /// An owned, growable string of well-formed WTF-8 data.
121 /// Similar to `String`, but can additionally contain surrogate code points
122 /// if they’re not in a surrogate pair.
123 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
128 impl ops
::Deref
for Wtf8Buf
{
131 fn deref(&self) -> &Wtf8
{
136 impl ops
::DerefMut
for Wtf8Buf
{
137 fn deref_mut(&mut self) -> &mut Wtf8
{
142 /// Format the string with double quotes,
143 /// and surrogates as `\u` followed by four hexadecimal digits.
144 /// Example: `"a\u{D800}"` for a string with code points [U+0061, U+D800]
145 impl fmt
::Debug
for Wtf8Buf
{
147 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> Result
<(), fmt
::Error
> {
148 fmt
::Debug
::fmt(&**self, formatter
)
153 /// Creates a new, empty WTF-8 string.
155 pub fn new() -> Wtf8Buf
{
156 Wtf8Buf { bytes: Vec::new() }
159 /// Creates a new, empty WTF-8 string with pre-allocated capacity for `n` bytes.
161 pub fn with_capacity(n
: usize) -> Wtf8Buf
{
162 Wtf8Buf { bytes: Vec::with_capacity(n) }
165 /// Creates a WTF-8 string from a UTF-8 `String`.
167 /// This takes ownership of the `String` and does not copy.
169 /// Since WTF-8 is a superset of UTF-8, this always succeeds.
171 pub fn from_string(string
: String
) -> Wtf8Buf
{
172 Wtf8Buf { bytes: string.into_bytes() }
175 /// Creates a WTF-8 string from a UTF-8 `&str` slice.
177 /// This copies the content of the slice.
179 /// Since WTF-8 is a superset of UTF-8, this always succeeds.
181 pub fn from_str(str: &str) -> Wtf8Buf
{
182 Wtf8Buf { bytes: <[_]>::to_vec(str.as_bytes()) }
185 pub fn clear(&mut self) {
189 /// Creates a WTF-8 string from a potentially ill-formed UTF-16 slice of 16-bit code units.
191 /// This is lossless: calling `.encode_wide()` on the resulting string
192 /// will always return the original code units.
193 pub fn from_wide(v
: &[u16]) -> Wtf8Buf
{
194 let mut string
= Wtf8Buf
::with_capacity(v
.len());
195 for item
in char::decode_utf16(v
.iter().cloned()) {
197 Ok(ch
) => string
.push_char(ch
),
199 let surrogate
= surrogate
.unpaired_surrogate();
200 // Surrogates are known to be in the code point range.
201 let code_point
= unsafe {
202 CodePoint
::from_u32_unchecked(surrogate
as u32)
204 // Skip the WTF-8 concatenation check,
205 // surrogate pairs are already decoded by decode_utf16
206 string
.push_code_point_unchecked(code_point
)
213 /// Copied from String::push
214 /// This does **not** include the WTF-8 concatenation check.
215 fn push_code_point_unchecked(&mut self, code_point
: CodePoint
) {
217 char::from_u32_unchecked(code_point
.value
)
219 let mut bytes
= [0; 4];
220 let bytes
= c
.encode_utf8(&mut bytes
).as_bytes();
221 self.bytes
.extend_from_slice(bytes
)
225 pub fn as_slice(&self) -> &Wtf8
{
226 unsafe { Wtf8::from_bytes_unchecked(&self.bytes) }
230 pub fn as_mut_slice(&mut self) -> &mut Wtf8
{
231 unsafe { Wtf8::from_mut_bytes_unchecked(&mut self.bytes) }
234 /// Reserves capacity for at least `additional` more bytes to be inserted
235 /// in the given `Wtf8Buf`.
236 /// The collection may reserve more space to avoid frequent reallocations.
240 /// Panics if the new capacity overflows `usize`.
242 pub fn reserve(&mut self, additional
: usize) {
243 self.bytes
.reserve(additional
)
247 pub fn reserve_exact(&mut self, additional
: usize) {
248 self.bytes
.reserve_exact(additional
)
252 pub fn shrink_to_fit(&mut self) {
253 self.bytes
.shrink_to_fit()
257 pub fn shrink_to(&mut self, min_capacity
: usize) {
258 self.bytes
.shrink_to(min_capacity
)
261 /// Returns the number of bytes that this string buffer can hold without reallocating.
263 pub fn capacity(&self) -> usize {
264 self.bytes
.capacity()
267 /// Append a UTF-8 slice at the end of the string.
269 pub fn push_str(&mut self, other
: &str) {
270 self.bytes
.extend_from_slice(other
.as_bytes())
273 /// Append a WTF-8 slice at the end of the string.
275 /// This replaces newly paired surrogates at the boundary
276 /// with a supplementary code point,
277 /// like concatenating ill-formed UTF-16 strings effectively would.
279 pub fn push_wtf8(&mut self, other
: &Wtf8
) {
280 match ((&*self).final_lead_surrogate(), other
.initial_trail_surrogate()) {
281 // Replace newly paired surrogates by a supplementary code point.
282 (Some(lead
), Some(trail
)) => {
283 let len_without_lead_surrogate
= self.len() - 3;
284 self.bytes
.truncate(len_without_lead_surrogate
);
285 let other_without_trail_surrogate
= &other
.bytes
[3..];
286 // 4 bytes for the supplementary code point
287 self.bytes
.reserve(4 + other_without_trail_surrogate
.len());
288 self.push_char(decode_surrogate_pair(lead
, trail
));
289 self.bytes
.extend_from_slice(other_without_trail_surrogate
);
291 _
=> self.bytes
.extend_from_slice(&other
.bytes
)
295 /// Append a Unicode scalar value at the end of the string.
297 pub fn push_char(&mut self, c
: char) {
298 self.push_code_point_unchecked(CodePoint
::from_char(c
))
301 /// Append a code point at the end of the string.
303 /// This replaces newly paired surrogates at the boundary
304 /// with a supplementary code point,
305 /// like concatenating ill-formed UTF-16 strings effectively would.
307 pub fn push(&mut self, code_point
: CodePoint
) {
308 if let trail @
0xDC00...0xDFFF = code_point
.to_u32() {
309 if let Some(lead
) = (&*self).final_lead_surrogate() {
310 let len_without_lead_surrogate
= self.len() - 3;
311 self.bytes
.truncate(len_without_lead_surrogate
);
312 self.push_char(decode_surrogate_pair(lead
, trail
as u16));
317 // No newly paired surrogates at the boundary.
318 self.push_code_point_unchecked(code_point
)
321 /// Shortens a string to the specified length.
325 /// Panics if `new_len` > current length,
326 /// or if `new_len` is not a code point boundary.
328 pub fn truncate(&mut self, new_len
: usize) {
329 assert
!(is_code_point_boundary(self, new_len
));
330 self.bytes
.truncate(new_len
)
333 /// Consumes the WTF-8 string and tries to convert it to UTF-8.
335 /// This does not copy the data.
337 /// If the contents are not well-formed UTF-8
338 /// (that is, if the string contains surrogates),
339 /// the original WTF-8 string is returned instead.
340 pub fn into_string(self) -> Result
<String
, Wtf8Buf
> {
341 match self.next_surrogate(0) {
342 None
=> Ok(unsafe { String::from_utf8_unchecked(self.bytes) }
),
343 Some(_
) => Err(self),
347 /// Consumes the WTF-8 string and converts it lossily to UTF-8.
349 /// This does not copy the data (but may overwrite parts of it in place).
351 /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”)
352 pub fn into_string_lossy(mut self) -> String
{
355 match self.next_surrogate(pos
) {
356 Some((surrogate_pos
, _
)) => {
357 pos
= surrogate_pos
+ 3;
358 self.bytes
[surrogate_pos
..pos
]
359 .copy_from_slice(UTF8_REPLACEMENT_CHARACTER
.as_bytes());
361 None
=> return unsafe { String::from_utf8_unchecked(self.bytes) }
366 /// Converts this `Wtf8Buf` into a boxed `Wtf8`.
368 pub fn into_box(self) -> Box
<Wtf8
> {
369 unsafe { mem::transmute(self.bytes.into_boxed_slice()) }
372 /// Converts a `Box<Wtf8>` into a `Wtf8Buf`.
373 pub fn from_box(boxed
: Box
<Wtf8
>) -> Wtf8Buf
{
374 let bytes
: Box
<[u8]> = unsafe { mem::transmute(boxed) }
;
375 Wtf8Buf { bytes: bytes.into_vec() }
379 /// Create a new WTF-8 string from an iterator of code points.
381 /// This replaces surrogate code point pairs with supplementary code points,
382 /// like concatenating ill-formed UTF-16 strings effectively would.
383 impl FromIterator
<CodePoint
> for Wtf8Buf
{
384 fn from_iter
<T
: IntoIterator
<Item
=CodePoint
>>(iter
: T
) -> Wtf8Buf
{
385 let mut string
= Wtf8Buf
::new();
391 /// Append code points from an iterator to the string.
393 /// This replaces surrogate code point pairs with supplementary code points,
394 /// like concatenating ill-formed UTF-16 strings effectively would.
395 impl Extend
<CodePoint
> for Wtf8Buf
{
396 fn extend
<T
: IntoIterator
<Item
=CodePoint
>>(&mut self, iter
: T
) {
397 let iterator
= iter
.into_iter();
398 let (low
, _high
) = iterator
.size_hint();
399 // Lower bound of one byte per code point (ASCII only)
400 self.bytes
.reserve(low
);
401 for code_point
in iterator
{
402 self.push(code_point
);
407 /// A borrowed slice of well-formed WTF-8 data.
409 /// Similar to `&str`, but can additionally contain surrogate code points
410 /// if they’re not in a surrogate pair.
411 #[derive(Eq, Ord, PartialEq, PartialOrd)]
416 impl AsInner
<[u8]> for Wtf8
{
417 fn as_inner(&self) -> &[u8] { &self.bytes }
420 /// Format the slice with double quotes,
421 /// and surrogates as `\u` followed by four hexadecimal digits.
422 /// Example: `"a\u{D800}"` for a slice with code points [U+0061, U+D800]
423 impl fmt
::Debug
for Wtf8
{
424 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
425 fn write_str_escaped(f
: &mut fmt
::Formatter
, s
: &str) -> fmt
::Result
{
427 for c
in s
.chars().flat_map(|c
| c
.escape_debug()) {
433 formatter
.write_str("\"")?
;
435 while let Some((surrogate_pos
, surrogate
)) = self.next_surrogate(pos
) {
438 unsafe { str::from_utf8_unchecked(
439 &self.bytes
[pos
.. surrogate_pos
]
442 write
!(formatter
, "\\u{{{:x}}}", surrogate
)?
;
443 pos
= surrogate_pos
+ 3;
447 unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) }
,
449 formatter
.write_str("\"")
453 impl fmt
::Display
for Wtf8
{
454 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
455 let wtf8_bytes
= &self.bytes
;
458 match self.next_surrogate(pos
) {
459 Some((surrogate_pos
, _
)) => {
460 formatter
.write_str(unsafe {
461 str::from_utf8_unchecked(&wtf8_bytes
[pos
.. surrogate_pos
])
463 formatter
.write_str(UTF8_REPLACEMENT_CHARACTER
)?
;
464 pos
= surrogate_pos
+ 3;
468 str::from_utf8_unchecked(&wtf8_bytes
[pos
..])
471 return s
.fmt(formatter
)
473 return formatter
.write_str(s
)
482 /// Creates a WTF-8 slice from a UTF-8 `&str` slice.
484 /// Since WTF-8 is a superset of UTF-8, this always succeeds.
486 pub fn from_str(value
: &str) -> &Wtf8
{
487 unsafe { Wtf8::from_bytes_unchecked(value.as_bytes()) }
490 /// Creates a WTF-8 slice from a WTF-8 byte slice.
492 /// Since the byte slice is not checked for valid WTF-8, this functions is
495 unsafe fn from_bytes_unchecked(value
: &[u8]) -> &Wtf8
{
496 mem
::transmute(value
)
499 /// Creates a mutable WTF-8 slice from a mutable WTF-8 byte slice.
501 /// Since the byte slice is not checked for valid WTF-8, this functions is
504 unsafe fn from_mut_bytes_unchecked(value
: &mut [u8]) -> &mut Wtf8
{
505 mem
::transmute(value
)
508 /// Returns the length, in WTF-8 bytes.
510 pub fn len(&self) -> usize {
515 pub fn is_empty(&self) -> bool
{
516 self.bytes
.is_empty()
519 /// Returns the code point at `position` if it is in the ASCII range,
520 /// or `b'\xFF' otherwise.
524 /// Panics if `position` is beyond the end of the string.
526 pub fn ascii_byte_at(&self, position
: usize) -> u8 {
527 match self.bytes
[position
] {
528 ascii_byte @
0x00 ... 0x7F => ascii_byte
,
533 /// Returns an iterator for the string’s code points.
535 pub fn code_points(&self) -> Wtf8CodePoints
{
536 Wtf8CodePoints { bytes: self.bytes.iter() }
539 /// Tries to convert the string to UTF-8 and return a `&str` slice.
541 /// Returns `None` if the string contains surrogates.
543 /// This does not copy the data.
545 pub fn as_str(&self) -> Option
<&str> {
546 // Well-formed WTF-8 is also well-formed UTF-8
547 // if and only if it contains no surrogate.
548 match self.next_surrogate(0) {
549 None
=> Some(unsafe { str::from_utf8_unchecked(&self.bytes) }
),
554 /// Lossily converts the string to UTF-8.
555 /// Returns a UTF-8 `&str` slice if the contents are well-formed in UTF-8.
557 /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”).
559 /// This only copies the data if necessary (if it contains any surrogate).
560 pub fn to_string_lossy(&self) -> Cow
<str> {
561 let surrogate_pos
= match self.next_surrogate(0) {
562 None
=> return Cow
::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) }
),
563 Some((pos
, _
)) => pos
,
565 let wtf8_bytes
= &self.bytes
;
566 let mut utf8_bytes
= Vec
::with_capacity(self.len());
567 utf8_bytes
.extend_from_slice(&wtf8_bytes
[..surrogate_pos
]);
568 utf8_bytes
.extend_from_slice(UTF8_REPLACEMENT_CHARACTER
.as_bytes());
569 let mut pos
= surrogate_pos
+ 3;
571 match self.next_surrogate(pos
) {
572 Some((surrogate_pos
, _
)) => {
573 utf8_bytes
.extend_from_slice(&wtf8_bytes
[pos
.. surrogate_pos
]);
574 utf8_bytes
.extend_from_slice(UTF8_REPLACEMENT_CHARACTER
.as_bytes());
575 pos
= surrogate_pos
+ 3;
578 utf8_bytes
.extend_from_slice(&wtf8_bytes
[pos
..]);
579 return Cow
::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) }
)
585 /// Converts the WTF-8 string to potentially ill-formed UTF-16
586 /// and return an iterator of 16-bit code units.
588 /// This is lossless:
589 /// calling `Wtf8Buf::from_ill_formed_utf16` on the resulting code units
590 /// would always return the original WTF-8 string.
592 pub fn encode_wide(&self) -> EncodeWide
{
593 EncodeWide { code_points: self.code_points(), extra: 0 }
597 fn next_surrogate(&self, mut pos
: usize) -> Option
<(usize, u16)> {
598 let mut iter
= self.bytes
[pos
..].iter();
600 let b
= *iter
.next()?
;
606 } else if b
== 0xED {
607 match (iter
.next(), iter
.next()) {
608 (Some(&b2
), Some(&b3
)) if b2
>= 0xA0 => {
609 return Some((pos
, decode_surrogate(b2
, b3
)))
627 fn final_lead_surrogate(&self) -> Option
<u16> {
628 let len
= self.len();
632 match &self.bytes
[(len
- 3)..] {
633 &[0xED, b2 @
0xA0...0xAF, b3
] => Some(decode_surrogate(b2
, b3
)),
639 fn initial_trail_surrogate(&self) -> Option
<u16> {
640 let len
= self.len();
644 match &self.bytes
[..3] {
645 &[0xED, b2 @
0xB0...0xBF, b3
] => Some(decode_surrogate(b2
, b3
)),
650 /// Boxes this `Wtf8`.
652 pub fn into_box(&self) -> Box
<Wtf8
> {
653 let boxed
: Box
<[u8]> = self.bytes
.into();
654 unsafe { mem::transmute(boxed) }
657 /// Creates a boxed, empty `Wtf8`.
658 pub fn empty_box() -> Box
<Wtf8
> {
659 let boxed
: Box
<[u8]> = Default
::default();
660 unsafe { mem::transmute(boxed) }
664 pub fn into_arc(&self) -> Arc
<Wtf8
> {
665 let arc
: Arc
<[u8]> = Arc
::from(&self.bytes
);
666 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Wtf8) }
670 pub fn into_rc(&self) -> Rc
<Wtf8
> {
671 let rc
: Rc
<[u8]> = Rc
::from(&self.bytes
);
672 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Wtf8) }
677 /// Return a slice of the given string for the byte range [`begin`..`end`).
681 /// Panics when `begin` and `end` do not point to code point boundaries,
682 /// or point beyond the end of the string.
683 impl ops
::Index
<ops
::Range
<usize>> for Wtf8
{
687 fn index(&self, range
: ops
::Range
<usize>) -> &Wtf8
{
688 // is_code_point_boundary checks that the index is in [0, .len()]
689 if range
.start
<= range
.end
&&
690 is_code_point_boundary(self, range
.start
) &&
691 is_code_point_boundary(self, range
.end
) {
692 unsafe { slice_unchecked(self, range.start, range.end) }
694 slice_error_fail(self, range
.start
, range
.end
)
699 /// Return a slice of the given string from byte `begin` to its end.
703 /// Panics when `begin` is not at a code point boundary,
704 /// or is beyond the end of the string.
705 impl ops
::Index
<ops
::RangeFrom
<usize>> for Wtf8
{
709 fn index(&self, range
: ops
::RangeFrom
<usize>) -> &Wtf8
{
710 // is_code_point_boundary checks that the index is in [0, .len()]
711 if is_code_point_boundary(self, range
.start
) {
712 unsafe { slice_unchecked(self, range.start, self.len()) }
714 slice_error_fail(self, range
.start
, self.len())
719 /// Return a slice of the given string from its beginning to byte `end`.
723 /// Panics when `end` is not at a code point boundary,
724 /// or is beyond the end of the string.
725 impl ops
::Index
<ops
::RangeTo
<usize>> for Wtf8
{
729 fn index(&self, range
: ops
::RangeTo
<usize>) -> &Wtf8
{
730 // is_code_point_boundary checks that the index is in [0, .len()]
731 if is_code_point_boundary(self, range
.end
) {
732 unsafe { slice_unchecked(self, 0, range.end) }
734 slice_error_fail(self, 0, range
.end
)
739 impl ops
::Index
<ops
::RangeFull
> for Wtf8
{
743 fn index(&self, _range
: ops
::RangeFull
) -> &Wtf8
{
749 fn decode_surrogate(second_byte
: u8, third_byte
: u8) -> u16 {
750 // The first byte is assumed to be 0xED
751 0xD800 | (second_byte
as u16 & 0x3F) << 6 | third_byte
as u16 & 0x3F
755 fn decode_surrogate_pair(lead
: u16, trail
: u16) -> char {
756 let code_point
= 0x10000 + ((((lead
- 0xD800) as u32) << 10) | (trail
- 0xDC00) as u32);
757 unsafe { char::from_u32_unchecked(code_point) }
760 /// Copied from core::str::StrPrelude::is_char_boundary
762 pub fn is_code_point_boundary(slice
: &Wtf8
, index
: usize) -> bool
{
763 if index
== slice
.len() { return true; }
764 match slice
.bytes
.get(index
) {
766 Some(&b
) => b
< 128 || b
>= 192,
770 /// Copied from core::str::raw::slice_unchecked
772 pub unsafe fn slice_unchecked(s
: &Wtf8
, begin
: usize, end
: usize) -> &Wtf8
{
773 // memory layout of an &[u8] and &Wtf8 are the same
774 Wtf8
::from_bytes_unchecked(slice
::from_raw_parts(
775 s
.bytes
.as_ptr().offset(begin
as isize),
780 /// Copied from core::str::raw::slice_error_fail
782 pub fn slice_error_fail(s
: &Wtf8
, begin
: usize, end
: usize) -> ! {
783 assert
!(begin
<= end
);
784 panic
!("index {} and/or {} in `{:?}` do not lie on character boundary",
788 /// Iterator for the code points of a WTF-8 string.
790 /// Created with the method `.code_points()`.
792 pub struct Wtf8CodePoints
<'a
> {
793 bytes
: slice
::Iter
<'a
, u8>
796 impl<'a
> Iterator
for Wtf8CodePoints
<'a
> {
797 type Item
= CodePoint
;
800 fn next(&mut self) -> Option
<CodePoint
> {
801 next_code_point(&mut self.bytes
).map(|c
| CodePoint { value: c }
)
805 fn size_hint(&self) -> (usize, Option
<usize>) {
806 let len
= self.bytes
.len();
807 (len
.saturating_add(3) / 4, Some(len
))
811 /// Generates a wide character sequence for potentially ill-formed UTF-16.
812 #[stable(feature = "rust1", since = "1.0.0")]
814 pub struct EncodeWide
<'a
> {
815 code_points
: Wtf8CodePoints
<'a
>,
819 // Copied from libunicode/u_str.rs
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl<'a
> Iterator
for EncodeWide
<'a
> {
825 fn next(&mut self) -> Option
<u16> {
827 let tmp
= self.extra
;
832 let mut buf
= [0; 2];
833 self.code_points
.next().map(|code_point
| {
835 char::from_u32_unchecked(code_point
.value
)
837 let n
= c
.encode_utf16(&mut buf
).len();
846 fn size_hint(&self) -> (usize, Option
<usize>) {
847 let (low
, high
) = self.code_points
.size_hint();
848 // every code point gets either one u16 or two u16,
849 // so this iterator is between 1 or 2 times as
850 // long as the underlying iterator.
851 (low
, high
.and_then(|n
| n
.checked_mul(2)))
855 impl Hash
for CodePoint
{
857 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
858 self.value
.hash(state
)
862 impl Hash
for Wtf8Buf
{
864 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
865 state
.write(&self.bytes
);
872 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
873 state
.write(&self.bytes
);
879 pub fn is_ascii(&self) -> bool
{
880 self.bytes
.is_ascii()
882 pub fn to_ascii_uppercase(&self) -> Wtf8Buf
{
883 Wtf8Buf { bytes: self.bytes.to_ascii_uppercase() }
885 pub fn to_ascii_lowercase(&self) -> Wtf8Buf
{
886 Wtf8Buf { bytes: self.bytes.to_ascii_lowercase() }
888 pub fn eq_ignore_ascii_case(&self, other
: &Wtf8
) -> bool
{
889 self.bytes
.eq_ignore_ascii_case(&other
.bytes
)
892 pub fn make_ascii_uppercase(&mut self) { self.bytes.make_ascii_uppercase() }
893 pub fn make_ascii_lowercase(&mut self) { self.bytes.make_ascii_lowercase() }
902 fn code_point_from_u32() {
903 assert
!(CodePoint
::from_u32(0).is_some());
904 assert
!(CodePoint
::from_u32(0xD800).is_some());
905 assert
!(CodePoint
::from_u32(0x10FFFF).is_some());
906 assert
!(CodePoint
::from_u32(0x110000).is_none());
910 fn code_point_to_u32() {
911 fn c(value
: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
912 assert_eq
!(c(0).to_u32(), 0);
913 assert_eq
!(c(0xD800).to_u32(), 0xD800);
914 assert_eq
!(c(0x10FFFF).to_u32(), 0x10FFFF);
918 fn code_point_from_char() {
919 assert_eq
!(CodePoint
::from_char('a'
).to_u32(), 0x61);
920 assert_eq
!(CodePoint
::from_char('💩'
).to_u32(), 0x1F4A9);
924 fn code_point_to_string() {
925 assert_eq
!(format
!("{:?}", CodePoint
::from_char('a'
)), "U+0061");
926 assert_eq
!(format
!("{:?}", CodePoint
::from_char('💩'
)), "U+1F4A9");
930 fn code_point_to_char() {
931 fn c(value
: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
932 assert_eq
!(c(0x61).to_char(), Some('a'
));
933 assert_eq
!(c(0x1F4A9).to_char(), Some('💩'
));
934 assert_eq
!(c(0xD800).to_char(), None
);
938 fn code_point_to_char_lossy() {
939 fn c(value
: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
940 assert_eq
!(c(0x61).to_char_lossy(), 'a'
);
941 assert_eq
!(c(0x1F4A9).to_char_lossy(), '💩'
);
942 assert_eq
!(c(0xD800).to_char_lossy(), '
\u{FFFD}'
);
947 assert_eq
!(Wtf8Buf
::new().bytes
, b
"");
951 fn wtf8buf_from_str() {
952 assert_eq
!(Wtf8Buf
::from_str("").bytes
, b
"");
953 assert_eq
!(Wtf8Buf
::from_str("aé 💩").bytes
,
954 b
"a\xC3\xA9 \xF0\x9F\x92\xA9");
958 fn wtf8buf_from_string() {
959 assert_eq
!(Wtf8Buf
::from_string(String
::from("")).bytes
, b
"");
960 assert_eq
!(Wtf8Buf
::from_string(String
::from("aé 💩")).bytes
,
961 b
"a\xC3\xA9 \xF0\x9F\x92\xA9");
965 fn wtf8buf_from_wide() {
966 assert_eq
!(Wtf8Buf
::from_wide(&[]).bytes
, b
"");
967 assert_eq
!(Wtf8Buf
::from_wide(
968 &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes
,
969 b
"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9");
973 fn wtf8buf_push_str() {
974 let mut string
= Wtf8Buf
::new();
975 assert_eq
!(string
.bytes
, b
"");
976 string
.push_str("aé 💩");
977 assert_eq
!(string
.bytes
, b
"a\xC3\xA9 \xF0\x9F\x92\xA9");
981 fn wtf8buf_push_char() {
982 let mut string
= Wtf8Buf
::from_str("aé ");
983 assert_eq
!(string
.bytes
, b
"a\xC3\xA9 ");
984 string
.push_char('💩'
);
985 assert_eq
!(string
.bytes
, b
"a\xC3\xA9 \xF0\x9F\x92\xA9");
990 let mut string
= Wtf8Buf
::from_str("aé ");
991 assert_eq
!(string
.bytes
, b
"a\xC3\xA9 ");
992 string
.push(CodePoint
::from_char('💩'
));
993 assert_eq
!(string
.bytes
, b
"a\xC3\xA9 \xF0\x9F\x92\xA9");
995 fn c(value
: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
997 let mut string
= Wtf8Buf
::new();
998 string
.push(c(0xD83D)); // lead
999 string
.push(c(0xDCA9)); // trail
1000 assert_eq
!(string
.bytes
, b
"\xF0\x9F\x92\xA9"); // Magic!
1002 let mut string
= Wtf8Buf
::new();
1003 string
.push(c(0xD83D)); // lead
1004 string
.push(c(0x20)); // not surrogate
1005 string
.push(c(0xDCA9)); // trail
1006 assert_eq
!(string
.bytes
, b
"\xED\xA0\xBD \xED\xB2\xA9");
1008 let mut string
= Wtf8Buf
::new();
1009 string
.push(c(0xD800)); // lead
1010 string
.push(c(0xDBFF)); // lead
1011 assert_eq
!(string
.bytes
, b
"\xED\xA0\x80\xED\xAF\xBF");
1013 let mut string
= Wtf8Buf
::new();
1014 string
.push(c(0xD800)); // lead
1015 string
.push(c(0xE000)); // not surrogate
1016 assert_eq
!(string
.bytes
, b
"\xED\xA0\x80\xEE\x80\x80");
1018 let mut string
= Wtf8Buf
::new();
1019 string
.push(c(0xD7FF)); // not surrogate
1020 string
.push(c(0xDC00)); // trail
1021 assert_eq
!(string
.bytes
, b
"\xED\x9F\xBF\xED\xB0\x80");
1023 let mut string
= Wtf8Buf
::new();
1024 string
.push(c(0x61)); // not surrogate, < 3 bytes
1025 string
.push(c(0xDC00)); // trail
1026 assert_eq
!(string
.bytes
, b
"\x61\xED\xB0\x80");
1028 let mut string
= Wtf8Buf
::new();
1029 string
.push(c(0xDC00)); // trail
1030 assert_eq
!(string
.bytes
, b
"\xED\xB0\x80");
1034 fn wtf8buf_push_wtf8() {
1035 let mut string
= Wtf8Buf
::from_str("aé");
1036 assert_eq
!(string
.bytes
, b
"a\xC3\xA9");
1037 string
.push_wtf8(Wtf8
::from_str(" 💩"));
1038 assert_eq
!(string
.bytes
, b
"a\xC3\xA9 \xF0\x9F\x92\xA9");
1040 fn w(v
: &[u8]) -> &Wtf8 { unsafe { Wtf8::from_bytes_unchecked(v) }
}
1042 let mut string
= Wtf8Buf
::new();
1043 string
.push_wtf8(w(b
"\xED\xA0\xBD")); // lead
1044 string
.push_wtf8(w(b
"\xED\xB2\xA9")); // trail
1045 assert_eq
!(string
.bytes
, b
"\xF0\x9F\x92\xA9"); // Magic!
1047 let mut string
= Wtf8Buf
::new();
1048 string
.push_wtf8(w(b
"\xED\xA0\xBD")); // lead
1049 string
.push_wtf8(w(b
" ")); // not surrogate
1050 string
.push_wtf8(w(b
"\xED\xB2\xA9")); // trail
1051 assert_eq
!(string
.bytes
, b
"\xED\xA0\xBD \xED\xB2\xA9");
1053 let mut string
= Wtf8Buf
::new();
1054 string
.push_wtf8(w(b
"\xED\xA0\x80")); // lead
1055 string
.push_wtf8(w(b
"\xED\xAF\xBF")); // lead
1056 assert_eq
!(string
.bytes
, b
"\xED\xA0\x80\xED\xAF\xBF");
1058 let mut string
= Wtf8Buf
::new();
1059 string
.push_wtf8(w(b
"\xED\xA0\x80")); // lead
1060 string
.push_wtf8(w(b
"\xEE\x80\x80")); // not surrogate
1061 assert_eq
!(string
.bytes
, b
"\xED\xA0\x80\xEE\x80\x80");
1063 let mut string
= Wtf8Buf
::new();
1064 string
.push_wtf8(w(b
"\xED\x9F\xBF")); // not surrogate
1065 string
.push_wtf8(w(b
"\xED\xB0\x80")); // trail
1066 assert_eq
!(string
.bytes
, b
"\xED\x9F\xBF\xED\xB0\x80");
1068 let mut string
= Wtf8Buf
::new();
1069 string
.push_wtf8(w(b
"a")); // not surrogate, < 3 bytes
1070 string
.push_wtf8(w(b
"\xED\xB0\x80")); // trail
1071 assert_eq
!(string
.bytes
, b
"\x61\xED\xB0\x80");
1073 let mut string
= Wtf8Buf
::new();
1074 string
.push_wtf8(w(b
"\xED\xB0\x80")); // trail
1075 assert_eq
!(string
.bytes
, b
"\xED\xB0\x80");
1079 fn wtf8buf_truncate() {
1080 let mut string
= Wtf8Buf
::from_str("aé");
1082 assert_eq
!(string
.bytes
, b
"a");
1087 fn wtf8buf_truncate_fail_code_point_boundary() {
1088 let mut string
= Wtf8Buf
::from_str("aé");
1094 fn wtf8buf_truncate_fail_longer() {
1095 let mut string
= Wtf8Buf
::from_str("aé");
1100 fn wtf8buf_into_string() {
1101 let mut string
= Wtf8Buf
::from_str("aé 💩");
1102 assert_eq
!(string
.clone().into_string(), Ok(String
::from("aé 💩")));
1103 string
.push(CodePoint
::from_u32(0xD800).unwrap());
1104 assert_eq
!(string
.clone().into_string(), Err(string
));
1108 fn wtf8buf_into_string_lossy() {
1109 let mut string
= Wtf8Buf
::from_str("aé 💩");
1110 assert_eq
!(string
.clone().into_string_lossy(), String
::from("aé 💩"));
1111 string
.push(CodePoint
::from_u32(0xD800).unwrap());
1112 assert_eq
!(string
.clone().into_string_lossy(), String
::from("aé 💩�"));
1116 fn wtf8buf_from_iterator() {
1117 fn f(values
: &[u32]) -> Wtf8Buf
{
1118 values
.iter().map(|&c
| CodePoint
::from_u32(c
).unwrap()).collect
::<Wtf8Buf
>()
1120 assert_eq
!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes
, b
"a\xC3\xA9 \xF0\x9F\x92\xA9");
1122 assert_eq
!(f(&[0xD83D, 0xDCA9]).bytes
, b
"\xF0\x9F\x92\xA9"); // Magic!
1123 assert_eq
!(f(&[0xD83D, 0x20, 0xDCA9]).bytes
, b
"\xED\xA0\xBD \xED\xB2\xA9");
1124 assert_eq
!(f(&[0xD800, 0xDBFF]).bytes
, b
"\xED\xA0\x80\xED\xAF\xBF");
1125 assert_eq
!(f(&[0xD800, 0xE000]).bytes
, b
"\xED\xA0\x80\xEE\x80\x80");
1126 assert_eq
!(f(&[0xD7FF, 0xDC00]).bytes
, b
"\xED\x9F\xBF\xED\xB0\x80");
1127 assert_eq
!(f(&[0x61, 0xDC00]).bytes
, b
"\x61\xED\xB0\x80");
1128 assert_eq
!(f(&[0xDC00]).bytes
, b
"\xED\xB0\x80");
1132 fn wtf8buf_extend() {
1133 fn e(initial
: &[u32], extended
: &[u32]) -> Wtf8Buf
{
1134 fn c(value
: &u32) -> CodePoint { CodePoint::from_u32(*value).unwrap() }
1135 let mut string
= initial
.iter().map(c
).collect
::<Wtf8Buf
>();
1136 string
.extend(extended
.iter().map(c
));
1140 assert_eq
!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes
,
1141 b
"a\xC3\xA9 \xF0\x9F\x92\xA9");
1143 assert_eq
!(e(&[0xD83D], &[0xDCA9]).bytes
, b
"\xF0\x9F\x92\xA9"); // Magic!
1144 assert_eq
!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes
, b
"\xED\xA0\xBD \xED\xB2\xA9");
1145 assert_eq
!(e(&[0xD800], &[0xDBFF]).bytes
, b
"\xED\xA0\x80\xED\xAF\xBF");
1146 assert_eq
!(e(&[0xD800], &[0xE000]).bytes
, b
"\xED\xA0\x80\xEE\x80\x80");
1147 assert_eq
!(e(&[0xD7FF], &[0xDC00]).bytes
, b
"\xED\x9F\xBF\xED\xB0\x80");
1148 assert_eq
!(e(&[0x61], &[0xDC00]).bytes
, b
"\x61\xED\xB0\x80");
1149 assert_eq
!(e(&[], &[0xDC00]).bytes
, b
"\xED\xB0\x80");
1154 let mut string
= Wtf8Buf
::from_str("a\té \u{7f}💩\r");
1155 string
.push(CodePoint
::from_u32(0xD800).unwrap());
1156 assert_eq
!(format
!("{:?}", string
), "\"a\\té \\u{7f}\u{1f4a9}\\r\\u{d800}\"");
1160 fn wtf8buf_as_slice() {
1161 assert_eq
!(Wtf8Buf
::from_str("aé").as_slice(), Wtf8
::from_str("aé"));
1165 fn wtf8buf_show_str() {
1166 let text
= "a\té 💩\r";
1167 let string
= Wtf8Buf
::from_str(text
);
1168 assert_eq
!(format
!("{:?}", text
), format
!("{:?}", string
));
1172 fn wtf8_from_str() {
1173 assert_eq
!(&Wtf8
::from_str("").bytes
, b
"");
1174 assert_eq
!(&Wtf8
::from_str("aé 💩").bytes
, b
"a\xC3\xA9 \xF0\x9F\x92\xA9");
1179 assert_eq
!(Wtf8
::from_str("").len(), 0);
1180 assert_eq
!(Wtf8
::from_str("aé 💩").len(), 8);
1185 assert_eq
!(&Wtf8
::from_str("aé 💩")[1.. 4].bytes
, b
"\xC3\xA9 ");
1190 fn wtf8_slice_not_code_point_boundary() {
1191 &Wtf8
::from_str("aé 💩")[2.. 4];
1195 fn wtf8_slice_from() {
1196 assert_eq
!(&Wtf8
::from_str("aé 💩")[1..].bytes
, b
"\xC3\xA9 \xF0\x9F\x92\xA9");
1201 fn wtf8_slice_from_not_code_point_boundary() {
1202 &Wtf8
::from_str("aé 💩")[2..];
1206 fn wtf8_slice_to() {
1207 assert_eq
!(&Wtf8
::from_str("aé 💩")[..4].bytes
, b
"a\xC3\xA9 ");
1212 fn wtf8_slice_to_not_code_point_boundary() {
1213 &Wtf8
::from_str("aé 💩")[5..];
1217 fn wtf8_ascii_byte_at() {
1218 let slice
= Wtf8
::from_str("aé 💩");
1219 assert_eq
!(slice
.ascii_byte_at(0), b'a'
);
1220 assert_eq
!(slice
.ascii_byte_at(1), b'
\xFF'
);
1221 assert_eq
!(slice
.ascii_byte_at(2), b'
\xFF'
);
1222 assert_eq
!(slice
.ascii_byte_at(3), b' '
);
1223 assert_eq
!(slice
.ascii_byte_at(4), b'
\xFF'
);
1227 fn wtf8_code_points() {
1228 fn c(value
: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
1229 fn cp(string
: &Wtf8Buf
) -> Vec
<Option
<char>> {
1230 string
.code_points().map(|c
| c
.to_char()).collect
::<Vec
<_
>>()
1232 let mut string
= Wtf8Buf
::from_str("é ");
1233 assert_eq
!(cp(&string
), [Some('é'
), Some(' '
)]);
1234 string
.push(c(0xD83D));
1235 assert_eq
!(cp(&string
), [Some('é'
), Some(' '
), None
]);
1236 string
.push(c(0xDCA9));
1237 assert_eq
!(cp(&string
), [Some('é'
), Some(' '
), Some('💩'
)]);
1242 assert_eq
!(Wtf8
::from_str("").as_str(), Some(""));
1243 assert_eq
!(Wtf8
::from_str("aé 💩").as_str(), Some("aé 💩"));
1244 let mut string
= Wtf8Buf
::new();
1245 string
.push(CodePoint
::from_u32(0xD800).unwrap());
1246 assert_eq
!(string
.as_str(), None
);
1250 fn wtf8_to_string_lossy() {
1251 assert_eq
!(Wtf8
::from_str("").to_string_lossy(), Cow
::Borrowed(""));
1252 assert_eq
!(Wtf8
::from_str("aé 💩").to_string_lossy(), Cow
::Borrowed("aé 💩"));
1253 let mut string
= Wtf8Buf
::from_str("aé 💩");
1254 string
.push(CodePoint
::from_u32(0xD800).unwrap());
1255 let expected
: Cow
<str> = Cow
::Owned(String
::from("aé 💩�"));
1256 assert_eq
!(string
.to_string_lossy(), expected
);
1261 fn d(b
: &[u8]) -> String
{
1262 format
!("{}", &unsafe { Wtf8::from_bytes_unchecked(b) }
)
1265 assert_eq
!("", d("".as_bytes()));
1266 assert_eq
!("aé 💩", d("aé 💩".as_bytes()));
1268 let mut string
= Wtf8Buf
::from_str("aé 💩");
1269 string
.push(CodePoint
::from_u32(0xD800).unwrap());
1270 assert_eq
!("aé 💩�", d(string
.as_inner()));
1274 fn wtf8_encode_wide() {
1275 let mut string
= Wtf8Buf
::from_str("aé ");
1276 string
.push(CodePoint
::from_u32(0xD83D).unwrap());
1277 string
.push_char('💩'
);
1278 assert_eq
!(string
.encode_wide().collect
::<Vec
<_
>>(),
1279 vec
![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]);