1use crate::error::Error;
4use crate::fmt;
5use crate::iter::FusedIterator;
6
7#[stable(feature = "decode_utf16", since = "1.9.0")]
14#[derive(Clone, Debug)]
15#[ferrocene::prevalidated]
16pub struct DecodeUtf16<I>
17where
18 I: Iterator<Item = u16>,
19{
20 iter: I,
21 buf: Option<u16>,
22}
23
24#[stable(feature = "decode_utf16", since = "1.9.0")]
28#[derive(Debug, Clone, Eq, PartialEq)]
29#[ferrocene::prevalidated]
30pub struct DecodeUtf16Error {
31 code: u16,
32}
33
34#[inline]
37#[ferrocene::prevalidated]
38pub(super) fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
39 DecodeUtf16 { iter: iter.into_iter(), buf: None }
40}
41
42#[stable(feature = "decode_utf16", since = "1.9.0")]
43impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {
44 type Item = Result<char, DecodeUtf16Error>;
45
46 #[ferrocene::prevalidated]
47 fn next(&mut self) -> Option<Result<char, DecodeUtf16Error>> {
48 let u = match self.buf.take() {
49 Some(buf) => buf,
50 None => self.iter.next()?,
51 };
52
53 if !u.is_utf16_surrogate() {
54 Some(Ok(unsafe { char::from_u32_unchecked(u as u32) }))
56 } else if u >= 0xDC00 {
57 Some(Err(DecodeUtf16Error { code: u }))
59 } else {
60 let u2 = match self.iter.next() {
61 Some(u2) => u2,
62 None => return Some(Err(DecodeUtf16Error { code: u })),
64 };
65 if u2 < 0xDC00 || u2 > 0xDFFF {
66 self.buf = Some(u2);
69 return Some(Err(DecodeUtf16Error { code: u }));
70 }
71
72 let c = (((u & 0x3ff) as u32) << 10 | (u2 & 0x3ff) as u32) + 0x1_0000;
74 Some(Ok(unsafe { char::from_u32_unchecked(c) }))
76 }
77 }
78
79 #[inline]
80 #[ferrocene::prevalidated]
81 fn size_hint(&self) -> (usize, Option<usize>) {
82 let (low, high) = self.iter.size_hint();
83
84 let (low_buf, high_buf) = match self.buf {
85 None => (0, 0),
87 Some(u) if !u.is_utf16_surrogate() => (1, 1),
89 Some(_u) if high == Some(0) => (1, 1),
95 Some(_u) => (0, 1),
100 };
101
102 let low = low.div_ceil(2) + low_buf;
108 let high = high.and_then(|h| h.checked_add(high_buf));
109
110 (low, high)
111 }
112}
113
114#[stable(feature = "decode_utf16_fused_iterator", since = "1.75.0")]
115impl<I: Iterator<Item = u16> + FusedIterator> FusedIterator for DecodeUtf16<I> {}
116
117impl DecodeUtf16Error {
118 #[must_use]
120 #[stable(feature = "decode_utf16", since = "1.9.0")]
121 #[ferrocene::prevalidated]
122 pub fn unpaired_surrogate(&self) -> u16 {
123 self.code
124 }
125}
126
127#[stable(feature = "decode_utf16", since = "1.9.0")]
128impl fmt::Display for DecodeUtf16Error {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 write!(f, "unpaired surrogate found: {:x}", self.code)
131 }
132}
133
134#[stable(feature = "decode_utf16", since = "1.9.0")]
135impl Error for DecodeUtf16Error {}