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
//! Iterators for working with wide strings.

use crate::{error::DecodeUtf32Error, U16CStr, U16Str, U32CStr, U32Str};
use core::{
    char::{self, DecodeUtf16Error},
    fmt::Write,
    iter::{Copied, FusedIterator},
    slice::Iter,
};

#[doc(no_inline)]
pub use core::char::DecodeUtf16;

/// 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`][core::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(core::char::REPLACEMENT_CHARACTER))
    }

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

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| core::char::from_u32(u).ok_or_else(|| DecodeUtf32Error::new(u)))
    }

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

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

/// 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> FusedIterator for DecodeUtf32Lossy<I> where I: Iterator<Item = u32> + FusedIterator {}

/// An iterator over decoded [`char`][prim@char]s of a string slice.
///
/// This struct is created by the [`chars`][crate::UStr<u16>::chars] method on [`U16Str`] and [`U16CStr`].
/// See its documentation for more.
#[derive(Clone)]
pub struct Utf16Chars<'a> {
    inner: DecodeUtf16<Copied<Iter<'a, u16>>>,
}

impl<'a> Utf16Chars<'a> {
    pub(super) fn from_ustr(s: &'a U16Str) -> Self {
        Self {
            inner: char::decode_utf16(s.as_slice().iter().copied()),
        }
    }

    pub(super) fn from_ucstr(s: &'a U16CStr) -> Self {
        Self {
            inner: char::decode_utf16(s.as_slice().iter().copied()),
        }
    }
}

impl<'a> Iterator for Utf16Chars<'a> {
    type Item = Result<char, DecodeUtf16Error>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

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

impl<'a> FusedIterator for Utf16Chars<'a> {}

impl<'a> core::fmt::Debug for Utf16Chars<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        crate::debug_fmt_utf16_iter(self.clone(), f)
    }
}

/// An iterator over decoded [`char`][prim@char]s of a string slice.
///
/// This struct is created by the [`chars`][crate::UStr<u32>::chars] method on [`U32Str`] and [`U32CStr`].
/// See its documentation for more.
#[derive(Clone)]
pub struct Utf32Chars<'a> {
    inner: DecodeUtf32<Copied<Iter<'a, u32>>>,
}

impl<'a> Utf32Chars<'a> {
    pub(super) fn from_ustr(s: &'a U32Str) -> Self {
        Self {
            inner: crate::decode_utf32(s.as_slice().iter().copied()),
        }
    }

    pub(super) fn from_ucstr(s: &'a U32CStr) -> Self {
        Self {
            inner: crate::decode_utf32(s.as_slice().iter().copied()),
        }
    }
}

impl<'a> Iterator for Utf32Chars<'a> {
    type Item = Result<char, DecodeUtf32Error>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

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

impl<'a> FusedIterator for Utf32Chars<'a> {}

impl<'a> core::fmt::Debug for Utf32Chars<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        crate::debug_fmt_utf32_iter(self.clone(), f)
    }
}

/// A lossy iterator over decoded [`char`][prim@char]s of a string slice.
///
/// This struct is created by the [`chars`][crate::UStr<u16>::chars] method on [`UStr`][crate::UStr] and
/// [`UCStr`][crate::UCStr]. See its documentation for more.
#[derive(Clone)]
pub struct CharsLossy<'a> {
    inner: CharsDecoderLossy<'a>,
}

#[derive(Clone)]
enum CharsDecoderLossy<'a> {
    Utf16(DecodeUtf16Lossy<Copied<Iter<'a, u16>>>),
    Utf32(DecodeUtf32Lossy<Copied<Iter<'a, u32>>>),
}

impl<'a> CharsLossy<'a> {
    pub(super) fn from_u16str(s: &'a U16Str) -> Self {
        Self {
            inner: CharsDecoderLossy::Utf16(crate::decode_utf16_lossy(
                s.as_slice().iter().copied(),
            )),
        }
    }

    pub(super) fn from_u16cstr(s: &'a U16CStr) -> Self {
        Self {
            inner: CharsDecoderLossy::Utf16(crate::decode_utf16_lossy(
                s.as_slice().iter().copied(),
            )),
        }
    }

    pub(super) fn from_u32str(s: &'a U32Str) -> Self {
        Self {
            inner: CharsDecoderLossy::Utf32(crate::decode_utf32_lossy(
                s.as_slice().iter().copied(),
            )),
        }
    }

    pub(super) fn from_u32cstr(s: &'a U32CStr) -> Self {
        Self {
            inner: CharsDecoderLossy::Utf32(crate::decode_utf32_lossy(
                s.as_slice().iter().copied(),
            )),
        }
    }
}

impl<'a> Iterator for CharsLossy<'a> {
    type Item = char;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.inner {
            CharsDecoderLossy::Utf16(iter) => iter.next(),
            CharsDecoderLossy::Utf32(iter) => iter.next(),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match &self.inner {
            CharsDecoderLossy::Utf16(iter) => iter.size_hint(),
            CharsDecoderLossy::Utf32(iter) => iter.size_hint(),
        }
    }
}

impl<'a> FusedIterator for CharsLossy<'a> {}

impl<'a> core::fmt::Debug for CharsLossy<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_char('"')?;
        for c in self.clone() {
            f.write_char(c)?;
        }
        f.write_char('"')
    }
}

/// An iterator over the [`char`][prim@char]s of a string slice, and their positions.
///
/// This struct is created by the [`char_indices`][crate::UStr<u16>::char_indices] method on [`U16Str`] and
/// [`U16CStr`]. See its documentation for more.
#[derive(Debug, Clone)]
pub struct Utf16CharIndices<'a> {
    index: usize,
    iter: DecodeUtf16<Copied<Iter<'a, u16>>>,
}

impl<'a> Utf16CharIndices<'a> {
    pub(super) fn from_ustr(s: &'a U16Str) -> Self {
        Self {
            index: 0,
            iter: char::decode_utf16(s.as_slice().iter().copied()),
        }
    }

    pub(super) fn from_ucstr(s: &'a U16CStr) -> Self {
        Self {
            index: 0,
            iter: char::decode_utf16(s.as_slice().iter().copied()),
        }
    }
}

impl<'a> Iterator for Utf16CharIndices<'a> {
    type Item = (Result<char, DecodeUtf16Error>, usize);

    fn next(&mut self) -> Option<Self::Item> {
        match self.iter.next() {
            Some(Ok(c)) => {
                let idx = self.index;
                self.index += c.len_utf16();
                Some((Ok(c), idx))
            }
            Some(Err(e)) => {
                let idx = self.index;
                self.index += 1;
                Some((Err(e), idx))
            }
            None => None,
        }
    }

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

impl<'a> FusedIterator for Utf16CharIndices<'a> {}

/// A lossy iterator over the [`char`][prim@char]s of a string slice, and their positions.
///
/// This struct is created by the [`char_indices_lossy`][crate::UStr<u16>::char_indices_lossy] method on
/// [`U16Str`] and [`U16CStr`]. See its documentation for more.
#[derive(Debug, Clone)]
pub struct Utf16CharIndicesLossy<'a> {
    index: usize,
    iter: DecodeUtf16<Copied<Iter<'a, u16>>>,
}

impl<'a> Utf16CharIndicesLossy<'a> {
    pub(super) fn from_ustr(s: &'a U16Str) -> Self {
        Self {
            index: 0,
            iter: char::decode_utf16(s.as_slice().iter().copied()),
        }
    }

    pub(super) fn from_ucstr(s: &'a U16CStr) -> Self {
        Self {
            index: 0,
            iter: char::decode_utf16(s.as_slice().iter().copied()),
        }
    }
}

impl<'a> Iterator for Utf16CharIndicesLossy<'a> {
    type Item = (char, usize);

    fn next(&mut self) -> Option<Self::Item> {
        match self.iter.next() {
            Some(Ok(c)) => {
                let idx = self.index;
                self.index += c.len_utf16();
                Some((c, idx))
            }
            Some(Err(_)) => {
                let idx = self.index;
                self.index += 1;
                Some((char::REPLACEMENT_CHARACTER, idx))
            }
            None => None,
        }
    }

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

impl<'a> FusedIterator for Utf16CharIndicesLossy<'a> {}