1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Iterators for encoding and decoding slices of string data.

use crate::{
    decode_utf16_surrogate_pair,
    error::{DecodeUtf16Error, DecodeUtf32Error},
    is_utf16_high_surrogate, is_utf16_low_surrogate, is_utf16_surrogate,
};
#[allow(unused_imports)]
use core::{
    char,
    iter::{DoubleEndedIterator, ExactSizeIterator, FusedIterator},
};

/// An iterator that decodes UTF-16 encoded code points from an iterator of [`u16`]s.
///
/// This struct is created by [`decode_utf16`][crate::decode_utf16]. See its documentation for more.
///
/// This struct is identical to [`char::DecodeUtf16`] except it is a [`DoubleEndedIterator`] if
/// `I` is.
#[derive(Debug, Clone)]
pub struct DecodeUtf16<I>
where
    I: Iterator<Item = u16>,
{
    iter: I,
    forward_buf: Option<u16>,
    back_buf: Option<u16>,
}

impl<I> DecodeUtf16<I>
where
    I: Iterator<Item = u16>,
{
    pub(crate) fn new(iter: I) -> Self {
        Self {
            iter,
            forward_buf: None,
            back_buf: None,
        }
    }
}

impl<I> Iterator for DecodeUtf16<I>
where
    I: Iterator<Item = u16>,
{
    type Item = Result<char, DecodeUtf16Error>;

    fn next(&mut self) -> Option<Self::Item> {
        // Copied from char::DecodeUtf16
        let u = match self.forward_buf.take() {
            Some(buf) => buf,
            None => self.iter.next().or_else(|| self.back_buf.take())?,
        };

        if !is_utf16_surrogate(u) {
            // SAFETY: not a surrogate
            Some(Ok(unsafe { char::from_u32_unchecked(u as u32) }))
        } else if is_utf16_low_surrogate(u) {
            // a trailing surrogate
            Some(Err(DecodeUtf16Error::new(u)))
        } else {
            let u2 = match self.iter.next().or_else(|| self.back_buf.take()) {
                Some(u2) => u2,
                // eof
                None => return Some(Err(DecodeUtf16Error::new(u))),
            };
            if !is_utf16_low_surrogate(u2) {
                // not a trailing surrogate so we're not a valid
                // surrogate pair, so rewind to redecode u2 next time.
                self.forward_buf = Some(u2);
                return Some(Err(DecodeUtf16Error::new(u)));
            }

            // all ok, so lets decode it.
            // SAFETY: verified the surrogate pair
            unsafe { Some(Ok(decode_utf16_surrogate_pair(u, u2))) }
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (low, high) = self.iter.size_hint();
        // we could be entirely valid surrogates (2 elements per
        // char), or entirely non-surrogates (1 element per char)
        (low / 2, high)
    }
}

impl<I> DoubleEndedIterator for DecodeUtf16<I>
where
    I: Iterator<Item = u16> + DoubleEndedIterator,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        let u2 = match self.back_buf.take() {
            Some(buf) => buf,
            None => self.iter.next_back().or_else(|| self.forward_buf.take())?,
        };

        if !is_utf16_surrogate(u2) {
            // SAFETY: not a surrogate
            Some(Ok(unsafe { char::from_u32_unchecked(u2 as u32) }))
        } else if is_utf16_high_surrogate(u2) {
            // a leading surrogate
            Some(Err(DecodeUtf16Error::new(u2)))
        } else {
            let u = match self.iter.next_back().or_else(|| self.forward_buf.take()) {
                Some(u) => u,
                // eof
                None => return Some(Err(DecodeUtf16Error::new(u2))),
            };
            if !is_utf16_high_surrogate(u) {
                // not a leading surrogate so we're not a valid
                // surrogate pair, so rewind to redecode u next time.
                self.back_buf = Some(u);
                return Some(Err(DecodeUtf16Error::new(u2)));
            }

            // all ok, so lets decode it.
            // SAFETY: verified the surrogate pair
            unsafe { Some(Ok(decode_utf16_surrogate_pair(u, u2))) }
        }
    }
}

impl<I> FusedIterator for DecodeUtf16<I> where I: Iterator<Item = u16> + FusedIterator {}

/// An iterator that lossily decodes possibly ill-formed UTF-16 encoded code points from an iterator
/// of [`u16`]s.
///
/// Any unpaired UTF-16 surrogate values are replaced by
/// [`U+FFFD REPLACEMENT_CHARACTER`][char::REPLACEMENT_CHARACTER] (�).
#[derive(Debug, Clone)]
pub struct DecodeUtf16Lossy<I>
where
    I: Iterator<Item = u16>,
{
    pub(crate) iter: DecodeUtf16<I>,
}

impl<I> Iterator for DecodeUtf16Lossy<I>
where
    I: Iterator<Item = u16>,
{
    type Item = char;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|res| res.unwrap_or(char::REPLACEMENT_CHARACTER))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<I> DoubleEndedIterator for DecodeUtf16Lossy<I>
where
    I: Iterator<Item = u16> + DoubleEndedIterator,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter
            .next_back()
            .map(|res| res.unwrap_or(char::REPLACEMENT_CHARACTER))
    }
}

impl<I> FusedIterator for DecodeUtf16Lossy<I> where I: Iterator<Item = u16> + FusedIterator {}

/// An iterator that decodes UTF-32 encoded code points from an iterator of `u32`s.
#[derive(Debug, Clone)]
pub struct DecodeUtf32<I>
where
    I: Iterator<Item = u32>,
{
    pub(crate) iter: I,
}

impl<I> Iterator for DecodeUtf32<I>
where
    I: Iterator<Item = u32>,
{
    type Item = Result<char, DecodeUtf32Error>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|u| char::from_u32(u).ok_or_else(|| DecodeUtf32Error::new(u)))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<I> DoubleEndedIterator for DecodeUtf32<I>
where
    I: Iterator<Item = u32> + DoubleEndedIterator,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter
            .next_back()
            .map(|u| char::from_u32(u).ok_or_else(|| DecodeUtf32Error::new(u)))
    }
}

impl<I> FusedIterator for DecodeUtf32<I> where I: Iterator<Item = u32> + FusedIterator {}

impl<I> ExactSizeIterator for DecodeUtf32<I>
where
    I: Iterator<Item = u32> + ExactSizeIterator,
{
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

/// An iterator that lossily decodes possibly ill-formed UTF-32 encoded code points from an iterator
/// of `u32`s.
///
/// Any invalid UTF-32 values are replaced by
/// [`U+FFFD REPLACEMENT_CHARACTER`][core::char::REPLACEMENT_CHARACTER] (�).
#[derive(Debug, Clone)]
pub struct DecodeUtf32Lossy<I>
where
    I: Iterator<Item = u32>,
{
    pub(crate) iter: DecodeUtf32<I>,
}

impl<I> Iterator for DecodeUtf32Lossy<I>
where
    I: Iterator<Item = u32>,
{
    type Item = char;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|res| res.unwrap_or(core::char::REPLACEMENT_CHARACTER))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<I> DoubleEndedIterator for DecodeUtf32Lossy<I>
where
    I: Iterator<Item = u32> + DoubleEndedIterator,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter
            .next_back()
            .map(|res| res.unwrap_or(core::char::REPLACEMENT_CHARACTER))
    }
}

impl<I> FusedIterator for DecodeUtf32Lossy<I> where I: Iterator<Item = u32> + FusedIterator {}

impl<I> ExactSizeIterator for DecodeUtf32Lossy<I>
where
    I: Iterator<Item = u32> + ExactSizeIterator,
{
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

/// An iterator that encodes an iterator of [`char`][prim@char]s into UTF-8 bytes.
///
/// This struct is created by [`encode_utf8`][crate::encode_utf8]. See its documentation for more.
#[derive(Debug, Clone)]
pub struct EncodeUtf8<I>
where
    I: Iterator<Item = char>,
{
    iter: I,
    buf: [u8; 4],
    idx: u8,
    len: u8,
}

impl<I> EncodeUtf8<I>
where
    I: Iterator<Item = char>,
{
    pub(crate) fn new(iter: I) -> Self {
        Self {
            iter,
            buf: [0; 4],
            idx: 0,
            len: 0,
        }
    }
}

impl<I> Iterator for EncodeUtf8<I>
where
    I: Iterator<Item = char>,
{
    type Item = u8;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.idx >= self.len {
            let c = self.iter.next()?;
            self.idx = 0;
            self.len = c.encode_utf8(&mut self.buf).len() as u8;
        }
        self.idx += 1;
        let idx = (self.idx - 1) as usize;
        Some(self.buf[idx])
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (lower, upper) = self.iter.size_hint();
        (lower, upper.and_then(|len| len.checked_mul(4))) // Max 4 UTF-8 bytes per char
    }
}

impl<I> FusedIterator for EncodeUtf8<I> where I: Iterator<Item = char> + FusedIterator {}

/// An iterator that encodes an iterator of [`char`][prim@char]s into UTF-16 [`u16`] code units.
///
/// This struct is created by [`encode_utf16`][crate::encode_utf16]. See its documentation for more.
#[derive(Debug, Clone)]
pub struct EncodeUtf16<I>
where
    I: Iterator<Item = char>,
{
    iter: I,
    buf: Option<u16>,
}

impl<I> EncodeUtf16<I>
where
    I: Iterator<Item = char>,
{
    pub(crate) fn new(iter: I) -> Self {
        Self { iter, buf: None }
    }
}

impl<I> Iterator for EncodeUtf16<I>
where
    I: Iterator<Item = char>,
{
    type Item = u16;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.buf.take().or_else(|| {
            let c = self.iter.next()?;
            let mut buf = [0; 2];
            let buf = c.encode_utf16(&mut buf);
            if buf.len() > 1 {
                self.buf = Some(buf[1]);
            }
            Some(buf[0])
        })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (lower, upper) = self.iter.size_hint();
        (lower, upper.and_then(|len| len.checked_mul(2))) // Max 2 UTF-16 code units per char
    }
}

impl<I> FusedIterator for EncodeUtf16<I> where I: Iterator<Item = char> + FusedIterator {}

/// An iterator that encodes an iterator of [`char`][prim@char]s into UTF-32 [`u32`] values.
///
/// This struct is created by [`encode_utf32`][crate::encode_utf32]. See its documentation for more.
#[derive(Debug, Clone)]
pub struct EncodeUtf32<I>
where
    I: Iterator<Item = char>,
{
    iter: I,
}

impl<I> EncodeUtf32<I>
where
    I: Iterator<Item = char>,
{
    pub(crate) fn new(iter: I) -> Self {
        Self { iter }
    }
}

impl<I> Iterator for EncodeUtf32<I>
where
    I: Iterator<Item = char>,
{
    type Item = u32;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|c| c as u32)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<I> FusedIterator for EncodeUtf32<I> where I: Iterator<Item = char> + FusedIterator {}

impl<I> ExactSizeIterator for EncodeUtf32<I>
where
    I: Iterator<Item = char> + ExactSizeIterator,
{
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<I> DoubleEndedIterator for EncodeUtf32<I>
where
    I: Iterator<Item = char> + DoubleEndedIterator,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.next_back().map(|c| c as u32)
    }
}