]> git.lizzy.rs Git - rust.git/blob - library/core/src/char/decode.rs
Rollup merge of #103360 - ChrisDenton:isterm-filetype, r=thomcc
[rust.git] / library / core / src / char / decode.rs
1 //! UTF-8 and UTF-16 decoding iterators
2
3 use crate::error::Error;
4 use crate::fmt;
5
6 use super::from_u32_unchecked;
7
8 /// An iterator that decodes UTF-16 encoded code points from an iterator of `u16`s.
9 ///
10 /// This `struct` is created by the [`decode_utf16`] method on [`char`]. See its
11 /// documentation for more.
12 ///
13 /// [`decode_utf16`]: char::decode_utf16
14 #[stable(feature = "decode_utf16", since = "1.9.0")]
15 #[derive(Clone, Debug)]
16 pub struct DecodeUtf16<I>
17 where
18     I: Iterator<Item = u16>,
19 {
20     iter: I,
21     buf: Option<u16>,
22 }
23
24 /// An error that can be returned when decoding UTF-16 code points.
25 ///
26 /// This `struct` is created when using the [`DecodeUtf16`] type.
27 #[stable(feature = "decode_utf16", since = "1.9.0")]
28 #[derive(Debug, Clone, Eq, PartialEq)]
29 pub struct DecodeUtf16Error {
30     code: u16,
31 }
32
33 /// Creates an iterator over the UTF-16 encoded code points in `iter`,
34 /// returning unpaired surrogates as `Err`s. See [`char::decode_utf16`].
35 #[inline]
36 pub(super) fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
37     DecodeUtf16 { iter: iter.into_iter(), buf: None }
38 }
39
40 #[stable(feature = "decode_utf16", since = "1.9.0")]
41 impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {
42     type Item = Result<char, DecodeUtf16Error>;
43
44     fn next(&mut self) -> Option<Result<char, DecodeUtf16Error>> {
45         let u = match self.buf.take() {
46             Some(buf) => buf,
47             None => self.iter.next()?,
48         };
49
50         if !u.is_utf16_surrogate() {
51             // SAFETY: not a surrogate
52             Some(Ok(unsafe { from_u32_unchecked(u as u32) }))
53         } else if u >= 0xDC00 {
54             // a trailing surrogate
55             Some(Err(DecodeUtf16Error { code: u }))
56         } else {
57             let u2 = match self.iter.next() {
58                 Some(u2) => u2,
59                 // eof
60                 None => return Some(Err(DecodeUtf16Error { code: u })),
61             };
62             if u2 < 0xDC00 || u2 > 0xDFFF {
63                 // not a trailing surrogate so we're not a valid
64                 // surrogate pair, so rewind to redecode u2 next time.
65                 self.buf = Some(u2);
66                 return Some(Err(DecodeUtf16Error { code: u }));
67             }
68
69             // all ok, so lets decode it.
70             let c = (((u - 0xD800) as u32) << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
71             // SAFETY: we checked that it's a legal unicode value
72             Some(Ok(unsafe { from_u32_unchecked(c) }))
73         }
74     }
75
76     #[inline]
77     fn size_hint(&self) -> (usize, Option<usize>) {
78         let (low, high) = self.iter.size_hint();
79
80         let (low_buf, high_buf) = match self.buf {
81             // buf is empty, no additional elements from it.
82             None => (0, 0),
83             // `u` is a non surrogate, so it's always an additional character.
84             Some(u) if !u.is_utf16_surrogate() => (1, 1),
85             // `u` is a leading surrogate (it can never be a trailing surrogate and
86             // it's a surrogate due to the previous branch) and `self.iter` is empty.
87             //
88             // `u` can't be paired, since the `self.iter` is empty,
89             // so it will always become an additional element (error).
90             Some(_u) if high == Some(0) => (1, 1),
91             // `u` is a leading surrogate and `iter` may be non-empty.
92             //
93             // `u` can either pair with a trailing surrogate, in which case no additional elements
94             // are produced, or it can become an error, in which case it's an additional character (error).
95             Some(_u) => (0, 1),
96         };
97
98         // `self.iter` could contain entirely valid surrogates (2 elements per
99         // char), or entirely non-surrogates (1 element per char).
100         //
101         // On odd lower bound, at least one element must stay unpaired
102         // (with other elements from `self.iter`), so we round up.
103         let low = low.div_ceil(2) + low_buf;
104         let high = high.and_then(|h| h.checked_add(high_buf));
105
106         (low, high)
107     }
108 }
109
110 impl DecodeUtf16Error {
111     /// Returns the unpaired surrogate which caused this error.
112     #[must_use]
113     #[stable(feature = "decode_utf16", since = "1.9.0")]
114     pub fn unpaired_surrogate(&self) -> u16 {
115         self.code
116     }
117 }
118
119 #[stable(feature = "decode_utf16", since = "1.9.0")]
120 impl fmt::Display for DecodeUtf16Error {
121     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122         write!(f, "unpaired surrogate found: {:x}", self.code)
123     }
124 }
125
126 #[stable(feature = "decode_utf16", since = "1.9.0")]
127 impl Error for DecodeUtf16Error {
128     #[allow(deprecated)]
129     fn description(&self) -> &str {
130         "unpaired surrogate found"
131     }
132 }