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
use crate::{
    debug_fmt_char_iter, decode_utf16, decode_utf32,
    iter::{DecodeUtf16, DecodeUtf32},
};
#[allow(unused_imports)]
use core::{
    fmt::Write,
    iter::{Copied, DoubleEndedIterator, ExactSizeIterator, FlatMap, FusedIterator},
    slice::Iter,
};

/// An iterator over the [`char`]s of a UTF-16 string slice
///
/// This struct is created by the [`chars`][crate::Utf16Str::chars] method on
/// [`Utf16Str`][crate::Utf16Str]. See its documentation for more.
#[derive(Clone)]
pub struct CharsUtf16<'a> {
    iter: DecodeUtf16<Copied<Iter<'a, u16>>>,
}

impl<'a> CharsUtf16<'a> {
    pub(super) fn new(s: &'a [u16]) -> Self {
        Self {
            iter: decode_utf16(s.iter().copied()),
        }
    }
}

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

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        // Utf16Str already ensures valid surrogate pairs
        self.iter.next().map(|r| r.unwrap())
    }

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

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

impl<'a> DoubleEndedIterator for CharsUtf16<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.next_back().map(|r| r.unwrap())
    }
}

impl<'a> core::fmt::Debug for CharsUtf16<'a> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        debug_fmt_char_iter(self.clone(), f)
    }
}

impl<'a> core::fmt::Display for CharsUtf16<'a> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.clone().try_for_each(|c| f.write_char(c))
    }
}

/// An iterator over the [`char`]s of a UTF-32 string slice
///
/// This struct is created by the [`chars`][crate::Utf32Str::chars] method on
/// [`Utf32Str`][crate::Utf32Str]. See its documentation for more.
#[derive(Clone)]
pub struct CharsUtf32<'a> {
    iter: DecodeUtf32<Copied<Iter<'a, u32>>>,
}

impl<'a> CharsUtf32<'a> {
    pub(super) fn new(s: &'a [u32]) -> Self {
        Self {
            iter: decode_utf32(s.iter().copied()),
        }
    }
}

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

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        // Utf32Str already ensures valid code points
        self.iter.next().map(|r| r.unwrap())
    }

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

impl<'a> DoubleEndedIterator for CharsUtf32<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        // Utf32Str already ensures valid code points
        self.iter.next_back().map(|r| r.unwrap())
    }
}

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

impl<'a> ExactSizeIterator for CharsUtf32<'a> {
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<'a> core::fmt::Debug for CharsUtf32<'a> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        debug_fmt_char_iter(self.clone(), f)
    }
}

impl<'a> core::fmt::Display for CharsUtf32<'a> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.clone().try_for_each(|c| f.write_char(c))
    }
}

/// An iterator over the [`char`]s of a string slice, and their positions
///
/// This struct is created by the [`char_indices`][crate::Utf16Str::char_indices] method on
/// [`Utf16Str`][crate::Utf16Str]. See its documentation for more.
#[derive(Debug, Clone)]
pub struct CharIndicesUtf16<'a> {
    forward_offset: usize,
    back_offset: usize,
    iter: CharsUtf16<'a>,
}

impl<'a> CharIndicesUtf16<'a> {
    /// Returns the position of the next character, or the length of the underlying string if
    /// there are no more characters.
    #[inline]
    pub fn offset(&self) -> usize {
        self.forward_offset
    }
}

impl<'a> CharIndicesUtf16<'a> {
    pub(super) fn new(s: &'a [u16]) -> Self {
        Self {
            forward_offset: 0,
            back_offset: s.len(),
            iter: CharsUtf16::new(s),
        }
    }
}

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

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let result = self.iter.next();
        if let Some(c) = result {
            let offset = self.forward_offset;
            self.forward_offset += c.len_utf16();
            Some((offset, c))
        } else {
            None
        }
    }

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

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

impl<'a> DoubleEndedIterator for CharIndicesUtf16<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        let result = self.iter.next_back();
        if let Some(c) = result {
            self.back_offset -= c.len_utf16();
            Some((self.back_offset, c))
        } else {
            None
        }
    }
}

/// An iterator over the [`char`]s of a string slice, and their positions
///
/// This struct is created by the [`char_indices`][crate::Utf32Str::char_indices] method on
/// [`Utf32Str`][crate::Utf32Str]. See its documentation for more.
#[derive(Debug, Clone)]
pub struct CharIndicesUtf32<'a> {
    forward_offset: usize,
    back_offset: usize,
    iter: CharsUtf32<'a>,
}

impl<'a> CharIndicesUtf32<'a> {
    /// Returns the position of the next character, or the length of the underlying string if
    /// there are no more characters.
    #[inline]
    pub fn offset(&self) -> usize {
        self.forward_offset
    }
}

impl<'a> CharIndicesUtf32<'a> {
    pub(super) fn new(s: &'a [u32]) -> Self {
        Self {
            forward_offset: 0,
            back_offset: s.len(),
            iter: CharsUtf32::new(s),
        }
    }
}

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

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let result = self.iter.next();
        if let Some(c) = result {
            let offset = self.forward_offset;
            self.forward_offset += 1;
            Some((offset, c))
        } else {
            None
        }
    }

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

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

impl<'a> DoubleEndedIterator for CharIndicesUtf32<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        let result = self.iter.next_back();
        if let Some(c) = result {
            self.back_offset -= 1;
            Some((self.back_offset, c))
        } else {
            None
        }
    }
}

impl<'a> ExactSizeIterator for CharIndicesUtf32<'a> {
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

/// The return type of [`Utf16Str::escape_debug`][crate::Utf16Str::escape_debug].
#[derive(Debug, Clone)]
pub struct EscapeDebug<I> {
    iter: FlatMap<I, core::char::EscapeDebug, fn(char) -> core::char::EscapeDebug>,
}

impl<'a> EscapeDebug<CharsUtf16<'a>> {
    pub(super) fn new(s: &'a [u16]) -> Self {
        Self {
            iter: CharsUtf16::new(s).flat_map(|c| c.escape_debug()),
        }
    }
}

impl<'a> EscapeDebug<CharsUtf32<'a>> {
    pub(super) fn new(s: &'a [u32]) -> Self {
        Self {
            iter: CharsUtf32::new(s).flat_map(|c| c.escape_debug()),
        }
    }
}

/// The return type of [`Utf16Str::escape_default`][crate::Utf16Str::escape_default].
#[derive(Debug, Clone)]
pub struct EscapeDefault<I> {
    iter: FlatMap<I, core::char::EscapeDefault, fn(char) -> core::char::EscapeDefault>,
}

impl<'a> EscapeDefault<CharsUtf16<'a>> {
    pub(super) fn new(s: &'a [u16]) -> Self {
        Self {
            iter: CharsUtf16::new(s).flat_map(|c| c.escape_default()),
        }
    }
}

impl<'a> EscapeDefault<CharsUtf32<'a>> {
    pub(super) fn new(s: &'a [u32]) -> Self {
        Self {
            iter: CharsUtf32::new(s).flat_map(|c| c.escape_default()),
        }
    }
}

/// The return type of [`Utf16Str::escape_unicode`][crate::Utf16Str::escape_unicode].
#[derive(Debug, Clone)]
pub struct EscapeUnicode<I> {
    iter: FlatMap<I, core::char::EscapeUnicode, fn(char) -> core::char::EscapeUnicode>,
}

impl<'a> EscapeUnicode<CharsUtf16<'a>> {
    pub(super) fn new(s: &'a [u16]) -> Self {
        Self {
            iter: CharsUtf16::new(s).flat_map(|c| c.escape_unicode()),
        }
    }
}

impl<'a> EscapeUnicode<CharsUtf32<'a>> {
    pub(super) fn new(s: &'a [u32]) -> Self {
        Self {
            iter: CharsUtf32::new(s).flat_map(|c| c.escape_unicode()),
        }
    }
}

macro_rules! escape_impls {
    ($($name:ident),+) => {$(
        impl<I> core::fmt::Display for $name<I> where I: Iterator<Item = char> + Clone {
            #[inline]
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                self.clone().try_for_each(|c| f.write_char(c))
            }
        }

        impl< I> Iterator for $name<I> where I: Iterator<Item = char> {
            type Item = char;

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

            #[inline]
            fn size_hint(&self) -> (usize, Option<usize>) {
                let (lower, upper) = self.iter.size_hint();
                // Worst case, every char has to be unicode escaped as \u{NNNNNN}
                (lower, upper.and_then(|len| len.checked_mul(10)))
            }
        }

        impl<I> FusedIterator for $name<I> where I: Iterator<Item = char> + FusedIterator {}
    )+}
}

escape_impls!(EscapeDebug, EscapeDefault, EscapeUnicode);

/// An iterator over the [`u16`] code units of a UTF-16 string slice
///
/// This struct is created by the [`code_units`][crate::Utf16Str::code_units] method on
/// [`Utf16Str`][crate::Utf16Str]. See its documentation for more.
#[derive(Debug, Clone)]
pub struct CodeUnits<'a> {
    iter: Copied<Iter<'a, u16>>,
}

impl<'a> CodeUnits<'a> {
    pub(super) fn new(s: &'a [u16]) -> Self {
        Self {
            iter: s.iter().copied(),
        }
    }
}

impl<'a> Iterator for CodeUnits<'a> {
    type Item = u16;

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

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

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

impl<'a> DoubleEndedIterator for CodeUnits<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.next_back()
    }
}

impl<'a> ExactSizeIterator for CodeUnits<'a> {
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}