1#![deny(missing_debug_implementations, missing_docs, rust_2018_idioms)]
11
12#[allow(missing_debug_implementations, missing_docs)]
13mod newlines;
14#[cfg(test)]
15mod tests;
16
17use nohash_hasher::IntMap;
18
19pub use newlines::{
20 Line, LineEnding, NewlineWithTrailingNewline, UniversalNewlineIterator, UniversalNewlines,
21 find_newline,
22};
23pub use text_size::{TextRange, TextSize};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub struct LineCol {
28 pub line: u32,
30 pub col: u32,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36#[non_exhaustive]
37pub enum WideEncoding {
38 Utf16,
40 Utf32,
42}
43
44impl WideEncoding {
45 pub fn measure(&self, text: &str) -> usize {
47 match self {
48 WideEncoding::Utf16 => text.encode_utf16().count(),
49 WideEncoding::Utf32 => text.chars().count(),
50 }
51 }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub struct WideLineCol {
61 pub line: u32,
63 pub col: u32,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68struct WideChar {
69 start: TextSize,
71 end: TextSize,
73}
74
75impl WideChar {
76 fn len(&self) -> TextSize {
78 self.end - self.start
79 }
80
81 fn wide_len(&self, enc: WideEncoding) -> u32 {
83 match enc {
84 WideEncoding::Utf16 => {
85 if self.len() == TextSize::from(4) {
86 2
87 } else {
88 1
89 }
90 }
91 WideEncoding::Utf32 => 1,
92 }
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct LineIndex {
99 newlines: Box<[TextSize]>,
101 line_wide_chars: IntMap<u32, Box<[WideChar]>>,
103 len: TextSize,
105}
106
107impl LineIndex {
108 pub fn new(text: &str) -> LineIndex {
110 let (newlines, line_wide_chars) = analyze_source_file(text);
111 LineIndex {
112 newlines: newlines.into_boxed_slice(),
113 line_wide_chars,
114 len: TextSize::of(text),
115 }
116 }
117
118 pub fn line_col(&self, offset: TextSize) -> LineCol {
124 self.try_line_col(offset).expect("invalid offset")
125 }
126
127 pub fn try_line_col(&self, offset: TextSize) -> Option<LineCol> {
132 if offset > self.len {
133 return None;
134 }
135 let line = self.newlines.partition_point(|&it| it <= offset);
136 let start = self.start_offset(line)?;
137 let col = offset - start;
138 let ret = LineCol {
139 line: line as u32,
140 col: col.into(),
141 };
142 self.line_wide_chars
143 .get(&ret.line)
144 .into_iter()
145 .flat_map(|it| it.iter())
146 .all(|it| col <= it.start || it.end <= col)
147 .then_some(ret)
148 }
149
150 pub fn offset(&self, line_col: LineCol) -> Option<TextSize> {
152 self.start_offset(line_col.line as usize)
153 .map(|start| start + TextSize::from(line_col.col))
154 }
155
156 fn start_offset(&self, line: usize) -> Option<TextSize> {
157 match line.checked_sub(1) {
158 None => Some(TextSize::from(0)),
159 Some(it) => self.newlines.get(it).copied(),
160 }
161 }
162
163 pub fn to_wide(&self, enc: WideEncoding, line_col: LineCol) -> Option<WideLineCol> {
165 let mut col = line_col.col;
166 if let Some(wide_chars) = self.line_wide_chars.get(&line_col.line) {
167 for c in wide_chars {
168 if u32::from(c.end) <= line_col.col {
169 col = col.checked_sub(u32::from(c.len()) - c.wide_len(enc))?;
170 } else {
171 break;
174 }
175 }
176 }
177 Some(WideLineCol {
178 line: line_col.line,
179 col,
180 })
181 }
182
183 pub fn to_utf8(&self, enc: WideEncoding, line_col: WideLineCol) -> Option<LineCol> {
185 let mut col = line_col.col;
186 if let Some(wide_chars) = self.line_wide_chars.get(&line_col.line) {
187 for c in wide_chars {
188 if col > u32::from(c.start) {
189 col = col.checked_add(u32::from(c.len()) - c.wide_len(enc))?;
190 } else {
191 break;
194 }
195 }
196 }
197 Some(LineCol {
198 line: line_col.line,
199 col,
200 })
201 }
202
203 pub fn line(&self, line: u32) -> Option<TextRange> {
205 let start = self.start_offset(line as usize)?;
206 let next_newline = self
207 .newlines
208 .get(line as usize)
209 .copied()
210 .unwrap_or(self.len);
211 let line_length = next_newline - start;
212 Some(TextRange::new(start, start + line_length))
213 }
214
215 pub fn lines(&self, range: TextRange) -> impl Iterator<Item = TextRange> + '_ {
219 let lo = self.newlines.partition_point(|&it| it < range.start());
220 let hi = self.newlines.partition_point(|&it| it <= range.end());
221 let all = std::iter::once(range.start())
222 .chain(self.newlines[lo..hi].iter().copied())
223 .chain(std::iter::once(range.end()));
224
225 all.clone()
226 .zip(all.skip(1))
227 .map(|(lo, hi)| TextRange::new(lo, hi))
228 .filter(|it| !it.is_empty())
229 }
230
231 pub fn len(&self) -> TextSize {
233 self.len
234 }
235}
236
237fn analyze_source_file(src: &str) -> (Vec<TextSize>, IntMap<u32, Box<[WideChar]>>) {
239 assert!(src.len() < !0u32 as usize);
240 let mut lines = vec![];
241 let mut line_wide_chars = IntMap::<u32, Vec<WideChar>>::default();
242
243 analyze_source_file_dispatch(src, &mut lines, &mut line_wide_chars);
245
246 (
247 lines,
248 line_wide_chars
249 .into_iter()
250 .map(|(k, v)| (k, v.into_boxed_slice()))
251 .collect(),
252 )
253}
254
255#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
256fn analyze_source_file_dispatch(
257 src: &str,
258 lines: &mut Vec<TextSize>,
259 multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
260) {
261 if is_x86_feature_detected!("sse2") {
262 unsafe {
264 analyze_source_file_sse2(src, lines, multi_byte_chars);
265 }
266 } else {
267 analyze_source_file_generic(src, src.len(), TextSize::from(0), lines, multi_byte_chars);
268 }
269}
270
271#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
272fn analyze_source_file_dispatch(
273 src: &str,
274 lines: &mut Vec<TextSize>,
275 multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
276) {
277 if std::arch::is_aarch64_feature_detected!("neon") {
278 unsafe {
280 analyze_source_file_neon(src, lines, multi_byte_chars);
281 }
282 } else {
283 analyze_source_file_generic(src, src.len(), TextSize::from(0), lines, multi_byte_chars);
284 }
285}
286
287#[target_feature(enable = "sse2")]
292#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
293#[allow(unsafe_op_in_unsafe_fn)]
295unsafe fn analyze_source_file_sse2(
296 src: &str,
297 lines: &mut Vec<TextSize>,
298 multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
299) {
300 #[cfg(target_arch = "x86")]
301 use std::arch::x86::*;
302 #[cfg(target_arch = "x86_64")]
303 use std::arch::x86_64::*;
304
305 const CHUNK_SIZE: usize = 16;
306
307 let src_bytes = src.as_bytes();
308
309 let chunk_count = src.len() / CHUNK_SIZE;
310
311 let mut intra_chunk_offset = 0;
316
317 for chunk_index in 0..chunk_count {
318 let ptr = src_bytes.as_ptr() as *const __m128i;
319 let chunk = unsafe { _mm_loadu_si128(ptr.add(chunk_index)) };
322
323 let multibyte_test = _mm_cmplt_epi8(chunk, _mm_set1_epi8(0));
326 let multibyte_mask = _mm_movemask_epi8(multibyte_test);
328
329 let cr_test = _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\r' as i8));
333 let cr_mask = _mm_movemask_epi8(cr_test);
334
335 if multibyte_mask == 0 && cr_mask == 0 {
337 assert!(intra_chunk_offset == 0);
338
339 let newlines_test = _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\n' as i8));
341 let newlines_mask = _mm_movemask_epi8(newlines_test);
342
343 if newlines_mask != 0 {
344 let mut newlines_mask = 0xFFFF0000 | newlines_mask as u32;
346 let output_offset = TextSize::from((chunk_index * CHUNK_SIZE + 1) as u32);
347
348 loop {
349 let index = newlines_mask.trailing_zeros();
350
351 if index >= CHUNK_SIZE as u32 {
352 break;
354 }
355
356 lines.push(TextSize::from(index) + output_offset);
357
358 newlines_mask &= (!1) << index;
360 }
361 }
362 continue;
363 }
364
365 let scan_start = chunk_index * CHUNK_SIZE + intra_chunk_offset;
368 intra_chunk_offset = analyze_source_file_generic(
369 &src[scan_start..],
370 CHUNK_SIZE - intra_chunk_offset,
371 TextSize::from(scan_start as u32),
372 lines,
373 multi_byte_chars,
374 );
375 }
376
377 let tail_start = chunk_count * CHUNK_SIZE + intra_chunk_offset;
379 if tail_start < src.len() {
380 analyze_source_file_generic(
381 &src[tail_start..],
382 src.len() - tail_start,
383 TextSize::from(tail_start as u32),
384 lines,
385 multi_byte_chars,
386 );
387 }
388}
389
390#[target_feature(enable = "neon")]
391#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
392#[inline]
393#[allow(unsafe_op_in_unsafe_fn)]
400unsafe fn move_mask(v: std::arch::aarch64::uint8x16_t) -> u64 {
401 use std::arch::aarch64::*;
402
403 let nibble_mask = vshrn_n_u16(vreinterpretq_u16_u8(v), 4);
404 vget_lane_u64(vreinterpret_u64_u8(nibble_mask), 0)
405}
406
407#[target_feature(enable = "neon")]
408#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
409#[allow(unsafe_op_in_unsafe_fn)]
411unsafe fn analyze_source_file_neon(
412 src: &str,
413 lines: &mut Vec<TextSize>,
414 multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
415) {
416 use std::arch::aarch64::*;
417
418 const CHUNK_SIZE: usize = 16;
419
420 let src_bytes = src.as_bytes();
421
422 let chunk_count = src.len() / CHUNK_SIZE;
423
424 let newline = vdupq_n_s8(b'\n' as i8);
425 let carriage_return = vdupq_n_s8(b'\r' as i8);
427
428 let mut intra_chunk_offset = 0;
433
434 for chunk_index in 0..chunk_count {
435 let ptr = src_bytes.as_ptr() as *const i8;
436 let chunk = unsafe { vld1q_s8(ptr.add(chunk_index * CHUNK_SIZE)) };
437
438 let multibyte_test = vcltzq_s8(chunk);
441 let multibyte_mask = unsafe { move_mask(multibyte_test) };
443
444 let cr_test = vceqq_s8(chunk, carriage_return);
446 let cr_mask = unsafe { move_mask(cr_test) };
447
448 if multibyte_mask == 0 && cr_mask == 0 {
450 assert!(intra_chunk_offset == 0);
451
452 let newlines_test = vceqq_s8(chunk, newline);
454 let mut newlines_mask = unsafe { move_mask(newlines_test) };
455
456 if newlines_mask != 0 {
458 let output_offset = TextSize::from((chunk_index * CHUNK_SIZE + 1) as u32);
459
460 while newlines_mask != 0 {
461 let trailing_zeros = newlines_mask.trailing_zeros();
462 let index = trailing_zeros / 4;
463
464 lines.push(TextSize::from(index) + output_offset);
465
466 newlines_mask &= (!0xF) << trailing_zeros;
468 }
469 }
470 continue;
471 }
472
473 let scan_start = chunk_index * CHUNK_SIZE + intra_chunk_offset;
474 intra_chunk_offset = analyze_source_file_generic(
475 &src[scan_start..],
476 CHUNK_SIZE - intra_chunk_offset,
477 TextSize::from(scan_start as u32),
478 lines,
479 multi_byte_chars,
480 );
481 }
482
483 let tail_start = chunk_count * CHUNK_SIZE + intra_chunk_offset;
484 if tail_start < src.len() {
485 analyze_source_file_generic(
486 &src[tail_start..],
487 src.len() - tail_start,
488 TextSize::from(tail_start as u32),
489 lines,
490 multi_byte_chars,
491 );
492 }
493}
494
495#[cfg(not(any(
496 target_arch = "x86",
497 target_arch = "x86_64",
498 all(target_arch = "aarch64", target_endian = "little")
499)))]
500fn analyze_source_file_dispatch(
502 src: &str,
503 lines: &mut Vec<TextSize>,
504 multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
505) {
506 analyze_source_file_generic(src, src.len(), TextSize::from(0), lines, multi_byte_chars);
507}
508
509fn analyze_source_file_generic(
513 src: &str,
514 scan_len: usize,
515 output_offset: TextSize,
516 lines: &mut Vec<TextSize>,
517 multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
518) -> usize {
519 assert!(src.len() >= scan_len);
520 let mut i = 0;
521 let src_bytes = src.as_bytes();
522
523 while i < scan_len {
524 let byte = unsafe {
525 *src_bytes.get_unchecked(i)
527 };
528
529 let mut char_len = 1;
532
533 if byte == b'\n' {
534 lines.push(TextSize::from(i as u32 + 1) + output_offset);
535 } else if byte == b'\r' && src_bytes.get(i + 1) != Some(&b'\n') {
540 lines.push(TextSize::from(i as u32 + 1) + output_offset);
541 } else if byte >= 127 {
542 let c = src[i..].chars().next().unwrap();
544 char_len = c.len_utf8();
545
546 let pos = TextSize::from(i as u32) + output_offset
549 - lines.last().unwrap_or(&TextSize::default());
550
551 if char_len > 1 {
552 assert!((2..=4).contains(&char_len));
553 let mbc = WideChar {
554 start: pos,
555 end: pos + TextSize::from(char_len as u32),
556 };
557 multi_byte_chars
558 .entry(lines.len() as u32)
559 .or_default()
560 .push(mbc);
561 }
562 }
563
564 i += char_len;
565 }
566
567 i - scan_len
568}