1extern crate alloc;
23
24use alloc::{
25 borrow::{Borrow, Cow},
26 string::String,
27 vec::Vec,
28};
29use core::{
30 fmt, hash,
31 iter::{FromIterator, IntoIterator},
32 mem::transmute,
33 ops::Deref,
34 slice, str,
35 str::FromStr,
36};
37use std::ops::Add;
38
39mod not_quite_std;
40
41static UTF8_REPLACEMENT_CHARACTER: &[u8] = b"\xEF\xBF\xBD";
42
43#[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
49pub struct CodePoint {
50 value: u32,
51}
52
53impl Copy for CodePoint {}
54
55impl fmt::Debug for CodePoint {
58 #[inline]
59 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
60 write!(formatter, "U+{:04X}", self.value)
61 }
62}
63
64impl CodePoint {
65 #[inline]
71 pub const unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
72 CodePoint { value }
73 }
74
75 #[inline]
79 pub const fn from_u32(value: u32) -> Option<CodePoint> {
80 match value {
81 0..=0x10ffff => Some(CodePoint { value }),
82 _ => None,
83 }
84 }
85
86 #[inline]
90 pub const fn from_char(value: char) -> CodePoint {
91 CodePoint {
92 value: value as u32,
93 }
94 }
95
96 #[inline]
98 pub fn to_u32(&self) -> u32 {
99 self.value
100 }
101
102 #[inline]
106 pub fn to_char(&self) -> Option<char> {
107 match self.value {
108 0xd800..=0xdfff => None,
109 _ => Some(unsafe { char::from_u32_unchecked(self.value) }),
110 }
111 }
112
113 #[inline]
118 pub fn to_char_lossy(&self) -> char {
119 self.to_char().unwrap_or('\u{FFFD}')
120 }
121
122 #[inline]
124 pub fn is_ascii(&self) -> bool {
125 self.value <= 0x7f
126 }
127}
128
129impl PartialEq<char> for CodePoint {
130 fn eq(&self, other: &char) -> bool {
131 self.value == *other as u32
132 }
133}
134
135#[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
140pub struct Wtf8Buf {
141 bytes: Vec<u8>,
142}
143
144impl Deref for Wtf8Buf {
145 type Target = Wtf8;
146
147 fn deref(&self) -> &Wtf8 {
148 unsafe { transmute(&*self.bytes) }
149 }
150}
151
152impl fmt::Debug for Wtf8Buf {
156 #[inline]
157 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
158 Wtf8::fmt(self, formatter)
159 }
160}
161
162impl Default for Wtf8Buf {
163 #[inline]
164 fn default() -> Self {
165 Self::new()
166 }
167}
168
169impl FromStr for Wtf8Buf {
170 type Err = core::convert::Infallible;
171
172 #[inline]
173 fn from_str(s: &str) -> Result<Self, Self::Err> {
174 Ok(Wtf8Buf {
175 bytes: s.as_bytes().to_vec(),
176 })
177 }
178}
179
180impl fmt::Write for Wtf8Buf {
181 fn write_str(&mut self, s: &str) -> std::fmt::Result {
182 self.push_str(s);
183 Ok(())
184 }
185}
186
187impl Add<&Wtf8> for Wtf8Buf {
188 type Output = Wtf8Buf;
189
190 fn add(self, rhs: &Wtf8) -> Self::Output {
191 let mut result = self;
192 result.push_wtf8(rhs);
193 result
194 }
195}
196
197impl Wtf8Buf {
198 #[inline]
200 pub fn new() -> Wtf8Buf {
201 Wtf8Buf { bytes: Vec::new() }
202 }
203
204 #[inline]
207 pub fn with_capacity(n: usize) -> Wtf8Buf {
208 Wtf8Buf {
209 bytes: Vec::with_capacity(n),
210 }
211 }
212
213 #[inline]
219 pub fn from_string(string: String) -> Wtf8Buf {
220 Wtf8Buf {
221 bytes: string.into_bytes(),
222 }
223 }
224
225 #[inline]
231 #[allow(clippy::should_implement_trait)]
232 pub fn from_str(s: &str) -> Wtf8Buf {
233 Wtf8Buf {
234 bytes: s.as_bytes().to_vec(),
235 }
236 }
237
238 pub fn from_ill_formed_utf16(v: &[u16]) -> Wtf8Buf {
244 let mut string = Wtf8Buf::with_capacity(v.len());
245 for item in not_quite_std::decode_utf16(v.iter().cloned()) {
246 match item {
247 Ok(c) => string.push_char(c),
248 Err(s) => {
249 let code_point = unsafe { CodePoint::from_u32_unchecked(s as u32) };
251 not_quite_std::push_code_point(&mut string, code_point)
254 }
255 }
256 }
257 string
258 }
259
260 #[inline]
268 pub fn reserve(&mut self, additional: usize) {
269 self.bytes.reserve(additional)
270 }
271
272 #[inline]
275 pub fn capacity(&self) -> usize {
276 self.bytes.capacity()
277 }
278
279 #[inline]
281 pub fn push_str(&mut self, other: &str) {
282 self.bytes.extend_from_slice(other.as_bytes())
283 }
284
285 #[inline]
291 pub fn push_wtf8(&mut self, other: &Wtf8) {
292 match (self.final_lead_surrogate(), other.initial_trail_surrogate()) {
293 (Some(lead), Some(trail)) => {
295 let len_without_lead_surrogate = self.len() - 3;
296 self.bytes.truncate(len_without_lead_surrogate);
297 let other_without_trail_surrogate = &other.bytes[3..];
298 self.bytes.reserve(4 + other_without_trail_surrogate.len());
300 self.push_char(decode_surrogate_pair(lead, trail));
301 self.bytes.extend_from_slice(other_without_trail_surrogate);
302 }
303 _ => self.bytes.extend_from_slice(&other.bytes),
304 }
305 }
306
307 #[inline]
309 pub fn push_char(&mut self, c: char) {
310 not_quite_std::push_code_point(self, CodePoint::from_char(c))
311 }
312
313 #[inline]
319 pub fn push(&mut self, code_point: CodePoint) {
320 if let trail @ 0xdc00..=0xdfff = code_point.to_u32() {
321 if let Some(lead) = self.final_lead_surrogate() {
322 let len_without_lead_surrogate = self.len() - 3;
323 self.bytes.truncate(len_without_lead_surrogate);
324 self.push_char(decode_surrogate_pair(lead, trail as u16));
325 return;
326 }
327 }
328
329 not_quite_std::push_code_point(self, code_point)
331 }
332
333 #[inline]
340 pub fn truncate(&mut self, new_len: usize) {
341 assert!(not_quite_std::is_code_point_boundary(self, new_len));
342 self.bytes.truncate(new_len)
343 }
344
345 #[inline]
347 pub fn clear(&mut self) {
348 self.bytes.clear();
349 }
350
351 pub fn into_string(self) -> Result<String, Wtf8Buf> {
359 match self.next_surrogate(0) {
360 None => Ok(unsafe { String::from_utf8_unchecked(self.bytes) }),
361 Some(_) => Err(self),
362 }
363 }
364
365 pub fn into_string_lossy(mut self) -> String {
372 let mut pos = 0;
373 loop {
374 match self.next_surrogate(pos) {
375 Some((surrogate_pos, _)) => {
376 pos = surrogate_pos + 3;
377 self.bytes[surrogate_pos..pos].copy_from_slice(UTF8_REPLACEMENT_CHARACTER);
378 }
379 None => return unsafe { String::from_utf8_unchecked(self.bytes) },
380 }
381 }
382 }
383
384 pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, Vec<u8>> {
398 if not_quite_std::validate_wtf8(&bytes) {
399 Ok(Self { bytes })
400 } else {
401 Err(bytes)
402 }
403 }
404
405 #[inline]
415 pub unsafe fn from_bytes_unchecked(bytes: Vec<u8>) -> Self {
416 Self { bytes }
417 }
418}
419
420impl FromIterator<CodePoint> for Wtf8Buf {
425 fn from_iter<T: IntoIterator<Item = CodePoint>>(iterable: T) -> Wtf8Buf {
426 let mut string = Wtf8Buf::new();
427 string.extend(iterable);
428 string
429 }
430}
431
432impl Extend<CodePoint> for Wtf8Buf {
437 fn extend<T: IntoIterator<Item = CodePoint>>(&mut self, iterable: T) {
438 let iterator = iterable.into_iter();
439 let (low, _high) = iterator.size_hint();
440 self.bytes.reserve(low);
442 for code_point in iterator {
443 self.push(code_point);
444 }
445 }
446}
447
448#[repr(transparent)]
453#[derive(PartialEq, Eq, PartialOrd, Ord)]
454pub struct Wtf8 {
455 bytes: [u8],
456}
457
458impl fmt::Debug for Wtf8 {
462 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
463 formatter.write_str("\"")?;
464 let mut pos = 0;
465 loop {
466 match self.next_surrogate(pos) {
467 None => break,
468 Some((surrogate_pos, surrogate)) => {
469 formatter.write_str(unsafe {
470 str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos])
471 })?;
472 write!(formatter, "\\u{{{surrogate:X}}}")?;
473 pos = surrogate_pos + 3;
474 }
475 }
476 }
477 formatter.write_str(unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?;
478 formatter.write_str("\"")
479 }
480}
481
482impl Wtf8 {
483 #[inline]
487 pub const fn from_str(value: &str) -> &Wtf8 {
488 unsafe { transmute(value.as_bytes()) }
489 }
490
491 #[inline]
493 pub const fn len(&self) -> usize {
494 self.bytes.len()
495 }
496
497 #[inline]
499 pub const fn is_empty(&self) -> bool {
500 self.bytes.is_empty()
501 }
502
503 #[inline]
505 pub const fn is_ascii(&self) -> bool {
506 let mut i = 0;
507
508 while i < self.bytes.len() {
509 if !self.bytes[i].is_ascii() {
510 return false;
511 }
512
513 i += 1;
514 }
515
516 true
517 }
518
519 #[inline]
526 pub fn slice(&self, begin: usize, end: usize) -> &Wtf8 {
527 if begin <= end
529 && not_quite_std::is_code_point_boundary(self, begin)
530 && not_quite_std::is_code_point_boundary(self, end)
531 {
532 unsafe { not_quite_std::slice_unchecked(self, begin, end) }
533 } else {
534 not_quite_std::slice_error_fail(self, begin, end)
535 }
536 }
537
538 #[inline]
545 pub fn slice_from(&self, begin: usize) -> &Wtf8 {
546 if not_quite_std::is_code_point_boundary(self, begin) {
548 unsafe { not_quite_std::slice_unchecked(self, begin, self.len()) }
549 } else {
550 not_quite_std::slice_error_fail(self, begin, self.len())
551 }
552 }
553
554 #[inline]
561 pub fn slice_to(&self, end: usize) -> &Wtf8 {
562 if not_quite_std::is_code_point_boundary(self, end) {
564 unsafe { not_quite_std::slice_unchecked(self, 0, end) }
565 } else {
566 not_quite_std::slice_error_fail(self, 0, end)
567 }
568 }
569
570 #[inline]
577 pub fn ascii_byte_at(&self, position: usize) -> u8 {
578 match self.bytes[position] {
579 ascii_byte @ 0x00..=0x7f => ascii_byte,
580 _ => 0xff,
581 }
582 }
583
584 #[inline]
586 pub fn code_points(&self) -> Wtf8CodePoints<'_> {
587 Wtf8CodePoints {
588 bytes: self.bytes.iter(),
589 }
590 }
591
592 #[inline]
594 pub fn contains_char(&self, ch: char) -> bool {
595 let target = CodePoint::from_char(ch);
596 self.contains(target)
597 }
598
599 #[inline]
601 pub fn contains(&self, code_point: CodePoint) -> bool {
602 self.code_points().any(|cp| cp == code_point)
603 }
604
605 #[inline]
607 pub fn starts_with(&self, pattern: &str) -> bool {
608 self.as_bytes().starts_with(pattern.as_bytes())
609 }
610
611 #[inline]
617 pub fn as_str(&self) -> Option<&str> {
618 match self.next_surrogate(0) {
621 None => Some(unsafe { str::from_utf8_unchecked(&self.bytes) }),
622 Some(_) => None,
623 }
624 }
625
626 #[inline]
628 pub const fn as_bytes(&self) -> &[u8] {
629 &self.bytes
630 }
631
632 pub fn to_string_lossy(&self) -> Cow<'_, str> {
640 let surrogate_pos = match self.next_surrogate(0) {
641 None => return Cow::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) }),
642 Some((pos, _)) => pos,
643 };
644 let wtf8_bytes = &self.bytes;
645 let mut utf8_bytes = Vec::with_capacity(self.len());
646 utf8_bytes.extend_from_slice(&wtf8_bytes[..surrogate_pos]);
647 utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER);
648 let mut pos = surrogate_pos + 3;
649 loop {
650 match self.next_surrogate(pos) {
651 Some((surrogate_pos, _)) => {
652 utf8_bytes.extend_from_slice(&wtf8_bytes[pos..surrogate_pos]);
653 utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER);
654 pos = surrogate_pos + 3;
655 }
656 None => {
657 utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]);
658 return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) });
659 }
660 }
661 }
662 }
663
664 #[inline]
671 pub fn to_ill_formed_utf16(&self) -> IllFormedUtf16CodeUnits<'_> {
672 IllFormedUtf16CodeUnits {
673 code_points: self.code_points(),
674 extra: 0,
675 }
676 }
677
678 #[inline]
680 pub fn to_uppercase(&self) -> Wtf8Buf {
681 let mut result = Wtf8Buf::with_capacity(self.len());
682 for cp in self.code_points() {
683 if let Some(ch) = cp.to_char() {
684 for upper_ch in ch.to_uppercase() {
685 result.push_char(upper_ch);
686 }
687 } else {
688 let code_point = unsafe { CodePoint::from_u32_unchecked(cp.to_u32()) };
690 not_quite_std::push_code_point(&mut result, code_point)
693 }
694 }
695 result
696 }
697
698 #[inline]
700 pub fn to_lowercase(&self) -> Wtf8Buf {
701 let mut result = Wtf8Buf::with_capacity(self.len());
702 for cp in self.code_points() {
703 if let Some(ch) = cp.to_char() {
704 for lower_ch in ch.to_lowercase() {
705 result.push_char(lower_ch);
706 }
707 } else {
708 let code_point = unsafe { CodePoint::from_u32_unchecked(cp.to_u32()) };
710 not_quite_std::push_code_point(&mut result, code_point)
713 }
714 }
715 result
716 }
717
718 pub fn from_bytes(bytes: &[u8]) -> Result<&Wtf8, &[u8]> {
732 if not_quite_std::validate_wtf8(bytes) {
733 Ok(unsafe { transmute::<&[u8], &Wtf8>(bytes) })
734 } else {
735 Err(bytes)
736 }
737 }
738
739 #[inline]
749 pub const unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Wtf8 {
750 unsafe { transmute(bytes) }
751 }
752
753 #[inline]
754 fn next_surrogate(&self, mut pos: usize) -> Option<(usize, u16)> {
755 let mut iter = self.bytes[pos..].iter();
756 loop {
757 let b = match iter.next() {
758 None => return None,
759 Some(&b) => b,
760 };
761 if b < 0x80 {
762 pos += 1;
763 } else if b < 0xe0 {
764 iter.next();
765 pos += 2;
766 } else if b == 0xed {
767 match (iter.next(), iter.next()) {
768 (Some(&b2), Some(&b3)) if b2 >= 0xa0 => {
769 return Some((pos, decode_surrogate(b2, b3)))
770 }
771 _ => pos += 3,
772 }
773 } else if b < 0xf0 {
774 iter.next();
775 iter.next();
776 pos += 3;
777 } else {
778 iter.next();
779 iter.next();
780 iter.next();
781 pos += 4;
782 }
783 }
784 }
785
786 #[inline]
787 fn final_lead_surrogate(&self) -> Option<u16> {
788 let len = self.len();
789 if len < 3 {
790 return None;
791 }
792 let seq = &self.bytes[len - 3..];
793 if seq[0] == 0xed && 0xa0 <= seq[1] && seq[1] <= 0xaf {
794 Some(decode_surrogate(seq[1], seq[2]))
795 } else {
796 None
797 }
798 }
799
800 #[inline]
801 fn initial_trail_surrogate(&self) -> Option<u16> {
802 let len = self.len();
803 if len < 3 {
804 return None;
805 }
806 let seq = &self.bytes[..3];
807 if seq[0] == 0xed && 0xb0 <= seq[1] && seq[1] <= 0xbf {
808 Some(decode_surrogate(seq[1], seq[2]))
809 } else {
810 None
811 }
812 }
813}
814
815#[inline]
816fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 {
817 0xd800 | (second_byte as u16 & 0x3f) << 6 | third_byte as u16 & 0x3f
819}
820
821#[inline]
822fn decode_surrogate_pair(lead: u16, trail: u16) -> char {
823 let code_point = 0x10000 + (((lead as u32 - 0xd800) << 10) | (trail as u32 - 0xdc00));
824 unsafe { char::from_u32_unchecked(code_point) }
825}
826
827#[derive(Clone)]
831pub struct Wtf8CodePoints<'a> {
832 bytes: slice::Iter<'a, u8>,
833}
834
835impl<'a> Iterator for Wtf8CodePoints<'a> {
836 type Item = CodePoint;
837
838 #[inline]
839 fn next(&mut self) -> Option<CodePoint> {
840 not_quite_std::next_code_point(&mut self.bytes).map(|value| {
841 unsafe { CodePoint::from_u32_unchecked(value) }
843 })
844 }
845
846 #[inline]
847 fn size_hint(&self) -> (usize, Option<usize>) {
848 let (len, _) = self.bytes.size_hint();
849 (len.saturating_add(3) / 4, Some(len))
850 }
851}
852
853#[derive(Clone)]
854pub struct IllFormedUtf16CodeUnits<'a> {
855 code_points: Wtf8CodePoints<'a>,
856 extra: u16,
857}
858
859impl<'a> Iterator for IllFormedUtf16CodeUnits<'a> {
860 type Item = u16;
861
862 #[inline]
863 fn next(&mut self) -> Option<u16> {
864 not_quite_std::next_utf16_code_unit(self)
865 }
866
867 #[inline]
868 fn size_hint(&self) -> (usize, Option<usize>) {
869 let (low, high) = self.code_points.size_hint();
870 (low, high.and_then(|n| n.checked_mul(2)))
874 }
875}
876
877impl PartialEq<&Wtf8> for Wtf8Buf {
878 fn eq(&self, other: &&Wtf8) -> bool {
879 **self == **other
880 }
881}
882
883impl PartialEq<Wtf8Buf> for &Wtf8 {
884 fn eq(&self, other: &Wtf8Buf) -> bool {
885 **self == **other
886 }
887}
888
889impl PartialEq<str> for &Wtf8 {
890 fn eq(&self, other: &str) -> bool {
891 match self.as_str() {
892 Some(s) => s == other,
893 None => false,
894 }
895 }
896}
897
898impl PartialEq<&str> for &Wtf8 {
899 fn eq(&self, other: &&str) -> bool {
900 match self.as_str() {
901 Some(s) => s == *other,
902 None => false,
903 }
904 }
905}
906
907impl hash::Hash for CodePoint {
908 #[inline]
909 fn hash<H: hash::Hasher>(&self, state: &mut H) {
910 self.value.hash(state)
911 }
912}
913
914impl hash::Hash for Wtf8Buf {
915 #[inline]
916 fn hash<H: hash::Hasher>(&self, state: &mut H) {
917 Wtf8::hash(self, state)
918 }
919}
920
921impl hash::Hash for Wtf8 {
922 #[inline]
923 fn hash<H: hash::Hasher>(&self, state: &mut H) {
924 state.write(&self.bytes);
925 0xfeu8.hash(state)
926 }
927}
928
929impl Borrow<Wtf8> for Wtf8Buf {
930 #[inline]
931 fn borrow(&self) -> &Wtf8 {
932 self
933 }
934}
935
936impl ToOwned for Wtf8 {
937 type Owned = Wtf8Buf;
938
939 #[inline]
940 fn to_owned(&self) -> Wtf8Buf {
941 Wtf8Buf {
942 bytes: self.bytes.to_vec(),
943 }
944 }
945}
946
947impl<'a> From<&'a Wtf8> for Cow<'a, Wtf8> {
948 #[inline]
949 fn from(s: &'a Wtf8) -> Cow<'a, Wtf8> {
950 Cow::Borrowed(s)
951 }
952}
953
954impl<'a> From<&'a str> for &'a Wtf8 {
955 #[inline]
956 fn from(s: &'a str) -> &'a Wtf8 {
957 Wtf8::from_str(s)
958 }
959}
960
961impl<'a> From<Wtf8Buf> for Cow<'a, Wtf8> {
962 #[inline]
963 fn from(s: Wtf8Buf) -> Cow<'a, Wtf8> {
964 Cow::Owned(s)
965 }
966}
967
968#[cfg(test)]
969mod tests {
970 use alloc::{format, vec};
971 use core::mem::transmute;
972
973 use super::*;
974
975 #[test]
976 fn code_point_from_u32() {
977 assert!(CodePoint::from_u32(0).is_some());
978 assert!(CodePoint::from_u32(0xd800).is_some());
979 assert!(CodePoint::from_u32(0x10ffff).is_some());
980 assert!(CodePoint::from_u32(0x110000).is_none());
981 }
982
983 #[test]
984 fn code_point_to_u32() {
985 fn c(value: u32) -> CodePoint {
986 CodePoint::from_u32(value).unwrap()
987 }
988 assert_eq!(c(0).to_u32(), 0);
989 assert_eq!(c(0xd800).to_u32(), 0xd800);
990 assert_eq!(c(0x10ffff).to_u32(), 0x10ffff);
991 }
992
993 #[test]
994 fn code_point_from_char() {
995 assert_eq!(CodePoint::from_char('a').to_u32(), 0x61);
996 assert_eq!(CodePoint::from_char('💩').to_u32(), 0x1f4a9);
997 }
998
999 #[test]
1000 fn code_point_to_string() {
1001 let cp_a = CodePoint::from_char('a');
1002 assert_eq!(format!("{cp_a:?}"), "U+0061");
1003 let cp_poop = CodePoint::from_char('💩');
1004 assert_eq!(format!("{cp_poop:?}"), "U+1F4A9");
1005 }
1006
1007 #[test]
1008 fn code_point_to_char() {
1009 fn c(value: u32) -> CodePoint {
1010 CodePoint::from_u32(value).unwrap()
1011 }
1012 assert_eq!(c(0x61).to_char(), Some('a'));
1013 assert_eq!(c(0x1f4a9).to_char(), Some('💩'));
1014 assert_eq!(c(0xd800).to_char(), None);
1015 }
1016
1017 #[test]
1018 fn code_point_to_char_lossy() {
1019 fn c(value: u32) -> CodePoint {
1020 CodePoint::from_u32(value).unwrap()
1021 }
1022 assert_eq!(c(0x61).to_char_lossy(), 'a');
1023 assert_eq!(c(0x1f4a9).to_char_lossy(), '💩');
1024 assert_eq!(c(0xd800).to_char_lossy(), '\u{FFFD}');
1025 }
1026
1027 #[test]
1028 fn wtf8buf_new() {
1029 assert_eq!(Wtf8Buf::new().bytes, b"");
1030 }
1031
1032 #[test]
1033 fn wtf8buf_from_str() {
1034 assert_eq!(Wtf8Buf::from_str("").bytes, b"");
1035 assert_eq!(
1036 Wtf8Buf::from_str("aé 💩").bytes,
1037 b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1038 );
1039 }
1040
1041 #[test]
1042 fn wtf8buf_from_string() {
1043 assert_eq!(Wtf8Buf::from_string(String::from("")).bytes, b"");
1044 assert_eq!(
1045 Wtf8Buf::from_string(String::from("aé 💩")).bytes,
1046 b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1047 );
1048 }
1049
1050 #[test]
1051 fn wtf8buf_from_ill_formed_utf16() {
1052 assert_eq!(Wtf8Buf::from_ill_formed_utf16(&[]).bytes, b"");
1053 assert_eq!(
1054 Wtf8Buf::from_ill_formed_utf16(&[0x61, 0xe9, 0x20, 0xd83d, 0xd83d, 0xdca9]).bytes,
1055 b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9"
1056 );
1057 }
1058
1059 #[test]
1060 fn wtf8buf_push_str() {
1061 let mut string = Wtf8Buf::new();
1062 assert_eq!(string.bytes, b"");
1063 string.push_str("aé 💩");
1064 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1065 }
1066
1067 #[test]
1068 fn wtf8buf_push_char() {
1069 let mut string = Wtf8Buf::from_str("aé ");
1070 assert_eq!(string.bytes, b"a\xC3\xA9 ");
1071 string.push_char('💩');
1072 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1073 }
1074
1075 #[test]
1076 fn wtf8buf_push_code_points_of_each_encoded_width() {
1077 fn code_point(value: u32) -> CodePoint {
1078 CodePoint::from_u32(value).unwrap()
1079 }
1080
1081 let mut string = Wtf8Buf::new();
1082
1083 string.push(code_point(0x7f));
1084 assert_eq!(string.bytes, b"\x7f");
1085
1086 string.push(code_point(0x80));
1087 assert_eq!(string.bytes, b"\x7f\xc2\x80");
1088
1089 string.push(code_point(0x800));
1090 assert_eq!(string.bytes, b"\x7f\xc2\x80\xe0\xa0\x80");
1091
1092 string.push(code_point(0xd800));
1093 assert_eq!(string.bytes, b"\x7f\xc2\x80\xe0\xa0\x80\xed\xa0\x80");
1094
1095 string.push(code_point(0x10000));
1096 assert_eq!(
1097 string.bytes,
1098 b"\x7f\xc2\x80\xe0\xa0\x80\xed\xa0\x80\xf0\x90\x80\x80"
1099 );
1100 }
1101
1102 #[test]
1103 fn wtf8buf_push() {
1104 let mut string = Wtf8Buf::from_str("aé ");
1105 assert_eq!(string.bytes, b"a\xC3\xA9 ");
1106 string.push(CodePoint::from_char('💩'));
1107 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1108
1109 fn c(value: u32) -> CodePoint {
1110 CodePoint::from_u32(value).unwrap()
1111 }
1112
1113 let mut string = Wtf8Buf::new();
1114 string.push(c(0xd83d)); string.push(c(0xdca9)); assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); let mut string = Wtf8Buf::new();
1119 string.push(c(0xd83d)); string.push(c(0x20)); string.push(c(0xdca9)); assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1123
1124 let mut string = Wtf8Buf::new();
1125 string.push(c(0xd800)); string.push(c(0xdbff)); assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1128
1129 let mut string = Wtf8Buf::new();
1130 string.push(c(0xd800)); string.push(c(0xe000)); assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
1133
1134 let mut string = Wtf8Buf::new();
1135 string.push(c(0xd7ff)); string.push(c(0xdc00)); assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1138
1139 let mut string = Wtf8Buf::new();
1140 string.push(c(0x61)); string.push(c(0xdc00)); assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
1143
1144 let mut string = Wtf8Buf::new();
1145 string.push(c(0xdc00)); assert_eq!(string.bytes, b"\xED\xB0\x80");
1147 }
1148
1149 #[test]
1150 fn wtf8buf_push_wtf8() {
1151 let mut string = Wtf8Buf::from_str("aé");
1152 assert_eq!(string.bytes, b"a\xC3\xA9");
1153 string.push_wtf8(Wtf8::from_str(" 💩"));
1154 assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
1155
1156 fn w(value: &[u8]) -> &Wtf8 {
1157 unsafe { transmute(value) }
1158 }
1159
1160 let mut string = Wtf8Buf::new();
1161 string.push_wtf8(w(b"\xED\xA0\xBD")); string.push_wtf8(w(b"\xED\xB2\xA9")); assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); let mut string = Wtf8Buf::new();
1166 string.push_wtf8(w(b"\xED\xA0\xBD")); string.push_wtf8(w(b" ")); string.push_wtf8(w(b"\xED\xB2\xA9")); assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
1170
1171 let mut string = Wtf8Buf::new();
1172 string.push_wtf8(w(b"\xED\xA0\x80")); string.push_wtf8(w(b"\xED\xAF\xBF")); assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1175
1176 let mut string = Wtf8Buf::new();
1177 string.push_wtf8(w(b"\xED\xA0\x80")); string.push_wtf8(w(b"\xEE\x80\x80")); assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
1180
1181 let mut string = Wtf8Buf::new();
1182 string.push_wtf8(w(b"\xED\x9F\xBF")); string.push_wtf8(w(b"\xED\xB0\x80")); assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1185
1186 let mut string = Wtf8Buf::new();
1187 string.push_wtf8(w(b"a")); string.push_wtf8(w(b"\xED\xB0\x80")); assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
1190
1191 let mut string = Wtf8Buf::new();
1192 string.push_wtf8(w(b"\xED\xB0\x80")); assert_eq!(string.bytes, b"\xED\xB0\x80");
1194 }
1195
1196 #[test]
1197 fn wtf8buf_truncate() {
1198 let mut string = Wtf8Buf::from_str("aé");
1199 string.truncate(1);
1200 assert_eq!(string.bytes, b"a");
1201 }
1202
1203 #[test]
1204 #[should_panic]
1205 fn wtf8buf_truncate_fail_code_point_boundary() {
1206 let mut string = Wtf8Buf::from_str("aé");
1207 string.truncate(2);
1208 }
1209
1210 #[test]
1211 #[should_panic]
1212 fn wtf8buf_truncate_fail_longer() {
1213 let mut string = Wtf8Buf::from_str("aé");
1214 string.truncate(4);
1215 }
1216
1217 #[test]
1218 fn wtf8buf_into_string() {
1219 let mut string = Wtf8Buf::from_str("aé 💩");
1220 assert_eq!(string.clone().into_string(), Ok(String::from("aé 💩")));
1221 string.push(CodePoint::from_u32(0xd800).unwrap());
1222 assert_eq!(string.clone().into_string(), Err(string));
1223 }
1224
1225 #[test]
1226 fn wtf8buf_into_string_lossy() {
1227 let mut string = Wtf8Buf::from_str("aé 💩");
1228 assert_eq!(string.clone().into_string_lossy(), String::from("aé 💩"));
1229 string.push(CodePoint::from_u32(0xd800).unwrap());
1230 assert_eq!(string.clone().into_string_lossy(), String::from("aé 💩�"));
1231 }
1232
1233 #[test]
1234 fn wtf8buf_from_iterator() {
1235 fn f(values: &[u32]) -> Wtf8Buf {
1236 values
1237 .iter()
1238 .map(|&c| CodePoint::from_u32(c).unwrap())
1239 .collect::<Wtf8Buf>()
1240 }
1241 assert_eq!(
1242 f(&[0x61, 0xe9, 0x20, 0x1f4a9]).bytes,
1243 b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1244 );
1245
1246 assert_eq!(f(&[0xd83d, 0xdca9]).bytes, b"\xF0\x9F\x92\xA9"); assert_eq!(
1248 f(&[0xd83d, 0x20, 0xdca9]).bytes,
1249 b"\xED\xA0\xBD \xED\xB2\xA9"
1250 );
1251 assert_eq!(f(&[0xd800, 0xdbff]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1252 assert_eq!(f(&[0xd800, 0xe000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1253 assert_eq!(f(&[0xd7ff, 0xdc00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1254 assert_eq!(f(&[0x61, 0xdc00]).bytes, b"\x61\xED\xB0\x80");
1255 assert_eq!(f(&[0xdc00]).bytes, b"\xED\xB0\x80");
1256 }
1257
1258 #[test]
1259 fn wtf8buf_extend() {
1260 fn e(initial: &[u32], extended: &[u32]) -> Wtf8Buf {
1261 fn c(value: &u32) -> CodePoint {
1262 CodePoint::from_u32(*value).unwrap()
1263 }
1264 let mut string = initial.iter().map(c).collect::<Wtf8Buf>();
1265 string.extend(extended.iter().map(c));
1266 string
1267 }
1268
1269 assert_eq!(
1270 e(&[0x61, 0xe9], &[0x20, 0x1f4a9]).bytes,
1271 b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1272 );
1273
1274 assert_eq!(e(&[0xd83d], &[0xdca9]).bytes, b"\xF0\x9F\x92\xA9"); assert_eq!(
1276 e(&[0xd83d, 0x20], &[0xdca9]).bytes,
1277 b"\xED\xA0\xBD \xED\xB2\xA9"
1278 );
1279 assert_eq!(e(&[0xd800], &[0xdbff]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
1280 assert_eq!(e(&[0xd800], &[0xe000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
1281 assert_eq!(e(&[0xd7ff], &[0xdc00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
1282 assert_eq!(e(&[0x61], &[0xdc00]).bytes, b"\x61\xED\xB0\x80");
1283 assert_eq!(e(&[], &[0xdc00]).bytes, b"\xED\xB0\x80");
1284 }
1285
1286 #[test]
1287 fn wtf8buf_debug() {
1288 let mut string = Wtf8Buf::from_str("aé 💩");
1289 string.push(CodePoint::from_u32(0xd800).unwrap());
1290 assert_eq!(format!("{string:?}"), r#""aé 💩\u{D800}""#);
1291 }
1292
1293 #[test]
1294 fn wtf8buf_as_slice() {
1295 assert_eq!(Wtf8Buf::from_str("aé"), Wtf8::from_str("aé"));
1296 }
1297
1298 #[test]
1299 fn wtf8_debug() {
1300 let mut string = Wtf8Buf::from_str("aé 💩");
1301 string.push(CodePoint::from_u32(0xd800).unwrap());
1302 let string_ref = &*string;
1303 assert_eq!(format!("{string_ref:?}"), r#""aé 💩\u{D800}""#);
1304 }
1305
1306 #[test]
1307 fn wtf8_from_str() {
1308 assert_eq!(&Wtf8::from_str("").bytes, b"");
1309 assert_eq!(
1310 &Wtf8::from_str("aé 💩").bytes,
1311 b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1312 );
1313 }
1314
1315 #[test]
1316 fn wtf8_as_bytes() {
1317 assert_eq!(Wtf8::from_str("").as_bytes(), b"");
1318 assert_eq!(
1319 Wtf8::from_str("aé 💩").as_bytes(),
1320 b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1321 );
1322 }
1323
1324 #[test]
1325 fn wtf8_starts_with() {
1326 assert!(Wtf8::from_str("aé 💩").starts_with("aé"));
1327 assert!(!Wtf8::from_str("aé 💩").starts_with("a💩"));
1328 assert!(!Wtf8::from_str("aé 💩").starts_with("aé 💩!"));
1329
1330 assert!(!Wtf8::from_str("/example/path/to/日本語").starts_with("next/dist/compiled"));
1332 }
1333
1334 #[test]
1335 fn wtf8_from_bytes_unchecked() {
1336 assert_eq!(unsafe { &Wtf8::from_bytes_unchecked(b"").bytes }, b"");
1337 assert_eq!(
1338 unsafe { &Wtf8::from_bytes_unchecked(b"a\xC3\xA9 \xF0\x9F\x92\xA9").bytes },
1339 b"a\xC3\xA9 \xF0\x9F\x92\xA9"
1340 );
1341 assert_eq!(
1342 unsafe { Wtf8::from_bytes_unchecked(b"a\xC3\xA9 \xF0\x9F\x92\xA9") },
1343 Wtf8::from_str("aé 💩")
1344 )
1345 }
1346
1347 #[test]
1348 fn wtf8_cow() {
1349 let s: Cow<Wtf8> = Cow::from(Wtf8::from_str("aé 💩"));
1350 assert!(matches!(s, Cow::Borrowed(_)));
1351 let owned: Wtf8Buf = s.into_owned();
1352 assert_eq!(owned, Wtf8Buf::from_str("aé 💩"));
1353 }
1354
1355 #[test]
1356 fn wtf8_len() {
1357 assert_eq!(Wtf8::from_str("").len(), 0);
1358 assert_eq!(Wtf8::from_str("aé 💩").len(), 8);
1359 }
1360
1361 #[test]
1362 fn wtf8_slice() {
1363 assert_eq!(&Wtf8::from_str("aé 💩").slice(1, 4).bytes, b"\xC3\xA9 ");
1364 }
1365
1366 #[test]
1367 #[should_panic]
1368 fn wtf8_slice_not_code_point_boundary() {
1369 Wtf8::from_str("aé 💩").slice(2, 4);
1370 }
1371
1372 #[test]
1373 fn wtf8_slice_from() {
1374 assert_eq!(
1375 &Wtf8::from_str("aé 💩").slice_from(1).bytes,
1376 b"\xC3\xA9 \xF0\x9F\x92\xA9"
1377 );
1378 }
1379
1380 #[test]
1381 #[should_panic]
1382 fn wtf8_slice_from_not_code_point_boundary() {
1383 Wtf8::from_str("aé 💩").slice_from(2);
1384 }
1385
1386 #[test]
1387 fn wtf8_slice_to() {
1388 assert_eq!(&Wtf8::from_str("aé 💩").slice_to(4).bytes, b"a\xC3\xA9 ");
1389 }
1390
1391 #[test]
1392 #[should_panic]
1393 fn wtf8_slice_to_not_code_point_boundary() {
1394 Wtf8::from_str("aé 💩").slice_from(5);
1395 }
1396
1397 #[test]
1398 fn wtf8_ascii_byte_at() {
1399 let slice = Wtf8::from_str("aé 💩");
1400 assert_eq!(slice.ascii_byte_at(0), b'a');
1401 assert_eq!(slice.ascii_byte_at(1), b'\xFF');
1402 assert_eq!(slice.ascii_byte_at(2), b'\xFF');
1403 assert_eq!(slice.ascii_byte_at(3), b' ');
1404 assert_eq!(slice.ascii_byte_at(4), b'\xFF');
1405 }
1406
1407 #[test]
1408 fn wtf8_code_points() {
1409 fn c(value: u32) -> CodePoint {
1410 CodePoint::from_u32(value).unwrap()
1411 }
1412 fn cp(string: &Wtf8Buf) -> Vec<Option<char>> {
1413 string
1414 .code_points()
1415 .map(|c| c.to_char())
1416 .collect::<Vec<_>>()
1417 }
1418 let mut string = Wtf8Buf::from_str("é ");
1419 assert_eq!(cp(&string), vec![Some('é'), Some(' ')]);
1420 string.push(c(0xd83d));
1421 assert_eq!(cp(&string), vec![Some('é'), Some(' '), None]);
1422 string.push(c(0xdca9));
1423 assert_eq!(cp(&string), vec![Some('é'), Some(' '), Some('💩')]);
1424 }
1425
1426 #[test]
1427 fn wtf8_as_str() {
1428 assert_eq!(Wtf8::from_str("").as_str(), Some(""));
1429 assert_eq!(Wtf8::from_str("aé 💩").as_str(), Some("aé 💩"));
1430 let mut string = Wtf8Buf::new();
1431 string.push(CodePoint::from_u32(0xd800).unwrap());
1432 assert_eq!(string.as_str(), None);
1433 }
1434
1435 #[test]
1436 fn wtf8_to_string_lossy() {
1437 assert_eq!(Wtf8::from_str("").to_string_lossy(), Cow::Borrowed(""));
1438 assert_eq!(
1439 Wtf8::from_str("aé 💩").to_string_lossy(),
1440 Cow::Borrowed("aé 💩")
1441 );
1442 let mut string = Wtf8Buf::from_str("aé 💩");
1443 string.push(CodePoint::from_u32(0xd800).unwrap());
1444 assert_eq!(string.to_string_lossy(), {
1445 let o: Cow<str> = Cow::Owned(String::from("aé 💩�"));
1446 o
1447 });
1448 }
1449
1450 #[test]
1451 fn wtf8_to_ill_formed_utf16() {
1452 let mut string = Wtf8Buf::from_str("aé ");
1453 string.push(CodePoint::from_u32(0xd83d).unwrap());
1454 string.push_char('💩');
1455 assert_eq!(
1456 string.to_ill_formed_utf16().collect::<Vec<_>>(),
1457 vec![0x61, 0xe9, 0x20, 0xd83d, 0xd83d, 0xdca9]
1458 );
1459 }
1460
1461 #[test]
1462 fn wtf8buf_wtf8_from_bytes_valid() {
1463 assert!(Wtf8Buf::from_bytes(b"hello".to_vec()).is_ok());
1465 assert!(Wtf8Buf::from_bytes(b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec()).is_ok());
1466 assert!(Wtf8::from_bytes(b"hello").is_ok());
1467 assert!(Wtf8::from_bytes(b"a\xC3\xA9 \xF0\x9F\x92\xA9").is_ok());
1468
1469 assert!(Wtf8Buf::from_bytes(b"\xED\xA0\x80".to_vec()).is_ok()); assert!(Wtf8Buf::from_bytes(b"\xED\xB0\x80".to_vec()).is_ok()); assert!(Wtf8Buf::from_bytes(b"a\xED\xA0\xBD".to_vec()).is_ok()); assert!(Wtf8Buf::from_bytes(b"\xED\xB2\xA9z".to_vec()).is_ok()); assert!(Wtf8Buf::from_bytes(b"\xED\xB2\xA9\xED\xA0\xBD".to_vec()).is_ok());
1475 }
1477
1478 #[test]
1479 fn wtf8buf_wtf8_from_bytes_invalid() {
1480 assert!(Wtf8Buf::from_bytes(b"\xED\xA0\x80\xED\xB0\x80".to_vec()).is_err());
1482 assert!(Wtf8Buf::from_bytes(b"\xED\xA0\xBD\xED\xB2\xA9".to_vec()).is_err());
1483 assert!(Wtf8::from_bytes(b"\xED\xA0\x80\xED\xB0\x80").is_err());
1484 assert!(Wtf8::from_bytes(b"\xED\xA0\xBD\xED\xB2\xA9").is_err());
1485
1486 assert!(Wtf8Buf::from_bytes(vec![0xff]).is_err());
1488 assert!(Wtf8Buf::from_bytes(vec![0xc0, 0x80]).is_err()); assert!(Wtf8Buf::from_bytes(vec![0xed, 0xa0]).is_err()); assert!(Wtf8Buf::from_bytes(vec![0xf4, 0x90, 0x80, 0x80]).is_err()); let original = vec![0xff, 0xfe];
1494 let result = Wtf8Buf::from_bytes(original.clone());
1495 assert_eq!(result.unwrap_err(), original);
1496
1497 let result = Wtf8::from_bytes(&original);
1498 assert_eq!(result.unwrap_err(), original);
1499 }
1500}