1#![unstable(
14 feature = "wtf8_internals",
15 issue = "none",
16 reason = "this is internal code for representing OsStr on some platforms and not a public API"
17)]
18#![doc(hidden)]
21
22use crate::char::{EscapeDebugExtArgs, encode_utf16_raw};
23use crate::clone::CloneToUninit;
24use crate::fmt::{self, Write};
25use crate::hash::{Hash, Hasher};
26use crate::iter::FusedIterator;
27use crate::num::niche_types::CodePointInner;
28use crate::str::next_code_point;
29use crate::{ops, slice, str};
30
31#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
37#[doc(hidden)]
38pub struct CodePoint(CodePointInner);
39
40impl fmt::Debug for CodePoint {
43 #[inline]
44 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
45 write!(formatter, "U+{:04X}", self.0.as_inner())
46 }
47}
48
49impl CodePoint {
50 #[inline]
56 pub unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
57 CodePoint(unsafe { CodePointInner::new_unchecked(value) })
59 }
60
61 #[inline]
65 pub fn from_u32(value: u32) -> Option<CodePoint> {
66 Some(CodePoint(CodePointInner::new(value)?))
67 }
68
69 #[inline]
73 pub fn from_char(value: char) -> CodePoint {
74 unsafe { CodePoint::from_u32_unchecked(value as u32) }
76 }
77
78 #[inline]
80 pub fn to_u32(&self) -> u32 {
81 self.0.as_inner()
82 }
83
84 #[inline]
86 pub fn to_lead_surrogate(&self) -> Option<u16> {
87 match self.to_u32() {
88 lead @ 0xD800..=0xDBFF => Some(lead as u16),
89 _ => None,
90 }
91 }
92
93 #[inline]
95 pub fn to_trail_surrogate(&self) -> Option<u16> {
96 match self.to_u32() {
97 trail @ 0xDC00..=0xDFFF => Some(trail as u16),
98 _ => None,
99 }
100 }
101
102 #[inline]
106 pub fn to_char(&self) -> Option<char> {
107 match self.to_u32() {
108 0xD800..=0xDFFF => None,
109 valid => Some(unsafe { char::from_u32_unchecked(valid) }),
111 }
112 }
113
114 #[inline]
119 pub fn to_char_lossy(&self) -> char {
120 self.to_char().unwrap_or(char::REPLACEMENT_CHARACTER)
121 }
122}
123
124#[derive(Eq, Ord, PartialEq, PartialOrd)]
129#[repr(transparent)]
130#[rustc_has_incoherent_inherent_impls]
131#[doc(hidden)]
132pub struct Wtf8 {
133 bytes: [u8],
134}
135
136impl AsRef<[u8]> for Wtf8 {
137 #[inline]
138 fn as_ref(&self) -> &[u8] {
139 &self.bytes
140 }
141}
142
143impl fmt::Debug for Wtf8 {
147 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
148 fn write_str_escaped(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
149 use crate::fmt::Write as _;
150 for c in s.chars().flat_map(|c| {
151 c.escape_debug_ext(EscapeDebugExtArgs {
152 escape_grapheme_extender: true,
153 escape_single_quote: false,
154 escape_double_quote: true,
155 })
156 }) {
157 f.write_char(c)?
158 }
159 Ok(())
160 }
161
162 formatter.write_char('"')?;
163 let mut pos = 0;
164 while let Some((surrogate_pos, surrogate)) = self.next_surrogate(pos) {
165 write_str_escaped(formatter, unsafe {
167 str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos])
168 })?;
169 write!(formatter, "\\u{{{:x}}}", surrogate)?;
170 pos = surrogate_pos + 3;
171 }
172
173 write_str_escaped(formatter, unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?;
175 formatter.write_char('"')
176 }
177}
178
179impl fmt::Display for Wtf8 {
182 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
183 let wtf8_bytes = &self.bytes;
184 let mut pos = 0;
185 loop {
186 match self.next_surrogate(pos) {
187 Some((surrogate_pos, _)) => {
188 formatter.write_str(unsafe {
190 str::from_utf8_unchecked(&wtf8_bytes[pos..surrogate_pos])
191 })?;
192 formatter.write_char(char::REPLACEMENT_CHARACTER)?;
193 pos = surrogate_pos + 3;
194 }
195 None => {
196 let s = unsafe { str::from_utf8_unchecked(&wtf8_bytes[pos..]) };
198 if pos == 0 { return s.fmt(formatter) } else { return formatter.write_str(s) }
199 }
200 }
201 }
202 }
203}
204
205impl Wtf8 {
206 #[inline]
208 pub fn from_str(value: &str) -> &Wtf8 {
209 unsafe { Wtf8::from_bytes_unchecked(value.as_bytes()) }
211 }
212
213 #[inline]
219 pub unsafe fn from_bytes_unchecked(value: &[u8]) -> &Wtf8 {
220 unsafe { &*(value as *const [u8] as *const Wtf8) }
222 }
223
224 #[inline]
230 pub unsafe fn from_mut_bytes_unchecked(value: &mut [u8]) -> &mut Wtf8 {
231 unsafe { &mut *(value as *mut [u8] as *mut Wtf8) }
233 }
234
235 #[inline]
237 pub fn len(&self) -> usize {
238 self.bytes.len()
239 }
240
241 #[inline]
242 pub fn is_empty(&self) -> bool {
243 self.bytes.is_empty()
244 }
245
246 #[inline]
253 pub fn ascii_byte_at(&self, position: usize) -> u8 {
254 match self.bytes[position] {
255 ascii_byte @ 0x00..=0x7F => ascii_byte,
256 _ => 0xFF,
257 }
258 }
259
260 #[inline]
262 pub fn code_points(&self) -> Wtf8CodePoints<'_> {
263 Wtf8CodePoints { bytes: self.bytes.iter() }
264 }
265
266 #[inline]
268 pub fn as_bytes(&self) -> &[u8] {
269 &self.bytes
270 }
271
272 #[inline]
278 pub fn as_str(&self) -> Result<&str, str::Utf8Error> {
279 str::from_utf8(&self.bytes)
280 }
281
282 #[inline]
289 pub fn encode_wide(&self) -> EncodeWide<'_> {
290 EncodeWide { code_points: self.code_points(), extra: 0 }
291 }
292
293 #[inline]
294 pub fn next_surrogate(&self, mut pos: usize) -> Option<(usize, u16)> {
295 let mut iter = self.bytes[pos..].iter();
296 loop {
297 let b = *iter.next()?;
298 if b < 0x80 {
299 pos += 1;
300 } else if b < 0xE0 {
301 iter.next();
302 pos += 2;
303 } else if b == 0xED {
304 match (iter.next(), iter.next()) {
305 (Some(&b2), Some(&b3)) if b2 >= 0xA0 => {
306 return Some((pos, decode_surrogate(b2, b3)));
307 }
308 _ => pos += 3,
309 }
310 } else if b < 0xF0 {
311 iter.next();
312 iter.next();
313 pos += 3;
314 } else {
315 iter.next();
316 iter.next();
317 iter.next();
318 pos += 4;
319 }
320 }
321 }
322
323 #[inline]
324 pub fn final_lead_surrogate(&self) -> Option<u16> {
325 match self.bytes {
326 [.., 0xED, b2 @ 0xA0..=0xAF, b3] => Some(decode_surrogate(b2, b3)),
327 _ => None,
328 }
329 }
330
331 #[inline]
332 pub fn initial_trail_surrogate(&self) -> Option<u16> {
333 match self.bytes {
334 [0xED, b2 @ 0xB0..=0xBF, b3, ..] => Some(decode_surrogate(b2, b3)),
335 _ => None,
336 }
337 }
338
339 #[inline]
340 pub fn make_ascii_lowercase(&mut self) {
341 self.bytes.make_ascii_lowercase()
342 }
343
344 #[inline]
345 pub fn make_ascii_uppercase(&mut self) {
346 self.bytes.make_ascii_uppercase()
347 }
348
349 #[inline]
350 pub fn is_ascii(&self) -> bool {
351 self.bytes.is_ascii()
352 }
353
354 #[inline]
355 pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
356 self.bytes.eq_ignore_ascii_case(&other.bytes)
357 }
358}
359
360impl ops::Index<ops::Range<usize>> for Wtf8 {
367 type Output = Wtf8;
368
369 #[inline]
370 fn index(&self, range: ops::Range<usize>) -> &Wtf8 {
371 if range.start <= range.end
372 && self.is_code_point_boundary(range.start)
373 && self.is_code_point_boundary(range.end)
374 {
375 unsafe { slice_unchecked(self, range.start, range.end) }
377 } else {
378 slice_error_fail(self, range.start, range.end)
379 }
380 }
381}
382
383impl ops::Index<ops::RangeFrom<usize>> for Wtf8 {
390 type Output = Wtf8;
391
392 #[inline]
393 fn index(&self, range: ops::RangeFrom<usize>) -> &Wtf8 {
394 if self.is_code_point_boundary(range.start) {
395 unsafe { slice_unchecked(self, range.start, self.len()) }
397 } else {
398 slice_error_fail(self, range.start, self.len())
399 }
400 }
401}
402
403impl ops::Index<ops::RangeTo<usize>> for Wtf8 {
410 type Output = Wtf8;
411
412 #[inline]
413 fn index(&self, range: ops::RangeTo<usize>) -> &Wtf8 {
414 if self.is_code_point_boundary(range.end) {
415 unsafe { slice_unchecked(self, 0, range.end) }
417 } else {
418 slice_error_fail(self, 0, range.end)
419 }
420 }
421}
422
423impl ops::Index<ops::RangeFull> for Wtf8 {
424 type Output = Wtf8;
425
426 #[inline]
427 fn index(&self, _range: ops::RangeFull) -> &Wtf8 {
428 self
429 }
430}
431
432#[inline]
433fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 {
434 0xD800 | (second_byte as u16 & 0x3F) << 6 | third_byte as u16 & 0x3F
436}
437
438impl Wtf8 {
439 #[inline]
441 pub fn is_code_point_boundary(&self, index: usize) -> bool {
442 if index == 0 {
443 return true;
444 }
445 match self.bytes.get(index) {
446 None => index == self.len(),
447 Some(&b) => (b as i8) >= -0x40,
448 }
449 }
450
451 #[track_caller]
459 #[inline]
460 pub fn check_utf8_boundary(&self, index: usize) {
461 let Err(err) = self.try_check_utf8_boundary(index) else { return };
462 match err {
463 Utf8BoundaryError::NotABoundary => {
464 panic!("byte index {index} is not a codepoint boundary")
465 }
466 Utf8BoundaryError::OutOfBounds => panic!("byte index {index} is out of bounds"),
467 Utf8BoundaryError::BetweenSurrogates => {
468 panic!("byte index {index} lies between surrogate codepoints")
469 }
470 }
471 }
472
473 #[track_caller]
474 #[inline]
475 pub fn try_check_utf8_boundary(&self, index: usize) -> Result<(), Utf8BoundaryError> {
476 if index == 0 {
477 return Ok(());
478 }
479 match self.bytes.get(index) {
480 Some(0xED) => (), Some(&b) if (b as i8) >= -0x40 => return Ok(()),
482 Some(_) => return Err(Utf8BoundaryError::NotABoundary),
483 None if index == self.len() => return Ok(()),
484 None => return Err(Utf8BoundaryError::OutOfBounds),
485 }
486 if self.bytes[index + 1] >= 0xA0 {
487 if index >= 3 && self.bytes[index - 3] == 0xED && self.bytes[index - 2] >= 0xA0 {
489 return Err(Utf8BoundaryError::BetweenSurrogates);
490 }
491 }
492 Ok(())
493 }
494}
495
496#[derive(Debug)]
499pub enum Utf8BoundaryError {
500 NotABoundary,
501 OutOfBounds,
502 BetweenSurrogates,
503}
504
505#[inline]
507unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 {
508 unsafe {
510 let len = end - begin;
511 let start = s.as_bytes().as_ptr().add(begin);
512 Wtf8::from_bytes_unchecked(slice::from_raw_parts(start, len))
513 }
514}
515
516#[inline(never)]
517fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! {
518 let len = s.len();
519 if begin > len {
520 panic!("start byte index {begin} is out of bounds for string of length {len}");
521 }
522 if end > len {
523 panic!("end byte index {end} is out of bounds for string of length {len}");
524 }
525 if begin > end {
526 panic!("byte range starts at {begin} but ends at {end}");
527 }
528 if !s.is_code_point_boundary(begin) {
529 panic!("byte index {begin} is not a code point boundary");
530 }
531 panic!("byte index {end} is not a code point boundary");
532}
533
534#[derive(Clone)]
538#[doc(hidden)]
539pub struct Wtf8CodePoints<'a> {
540 bytes: slice::Iter<'a, u8>,
541}
542
543impl Iterator for Wtf8CodePoints<'_> {
544 type Item = CodePoint;
545
546 #[inline]
547 fn next(&mut self) -> Option<CodePoint> {
548 unsafe { next_code_point(&mut self.bytes).map(|c| CodePoint::from_u32_unchecked(c)) }
550 }
551
552 #[inline]
553 fn size_hint(&self) -> (usize, Option<usize>) {
554 let len = self.bytes.len();
555 (len.saturating_add(3) / 4, Some(len))
556 }
557}
558
559impl fmt::Debug for Wtf8CodePoints<'_> {
560 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561 f.debug_tuple("Wtf8CodePoints")
562 .field(&unsafe { Wtf8::from_bytes_unchecked(self.bytes.as_slice()) })
564 .finish()
565 }
566}
567
568#[stable(feature = "rust1", since = "1.0.0")]
570#[derive(Clone)]
571#[doc(hidden)]
572pub struct EncodeWide<'a> {
573 code_points: Wtf8CodePoints<'a>,
574 extra: u16,
575}
576
577#[stable(feature = "rust1", since = "1.0.0")]
579impl Iterator for EncodeWide<'_> {
580 type Item = u16;
581
582 #[inline]
583 fn next(&mut self) -> Option<u16> {
584 if self.extra != 0 {
585 let tmp = self.extra;
586 self.extra = 0;
587 return Some(tmp);
588 }
589
590 let mut buf = [0; char::MAX_LEN_UTF16];
591 self.code_points.next().map(|code_point| {
592 let n = encode_utf16_raw(code_point.to_u32(), &mut buf).len();
593 if n == 2 {
594 self.extra = buf[1];
595 }
596 buf[0]
597 })
598 }
599
600 #[inline]
601 fn size_hint(&self) -> (usize, Option<usize>) {
602 let (low, high) = self.code_points.size_hint();
603 let ext = (self.extra != 0) as usize;
604 (low + ext, high.and_then(|n| n.checked_mul(2)).and_then(|n| n.checked_add(ext)))
608 }
609}
610
611#[stable(feature = "encode_wide_fused_iterator", since = "1.62.0")]
612impl FusedIterator for EncodeWide<'_> {}
613
614#[stable(feature = "encode_wide_debug", since = "1.92.0")]
615impl fmt::Debug for EncodeWide<'_> {
616 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
617 struct CodeUnit(u16);
618 impl fmt::Debug for CodeUnit {
619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620 match char::from_u32(self.0 as u32) {
628 Some(c) => write!(f, "{c:?}"),
629 None => write!(f, "0x{:04X}", self.0),
630 }
631 }
632 }
633
634 write!(f, "EncodeWide(")?;
635 f.debug_list().entries(self.clone().map(CodeUnit)).finish()?;
636 write!(f, ")")?;
637 Ok(())
638 }
639}
640
641impl Hash for CodePoint {
642 #[inline]
643 fn hash<H: Hasher>(&self, state: &mut H) {
644 self.0.hash(state)
645 }
646}
647
648impl Hash for Wtf8 {
649 #[inline]
650 fn hash<H: Hasher>(&self, state: &mut H) {
651 state.write(&self.bytes);
652 0xfeu8.hash(state)
653 }
654}
655
656#[unstable(feature = "clone_to_uninit", issue = "126799")]
657unsafe impl CloneToUninit for Wtf8 {
658 #[inline]
659 #[cfg_attr(debug_assertions, track_caller)]
660 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
661 unsafe { self.bytes.clone_to_uninit(dst) }
663 }
664}