parsec_encoding/
offsets.rs1use encoding_rs::{CoderResult, Encoding, UTF_8, UTF_16BE, UTF_16LE};
9
10pub struct Offsets {
39 points: Vec<(u32, u32)>,
42}
43
44impl Offsets {
45 pub fn new(bytes: &[u8], encoding: &'static Encoding) -> Offsets {
49 let bom = match Encoding::for_bom(bytes) {
50 Some((found, len)) if found == encoding => len,
51 _ => 0,
52 };
53 if encoding == UTF_8 {
54 return Offsets::utf8(bytes, bom);
55 }
56 let mut map = Offsets { points: Vec::new() };
57 map.at(0, bom);
58 if encoding.is_single_byte() {
59 let (text, _) = encoding.decode_without_bom_handling(bytes);
61 let mut decoded = 0;
62 for (i, c) in text.chars().enumerate() {
63 map.at(decoded, i);
64 decoded += c.len_utf8();
65 }
66 return map;
67 }
68 let narrow = encoding != UTF_16BE && encoding != UTF_16LE;
71 let mut decoder = encoding.new_decoder_without_bom_handling();
72 let mut out = [0u8; 64];
73 let mut decoded = 0;
74 let mut from = bom;
76 for i in bom..=bytes.len() {
77 let last = i == bytes.len();
78 let mut input = if last { &[][..] } else { &bytes[i..i + 1] };
79 let mut first = true;
80 loop {
81 let (result, read, written, _) = decoder.decode_to_utf8(input, &mut out, last);
82 input = &input[read..];
83 for (k, &b) in out[..written].iter().enumerate() {
84 if (b as i8) >= -0x40 {
86 let start = if first && !(narrow && b < 0x80) {
89 from
90 } else {
91 i
92 };
93 map.at(decoded + k, start);
94 first = false;
95 }
96 }
97 decoded += written;
98 if result == CoderResult::InputEmpty {
99 break;
100 }
101 }
102 if !first {
103 from = i + 1;
104 }
105 }
106 map.at(decoded, bytes.len());
107 map
108 }
109
110 pub fn lossy_utf8(bytes: &[u8]) -> Offsets {
115 Offsets::utf8(bytes, 0)
116 }
117
118 fn utf8(bytes: &[u8], bom: usize) -> Offsets {
122 let mut map = Offsets { points: Vec::new() };
123 map.at(0, bom);
124 let (mut decoded, mut source) = (0, bom);
125 for chunk in bytes[bom..].utf8_chunks() {
126 decoded += chunk.valid().len();
127 source += chunk.valid().len();
128 if !chunk.invalid().is_empty() {
129 decoded += '\u{FFFD}'.len_utf8();
130 source += chunk.invalid().len();
131 map.at(decoded, source);
132 }
133 }
134 map
135 }
136
137 fn at(&mut self, decoded: usize, source: usize) {
140 let (d, s) = self.points.last().copied().unwrap_or((0, 0));
141 if source as u64 != u64::from(s) + (decoded as u64 - u64::from(d)) {
142 self.points.push((decoded as u32, source as u32));
144 }
145 }
146
147 pub fn is_identity(&self) -> bool {
150 self.points.is_empty()
151 }
152
153 pub fn to_source(&self, decoded: usize) -> usize {
156 let i = self.points.partition_point(|&(d, _)| d as usize <= decoded);
157 match i.checked_sub(1).map(|i| self.points[i]) {
158 Some((d, s)) => (s as usize).saturating_add(decoded - d as usize),
159 None => decoded,
160 }
161 }
162
163 pub fn to_decoded(&self, source: usize) -> usize {
168 let i = self.points.partition_point(|&(_, s)| s as usize <= source);
169 match i.checked_sub(1).map(|i| self.points[i]) {
170 Some((d, s)) => {
171 let at = (d as usize).saturating_add(source - s as usize);
172 self.points
173 .get(i)
174 .map_or(at, |&(next, _)| at.min(next as usize))
175 }
176 None => source,
177 }
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184 use encoding_rs::*;
185
186 #[test]
187 fn lossy_utf8_keeps_the_byte_order_mark() {
188 let bytes = b"\xEF\xBB\xBF\xFF\xFFab";
189 let text = String::from_utf8_lossy(bytes);
190 let map = Offsets::lossy_utf8(bytes);
191 let a = text.find('a').unwrap();
192 assert_eq!(map.to_source(a), 5);
193 assert_eq!(map.to_decoded(5), a);
194 assert_eq!(map.to_source(0), 0);
195 assert!(Offsets::lossy_utf8(b"plain").is_identity());
196 }
197
198 #[test]
199 fn offsets_past_the_end_saturate() {
200 let map = Offsets::new(b"\xEF\xBB\xBFa\xFFb", UTF_8);
202 assert!(!map.is_identity());
203 for far in [usize::MAX, usize::MAX - 1, usize::MAX / 2 + 7] {
204 assert!(map.to_decoded(far) >= far / 2);
205 assert!(map.to_source(far) >= far / 2);
206 }
207 }
208
209 fn check(bytes: &[u8], encoding: &'static Encoding) -> Offsets {
212 let (text, _) = encoding.decode_with_bom_removal(bytes);
213 let map = Offsets::new(bytes, encoding);
214 for (d, c) in text.char_indices() {
215 if c.is_ascii() && encoding != UTF_16BE {
216 let s = map.to_source(d);
217 assert_eq!(bytes[s], c as u8, "{} at {d}", encoding.name());
218 assert_eq!(map.to_decoded(s), d);
219 }
220 }
221 assert_eq!(map.to_source(text.len()), bytes.len());
222 map
223 }
224
225 #[test]
226 fn ascii_and_clean_utf8_are_the_identity() {
227 assert!(check(b"<p>plain", UTF_8).is_identity());
228 assert!(check("<p>caf\u{e9}".as_bytes(), UTF_8).is_identity());
229 assert!(check(b"<p>plain", WINDOWS_1252).is_identity());
230 }
231
232 #[test]
233 fn utf8_boms_and_bad_bytes() {
234 let map = check(b"\xef\xbb\xbf<p>\xff\xfe</p><b>x", UTF_8);
235 assert_eq!(map.to_source(3 + 6 + 2), 3 + 3 + 2 + 2);
237 }
238
239 #[test]
240 fn legacy_multibyte() {
241 check(b"<p>\x93\xfa\x96\x7b</p><b>x</b>", SHIFT_JIS);
243 check(b"<p>\xc6\xfc\xcb\xdc</p><b>x</b>", EUC_JP);
244 check(b"<p>\x1b$BF|K\\\x1b(B</p><b>x</b>", ISO_2022_JP);
245 check(b"<p>\xc8\xd5\xb1\xbe</p><b>x</b>", GBK);
246 check(b"<p>\x81\x30\x81\x30\xc8\xd5</p><b>x</b>", GB18030);
247 check(b"<p>\xa4\xe9\xa5\xbb</p><b>x</b>", BIG5);
248 check(b"<p>\xc0\xcf\xba\xbb</p><b>x</b>", EUC_KR);
249 check(b"<p>\xcf\xf0\xe8</p><b>x</b>", WINDOWS_1251);
250 }
251
252 #[test]
253 fn a_bad_lead_byte_then_ascii() {
254 let map = check(b"<p>\x93<b>x</b>", SHIFT_JIS);
257 assert_eq!(map.to_source(6), 4);
258 check(b"<p>x\x93", SHIFT_JIS);
260 }
261
262 #[test]
263 fn utf16() {
264 let mut bytes = vec![0xff, 0xfe];
265 for u in "<p>\u{65e5}\u{1F600}x".encode_utf16() {
266 bytes.extend(u.to_le_bytes());
267 }
268 let map = check(&bytes, UTF_16LE);
269 assert_eq!(map.to_source(0), 2);
271 assert_eq!(map.to_source(3), 8);
272 assert_eq!(map.to_source(6), 10);
274 assert_eq!(map.to_source(10), 14);
275 assert_eq!(map.to_decoded(9), 4);
277 }
278}