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
use core::iter::FusedIterator;

use crate::{Encoding, String};

#[derive(Default, Debug, Clone)]
pub struct Chars<'a>(State<'a>);

impl<'a> From<&'a String> for Chars<'a> {
    #[inline]
    fn from(s: &'a String) -> Self {
        let state = match s.encoding() {
            Encoding::Utf8 => {
                let iter = ConventionallyUtf8::with_bytes(s.as_slice());
                State::Utf8(iter)
            }
            Encoding::Ascii => {
                let iter = Bytes::with_bytes(s.as_slice());
                State::Ascii(iter)
            }
            Encoding::Binary => {
                let iter = Bytes::with_bytes(s.as_slice());
                State::Binary(iter)
            }
        };
        Self(state)
    }
}

impl<'a> Iterator for Chars<'a> {
    type Item = &'a [u8];

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

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

impl<'a> Chars<'a> {
    pub(crate) fn new() -> Self {
        const EMPTY: &[u8] = &[];
        Self(State::Binary(Bytes::from(EMPTY)))
    }
}

#[derive(Debug, Clone)]
enum State<'a> {
    Utf8(ConventionallyUtf8<'a>),
    Ascii(Bytes<'a>),
    Binary(Bytes<'a>),
}

impl<'a> Default for State<'a> {
    fn default() -> Self {
        Self::Utf8(ConventionallyUtf8::new())
    }
}

impl<'a> Iterator for State<'a> {
    type Item = &'a [u8];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Ascii(iter) | Self::Binary(iter) => iter.next(),
            Self::Utf8(iter) => iter.next(),
        }
    }
}

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

#[derive(Default, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct Bytes<'a> {
    bytes: &'a [u8],
}

impl<'a> Bytes<'a> {
    #[inline]
    const fn with_bytes(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }
}

impl<'a> From<&'a [u8]> for Bytes<'a> {
    #[inline]
    fn from(bytes: &'a [u8]) -> Self {
        Self::with_bytes(bytes)
    }
}

impl<'a> Iterator for Bytes<'a> {
    type Item = &'a [u8];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.bytes.is_empty() {
            None
        } else {
            // Splitting the byte slice is guaranteed to not panic because the
            // slice is non-empty.
            let (next, remainder) = self.bytes.split_at(1);
            self.bytes = remainder;
            Some(next)
        }
    }
}

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

#[derive(Default, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct InvalidBytes<'a> {
    bytes: &'a [u8],
}

impl<'a> InvalidBytes<'a> {
    #[inline]
    const fn new() -> Self {
        Self { bytes: &[] }
    }

    #[inline]
    const fn with_bytes(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }
}

impl<'a> From<&'a [u8]> for InvalidBytes<'a> {
    fn from(bytes: &'a [u8]) -> Self {
        Self::with_bytes(bytes)
    }
}

impl<'a> Iterator for InvalidBytes<'a> {
    type Item = &'a [u8];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.bytes.is_empty() {
            None
        } else {
            // Splitting the byte slice is guaranteed to not panic because the
            // slice is non-empty.
            let (next, remainder) = self.bytes.split_at(1);
            self.bytes = remainder;
            Some(next)
        }
    }
}

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

#[derive(Default, Debug, Clone)]
pub struct ConventionallyUtf8<'a> {
    bytes: &'a [u8],
    invalid_bytes: InvalidBytes<'a>,
}

impl<'a> ConventionallyUtf8<'a> {
    #[inline]
    fn new() -> Self {
        let bytes = &[];
        Self {
            bytes,
            invalid_bytes: InvalidBytes::new(),
        }
    }

    #[inline]
    fn with_bytes(bytes: &'a [u8]) -> Self {
        Self {
            bytes,
            invalid_bytes: InvalidBytes::new(),
        }
    }
}

impl<'a> From<&'a [u8]> for ConventionallyUtf8<'a> {
    fn from(bytes: &'a [u8]) -> Self {
        Self::with_bytes(bytes)
    }
}

impl<'a> Iterator for ConventionallyUtf8<'a> {
    type Item = &'a [u8];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(slice) = self.invalid_bytes.next() {
            return Some(slice);
        }
        let (ch, size) = bstr::decode_utf8(self.bytes);
        if ch.is_some() {
            let (ch, remainder) = self.bytes.split_at(size);
            self.bytes = remainder;
            Some(ch)
        } else {
            let (invalid_utf8_bytes, remainder) = self.bytes.split_at(size);
            // Invalid UTF-8 bytes are yielded as byte slices one byte at a time.
            self.invalid_bytes = InvalidBytes::with_bytes(invalid_utf8_bytes);
            self.bytes = remainder;
            self.invalid_bytes.next()
        }
    }
}

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