]> git.lizzy.rs Git - rust.git/blob - src/libcore/char/decode.rs
Rollup merge of #71488 - spastorino:normalize-ty-to-fix-broken-mir, r=eddyb
[rust.git] / src / libcore / char / decode.rs
1 //! UTF-8 and UTF-16 decoding iterators
2
3 use crate::fmt;
4
5 use super::from_u32_unchecked;
6
7 /// An iterator that decodes UTF-16 encoded code points from an iterator of `u16`s.
8 #[stable(feature = "decode_utf16", since = "1.9.0")]
9 #[derive(Clone, Debug)]
10 pub struct DecodeUtf16<I>
11 where
12     I: Iterator<Item = u16>,
13 {
14     iter: I,
15     buf: Option<u16>,
16 }
17
18 /// An error that can be returned when decoding UTF-16 code points.
19 #[stable(feature = "decode_utf16", since = "1.9.0")]
20 #[derive(Debug, Clone, Eq, PartialEq)]
21 pub struct DecodeUtf16Error {
22     code: u16,
23 }
24
25 /// Creates an iterator over the UTF-16 encoded code points in `iter`,
26 /// returning unpaired surrogates as `Err`s.
27 ///
28 /// # Examples
29 ///
30 /// Basic usage:
31 ///
32 /// ```
33 /// use std::char::decode_utf16;
34 ///
35 /// // 𝄞mus<invalid>ic<invalid>
36 /// let v = [
37 ///     0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
38 /// ];
39 ///
40 /// assert_eq!(
41 ///     decode_utf16(v.iter().cloned())
42 ///         .map(|r| r.map_err(|e| e.unpaired_surrogate()))
43 ///         .collect::<Vec<_>>(),
44 ///     vec![
45 ///         Ok('𝄞'),
46 ///         Ok('m'), Ok('u'), Ok('s'),
47 ///         Err(0xDD1E),
48 ///         Ok('i'), Ok('c'),
49 ///         Err(0xD834)
50 ///     ]
51 /// );
52 /// ```
53 ///
54 /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
55 ///
56 /// ```
57 /// use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
58 ///
59 /// // 𝄞mus<invalid>ic<invalid>
60 /// let v = [
61 ///     0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
62 /// ];
63 ///
64 /// assert_eq!(
65 ///     decode_utf16(v.iter().cloned())
66 ///        .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
67 ///        .collect::<String>(),
68 ///     "𝄞mus�ic�"
69 /// );
70 /// ```
71 #[stable(feature = "decode_utf16", since = "1.9.0")]
72 #[inline]
73 pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
74     DecodeUtf16 { iter: iter.into_iter(), buf: None }
75 }
76
77 #[stable(feature = "decode_utf16", since = "1.9.0")]
78 impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {
79     type Item = Result<char, DecodeUtf16Error>;
80
81     fn next(&mut self) -> Option<Result<char, DecodeUtf16Error>> {
82         let u = match self.buf.take() {
83             Some(buf) => buf,
84             None => self.iter.next()?,
85         };
86
87         if u < 0xD800 || 0xDFFF < u {
88             // SAFETY: not a surrogate
89             Some(Ok(unsafe { from_u32_unchecked(u as u32) }))
90         } else if u >= 0xDC00 {
91             // a trailing surrogate
92             Some(Err(DecodeUtf16Error { code: u }))
93         } else {
94             let u2 = match self.iter.next() {
95                 Some(u2) => u2,
96                 // eof
97                 None => return Some(Err(DecodeUtf16Error { code: u })),
98             };
99             if u2 < 0xDC00 || u2 > 0xDFFF {
100                 // not a trailing surrogate so we're not a valid
101                 // surrogate pair, so rewind to redecode u2 next time.
102                 self.buf = Some(u2);
103                 return Some(Err(DecodeUtf16Error { code: u }));
104             }
105
106             // all ok, so lets decode it.
107             let c = (((u - 0xD800) as u32) << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
108             // SAFETY: we checked that it's a legal unicode value
109             Some(Ok(unsafe { from_u32_unchecked(c) }))
110         }
111     }
112
113     #[inline]
114     fn size_hint(&self) -> (usize, Option<usize>) {
115         let (low, high) = self.iter.size_hint();
116         // we could be entirely valid surrogates (2 elements per
117         // char), or entirely non-surrogates (1 element per char)
118         (low / 2, high)
119     }
120 }
121
122 impl DecodeUtf16Error {
123     /// Returns the unpaired surrogate which caused this error.
124     #[stable(feature = "decode_utf16", since = "1.9.0")]
125     pub fn unpaired_surrogate(&self) -> u16 {
126         self.code
127     }
128 }
129
130 #[stable(feature = "decode_utf16", since = "1.9.0")]
131 impl fmt::Display for DecodeUtf16Error {
132     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133         write!(f, "unpaired surrogate found: {:x}", self.code)
134     }
135 }