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
//! Read UTF-8 characters from object that implement Read trait
//!
//! # Examples:
//! ```rust
//! use utf8_reader::Utf8Reader;
//! use std::io::Cursor;
//! use std::io::Write;
//!
//! let mut buf = Cursor::new(Vec::new());
//! buf.write("复/d❤".as_bytes()).unwrap();
//! buf.set_position(0);
//!
//! let mut reader = Utf8Reader::new(buf);
//!
//! assert_eq!(Some('复'.into()), reader.next());
//! assert_eq!(Some('/'.into()), reader.next());
//! assert_eq!(Some('d'.into()), reader.next());
//! assert_eq!(Some('❤'.into()), reader.next());
//! assert_eq!(None, reader.next());
//! ```

use std::convert::AsRef;
use std::convert::From;
use std::fmt;
use std::io::Read;
use std::iter::Iterator;
use std::str::FromStr;

/// representing a UTF-8 character
///
/// Note: a UTF-8 character inside UTF8Char indicates an array [u8; 4]
/// so if an UTF-8 charactor's length of byte greater than 4 is not allow. e.g. ❤️ is 6 bytes length
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct Utf8Char([u8; 4]);

impl Utf8Char {
    /// Extracts a byte slice containing the UTF-8 bytes
    pub fn as_slice(&self) -> &[u8] {
        match self.0 {
            [0, 0, 0, 0] | [0, 0, 0, _] => &self.0[3..],
            [0, 0, _, _] => &self.0[2..],
            [0, _, _, _] => &self.0[1..],
            _ => &self.0[..],
        }
    }

    /// Extracts a byte slice containing the UTF-8 bytes
    pub fn as_str(&self) -> &str {
        self.as_ref()
    }

    /// Return `true` if this char is `white_space`
    ///
    /// `white_space` includes ` `, `\t`, `\r`, `\n`
    pub fn is_whitespace(&self) -> bool {
        match self.0 {
            [0, 0, 0, 9] | [0, 0, 0, 10] | [0, 0, 0, 13] | [0, 0, 0, 32] => true,
            _ => false,
        }
    }

    /// Check if the value is an ASCII decimal digit
    ///
    /// 0 to 9
    pub fn is_ascii_digit(&self) -> bool {
        match self.0 {
            [0, 0, 0, v] if v >= b'0' && v <= b'9' => true,
            _ => false,
        }
    }

    /// Return `true` if this char is an `Alphabetic`
    pub fn is_alphabetic(&self) -> bool {
        match self.0 {
            [0, 0, 0, v] if v >= b'A' && v <= b'Z' || v >= b'a' && v <= b'z' => true,
            _ => false,
        }
    }

    /// convert a UTF8Char to a digit
    ///
    /// diget as defined to be only the 0-9
    ///
    /// # Error
    /// Returns [Nane] if the UTF8Char does not refer to a digit
    pub fn to_digit(&self) -> Option<u32> {
        match self.0 {
            [0, 0, 0, v] if v >= b'0' && v <= b'9' => Some((v - b'0').into()),
            _ => None,
        }
    }
}

impl From<u8> for Utf8Char {
    fn from(value: u8) -> Self {
        Self([0, 0, 0, value])
    }
}

impl From<u32> for Utf8Char {
    fn from(value: u32) -> Self {
        Self(value.to_be_bytes())
    }
}

impl From<char> for Utf8Char {
    fn from(value: char) -> Self {
        let mut b = [0; 4];
        let st = value.encode_utf8(&mut b);
        let st = st.as_bytes();
        let mut b = [0; 4];
        for (i, v) in ((4 - st.len())..4).enumerate() {
            b[v] = st[i];
        }

        Self(b)
    }
}

impl fmt::Display for Utf8Char {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            String::from_str(self.as_str()).expect("cannot convert to a String")
        )
    }
}

impl AsRef<str> for Utf8Char {
    fn as_ref(&self) -> &str {
        use std::str;
        str::from_utf8(self.as_slice())
            .expect("cannot convert to a str, maybe is not a valid UTF-8 character")
    }
}

impl PartialEq<&str> for Utf8Char {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl PartialEq<Utf8Char> for &str {
    fn eq(&self, other: &Utf8Char) -> bool {
        other.as_str() == *self
    }
}

/// Readd UTF-8 characters from object that implement Read
///
/// This is not validate the content whether it is a valid UTF-8 format or not
/// Implemented [Iterator]
///
/// # Example:
///
/// ```rust
/// # use utf8_reader::Utf8Reader;
/// # use std::io::Cursor;
/// # use std::io::Write;
///
/// let mut buf = Cursor::new(Vec::new());
/// buf.write("复/d❤".as_bytes()).unwrap();
/// buf.set_position(0);
///
/// let mut reader = Utf8Reader::new(buf);
///
/// assert_eq!(Some('复'.into()), reader.next());
/// assert_eq!(Some('/'.into()), reader.next());
/// assert_eq!(Some('d'.into()), reader.next());
/// assert_eq!(Some('❤'.into()), reader.next());
/// assert_eq!(None, reader.next());
/// ```
pub struct Utf8Reader<T: Read>(T);

impl<T: Read> Utf8Reader<T> {
    /// Create a new Utf8Reader
    ///
    /// # Argement:
    /// inner: object that implemented Read
    ///
    /// # Example:
    ///
    pub fn new(inner: T) -> Self {
        Self(inner)
    }
}

impl<T: Read> Iterator for Utf8Reader<T> {
    type Item = Utf8Char;

    fn next(&mut self) -> Option<Self::Item> {
        let mut b = [0u8; 1];
        let size = self.0.read(&mut b).expect("read a byte faied");
        if size == 0 {
            return None;
        }

        let first_byte = b[0];
        if first_byte < 128 {
            return Some(first_byte.into());
        }

        let utf8_32 = match first_byte & 0b11100000 {
            0b11110000 => exact_next(&mut self.0, 3, first_byte),
            0b11100000 => exact_next(&mut self.0, 2, first_byte),
            0b11000000 => exact_next(&mut self.0, 1, first_byte),
            _ => first_byte as u32,
        };

        Some(utf8_32.into())
    }
}

fn exact_next(read: &mut impl Read, count: usize, first_byte: u8) -> u32 {
    let mut b = [0u8; 1];
    let mut res_u32 = first_byte as u32;

    for _ in 0..count {
        let size = read.read(&mut b).expect("read a byte faied");
        if size != 0 {
            res_u32 = res_u32 << 8 | b[0] as u32;
        }
    }

    res_u32
}

#[cfg(test)]
mod test {
    use super::*;
    use std::io::Cursor;
    use std::io::Write;

    #[test]
    fn test_whitespace() {
        let mut buf = Cursor::new(Vec::new());
        buf.write(" d\t\r\n".as_bytes()).unwrap();
        buf.set_position(0);

        let mut r = Utf8Reader::new(buf);
        assert!(r.next().unwrap().is_whitespace());
        assert!(!r.next().unwrap().is_whitespace());
        assert!(r.next().unwrap().is_whitespace());
        assert!(r.next().unwrap().is_whitespace());
        assert!(r.next().unwrap().is_whitespace());
        assert!(r.next().is_none());
    }

    #[test]
    fn test_digit() {
        let mut buf = Cursor::new(Vec::new());
        buf.write("0123456789abi".as_bytes()).unwrap();
        buf.set_position(0);

        let mut r = Utf8Reader::new(buf);
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(r.next().unwrap().is_ascii_digit());
        assert!(!r.next().unwrap().is_ascii_digit());
        assert!(!r.next().unwrap().is_ascii_digit());
        assert!(!r.next().unwrap().is_ascii_digit());
        assert!(r.next().is_none());
    }

    #[test]
    fn test_to_digit() {
        let mut buf = Cursor::new(Vec::new());
        buf.write("0123456789abi".as_bytes()).unwrap();
        buf.set_position(0);

        let mut r = Utf8Reader::new(buf);
        assert_eq!(Some(0), r.next().unwrap().to_digit());
        assert_eq!(Some(1), r.next().unwrap().to_digit());
        assert_eq!(Some(2), r.next().unwrap().to_digit());
        assert_eq!(Some(3), r.next().unwrap().to_digit());
        assert_eq!(Some(4), r.next().unwrap().to_digit());
        assert_eq!(Some(5), r.next().unwrap().to_digit());
        assert_eq!(Some(6), r.next().unwrap().to_digit());
        assert_eq!(Some(7), r.next().unwrap().to_digit());
        assert_eq!(Some(8), r.next().unwrap().to_digit());
        assert_eq!(Some(9), r.next().unwrap().to_digit());
        assert_eq!(None, r.next().unwrap().to_digit());
        assert_eq!(None, r.next().unwrap().to_digit());
        assert_eq!(None, r.next().unwrap().to_digit());
        assert_eq!(None, r.next());
    }

    #[test]
    fn is_alphabetic() {
        let mut buf = Cursor::new(Vec::new());
        buf.write("abcdABCDEZz0000".as_bytes()).unwrap();
        buf.set_position(0);

        let mut r = Utf8Reader::new(buf);
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(r.next().unwrap().is_alphabetic());
        assert!(!r.next().unwrap().is_alphabetic());
        assert!(!r.next().unwrap().is_alphabetic());
        assert!(!r.next().unwrap().is_alphabetic());
        assert!(!r.next().unwrap().is_alphabetic());
        assert!(r.next().is_none());
    }

    #[test]
    fn test_display() {
        let mut buf = Cursor::new(Vec::new());
        buf.write("复// d".as_bytes()).unwrap();
        buf.set_position(0);

        let mut r = Utf8Reader::new(buf);
        assert_eq!("复".to_string(), r.next().unwrap().to_string());
        assert_eq!("/".to_string(), r.next().unwrap().to_string());
    }

    #[test]
    fn test_as_str() {
        let mut buf = Cursor::new(Vec::new());
        buf.write("复// d".as_bytes()).unwrap();
        buf.set_position(0);

        let mut r = Utf8Reader::new(buf);
        let utf8char = r.next().unwrap();
        assert_eq!("复", utf8char.as_ref());
        let utf8char = r.next().unwrap();
        assert_eq!("/", utf8char.as_ref());
        let utf8char = r.next().unwrap();
        assert_eq!("/", utf8char.as_ref());
        let utf8char = r.next().unwrap();
        assert_eq!(" ", utf8char.as_ref());
        let utf8char = r.next().unwrap();
        assert_eq!("d", utf8char.as_ref());
        assert_eq!(None, r.next());
    }

    #[test]
    fn test_iterator() {
        let mut buf = Cursor::new(Vec::new());
        buf.write(
            r"复// d❤
1+1=2 // é异"
                .as_bytes(),
        )
        .unwrap();
        buf.set_position(0);

        let mut r = Utf8Reader::new(buf);

        assert_eq!(Some('复'.into()), r.next());
        assert_eq!(Some('/'.into()), r.next());
        assert_eq!(Some('/'.into()), r.next());
        assert_eq!(Some(' '.into()), r.next());
        assert_eq!(Some('d'.into()), r.next());
        assert_eq!(Some('❤'.into()), r.next());
        assert_eq!(Some('\n'.into()), r.next());
        assert_eq!(Some('1'.into()), r.next());
        assert_eq!(Some('+'.into()), r.next());
        assert_eq!(Some('1'.into()), r.next());
        assert_eq!(Some('='.into()), r.next());
        assert_eq!(Some('2'.into()), r.next());
        assert_eq!(Some(' '.into()), r.next());
        assert_eq!(Some('/'.into()), r.next());
        assert_eq!(Some('/'.into()), r.next());
        assert_eq!(Some(' '.into()), r.next());
        assert_eq!(Some('é'.into()), r.next());
        assert_eq!(Some('异'.into()), r.next());
        assert_eq!(None, r.next());
    }

    #[test]
    fn wrong_character() {
        let mut buf = Cursor::new(Vec::new());
        buf.write("\u{D7FF}复".as_bytes()).unwrap();
        buf.set_position(0);

        let mut r = Utf8Reader::new(buf);
        assert_eq!(Some('\u{D7FF}'.into()), r.next());
        assert_eq!(Some('复'.into()), r.next());
        assert_eq!(None, r.next());
    }

    #[test]
    fn equal_str() {
        let mut buf = Cursor::new(Vec::new());
        buf.write("0a/*-比".as_bytes()).unwrap();
        buf.set_position(0);

        let mut r = Utf8Reader::new(buf);
        assert_eq!("0", r.next().unwrap());
        assert_eq!("a", r.next().unwrap());
        assert_eq!("/", r.next().unwrap());
        assert_eq!("*", r.next().unwrap());
        assert_eq!("-", r.next().unwrap());
        assert_eq!(r.next().unwrap(), "比");
        assert_eq!(None, r.next());
    }
}