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
#![no_std]
type Result = ::core::result::Result<Option<char>, Utf8ParserError>;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Utf8ParserError {
InvalidByte,
InvalidContinuationByte,
InvalidCodePoint(u32),
UnexpectedContinuationByte,
}
#[derive(Clone, Default)]
pub struct Utf8Parser {
value: u32,
length: u32,
}
const LEAD_MASK: [u8; 3] = [0x1F, 0x0F, 0x07];
const CONT_MASK: u8 = 0x3F;
impl Utf8Parser {
pub fn new() -> Utf8Parser {
Utf8Parser::default()
}
pub fn parse_byte(&mut self, byte: u8) -> Result {
use core::convert::TryFrom;
use Utf8ParserError::*;
if !is_valid_utf8_byte(byte) {
self.length = 0;
return Err(InvalidByte);
}
if self.length == 0 {
if byte < 0x80 {
return Ok(Some(char::from(byte)));
} else if is_utf8_continuation_byte(byte) {
return Err(UnexpectedContinuationByte);
}
self.length = utf8_length(byte) - 1;
self.value = (byte & LEAD_MASK[self.length as usize]) as u32;
return Ok(None);
} else {
if !is_utf8_continuation_byte(byte) {
self.length = 0;
return Err(InvalidContinuationByte);
}
self.value = (self.value << 6) | (byte & CONT_MASK) as u32;
self.length -= 1;
if self.length == 0 {
match char::try_from(self.value) {
Ok(c) => return Ok(Some(c)),
Err(_) => return Err(InvalidCodePoint(self.value)),
}
} else {
return Ok(None);
}
}
}
#[allow(unused)]
fn parse_bytes(&mut self, bytes: &[u8]) {
unimplemented!("Utf8Parser::parse_bytes is unimplemented due to uncertainties as to what its return type should be.");
}
}
#[inline]
fn is_valid_utf8_byte(byte: u8) -> bool {
match byte {
0xC0 | 0xC1 | 0xF5..=0xFF => false,
_ => true,
}
}
#[inline]
fn is_utf8_continuation_byte(byte: u8) -> bool {
(byte >> 6) == 0b10
}
#[inline]
fn utf8_length(byte: u8) -> u32 {
debug_assert!(is_valid_utf8_byte(byte) && !is_utf8_continuation_byte(byte));
if byte < 0x80 {
1
} else {
(!byte).leading_zeros()
}
}