simd_csv/searcher.rs
1use std::iter::FusedIterator;
2
3#[cfg(target_arch = "x86_64")]
4mod x86_64 {
5 use std::marker::PhantomData;
6
7 use crate::ext::Pointer;
8
9 #[inline(always)]
10 fn get_for_offset(mask: u32) -> u32 {
11 #[cfg(target_endian = "big")]
12 {
13 mask.swap_bytes()
14 }
15 #[cfg(target_endian = "little")]
16 {
17 mask
18 }
19 }
20
21 #[inline(always)]
22 fn first_offset(mask: u32) -> usize {
23 get_for_offset(mask).trailing_zeros() as usize
24 }
25
26 #[inline(always)]
27 fn clear_least_significant_bit(mask: u32) -> u32 {
28 mask & (mask - 1)
29 }
30
31 // pub struct MaskIter(u32);
32
33 // impl Iterator for MaskIter {
34 // type Item = usize;
35
36 // #[inline(always)]
37 // fn next(&mut self) -> Option<Self::Item> {
38 // if self.0 == 0 {
39 // None
40 // } else {
41 // let offset = first_offset(self.0);
42 // self.0 = clear_least_significant_bit(self.0);
43 // Some(offset)
44 // }
45 // }
46 // }
47
48 // #[derive(Clone, Copy, Debug)]
49 // pub struct Mask(u32);
50
51 // impl Mask {
52 // #[inline(always)]
53 // pub fn into_first_offset(self) -> Option<usize> {
54 // if self.0 != 0 {
55 // Some(first_offset(self.0))
56 // } else {
57 // None
58 // }
59 // }
60
61 // #[inline(always)]
62 // pub fn into_iter(self) -> MaskIter {
63 // MaskIter(self.0)
64 // }
65 // }
66
67 pub mod sse2 {
68 use super::*;
69
70 use core::arch::x86_64::{
71 __m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_or_si128,
72 _mm_set1_epi8,
73 };
74
75 const CHUNK_SIZE: usize = 16;
76 // const FULL_MASK: u32 = (1 << CHUNK_SIZE) - 1;
77
78 #[derive(Debug)]
79 pub struct SSE2Searcher {
80 delimiter: u8,
81 newline: u8,
82 quote: u8,
83 delimiter_splat: __m128i,
84 newline_splat: __m128i,
85 quote_splat: __m128i,
86 }
87
88 impl SSE2Searcher {
89 #[inline]
90 pub unsafe fn new(delimiter: u8, newline: u8, quote: u8) -> Self {
91 Self {
92 delimiter,
93 newline,
94 quote,
95 delimiter_splat: _mm_set1_epi8(delimiter as i8),
96 newline_splat: _mm_set1_epi8(newline as i8),
97 quote_splat: _mm_set1_epi8(quote as i8),
98 }
99 }
100
101 #[inline(always)]
102 pub fn iter<'s, 'h>(&'s self, haystack: &'h [u8]) -> SSE2Indices<'s, 'h> {
103 SSE2Indices::new(self, haystack)
104 }
105
106 // #[inline(always)]
107 // unsafe fn process_loaded_chunk(&self, chunk: __m128i, valid_mask: u32) -> (Mask, Mask) {
108 // let delimiter_cmp = _mm_cmpeq_epi8(chunk, self.delimiter_splat);
109 // let newline_cmp = _mm_cmpeq_epi8(chunk, self.newline_splat);
110 // let quote_cmp = _mm_cmpeq_epi8(chunk, self.quote_splat);
111
112 // let structural_cmp = _mm_or_si128(newline_cmp, quote_cmp);
113
114 // // Ignore invalid lanes before looking for the first structural byte.
115 // let structural_mask = (_mm_movemask_epi8(structural_cmp) as u32) & valid_mask;
116 // let mut delimiter_mask = (_mm_movemask_epi8(delimiter_cmp) as u32) & valid_mask;
117
118 // delimiter_mask &= (1u32 << ((structural_mask | 0x1_0000).trailing_zeros())) - 1;
119
120 // (Mask(delimiter_mask), Mask(structural_mask))
121 // }
122
123 // #[inline]
124 // pub unsafe fn process_chunk(&self, haystack: &[u8]) -> (usize, (Mask, Mask)) {
125 // if haystack.len() >= CHUNK_SIZE {
126 // let chunk = _mm_loadu_si128(haystack.as_ptr() as *const __m128i);
127 // return (CHUNK_SIZE, self.process_loaded_chunk(chunk, FULL_MASK));
128 // }
129
130 // let mut tail = [0u8; CHUNK_SIZE];
131 // tail[..haystack.len()].copy_from_slice(haystack);
132
133 // let chunk = _mm_loadu_si128(tail.as_ptr() as *const __m128i);
134
135 // let valid_mask = match haystack.len() {
136 // 0 => 0,
137 // n => (1u32 << n) - 1,
138 // };
139
140 // (haystack.len(), self.process_loaded_chunk(chunk, valid_mask))
141 // }
142 }
143
144 #[derive(Debug)]
145 pub struct SSE2Indices<'s, 'h> {
146 searcher: &'s SSE2Searcher,
147 haystack: PhantomData<&'h [u8]>,
148 start: *const u8,
149 end: *const u8,
150 current: *const u8,
151 mask: u32,
152 }
153
154 impl<'s, 'h> SSE2Indices<'s, 'h> {
155 #[inline]
156 fn new(searcher: &'s SSE2Searcher, haystack: &'h [u8]) -> Self {
157 let ptr = haystack.as_ptr();
158
159 Self {
160 searcher,
161 haystack: PhantomData,
162 start: ptr,
163 end: ptr.wrapping_add(haystack.len()),
164 current: ptr,
165 mask: 0,
166 }
167 }
168 }
169
170 impl SSE2Indices<'_, '_> {
171 pub unsafe fn next(&mut self) -> Option<usize> {
172 if self.start >= self.end {
173 return None;
174 }
175
176 let mut mask = self.mask;
177
178 let mut current = self.current;
179 let start = self.start;
180 let len = self.end.distance(start);
181 let delimiter_splat = self.searcher.delimiter_splat;
182 let newline_splat = self.searcher.newline_splat;
183 let quote_splat = self.searcher.quote_splat;
184
185 'main: loop {
186 // Processing current move mask
187 if mask != 0 {
188 let offset = current.sub(CHUNK_SIZE).add(first_offset(mask));
189 self.mask = clear_least_significant_bit(mask);
190 self.current = current;
191
192 return Some(offset.distance(start));
193 }
194
195 // Main loop of unaligned loads
196 if len >= CHUNK_SIZE {
197 let vectorized_end = self.end.sub(CHUNK_SIZE);
198
199 while current <= vectorized_end {
200 let chunk = _mm_loadu_si128(current as *const __m128i);
201 let cmp1 = _mm_cmpeq_epi8(chunk, delimiter_splat);
202 let cmp2 = _mm_cmpeq_epi8(chunk, newline_splat);
203 let cmp3 = _mm_cmpeq_epi8(chunk, quote_splat);
204 let cmp = _mm_or_si128(cmp1, cmp2);
205 let cmp = _mm_or_si128(cmp, cmp3);
206
207 mask = _mm_movemask_epi8(cmp) as u32;
208
209 current = current.add(CHUNK_SIZE);
210
211 if mask != 0 {
212 continue 'main;
213 }
214 }
215 }
216
217 // Processing remaining bytes linearly
218 while current < self.end {
219 if *current == self.searcher.delimiter
220 || *current == self.searcher.newline
221 || *current == self.searcher.quote
222 {
223 let offset = current.distance(start);
224 self.current = current.add(1);
225 return Some(offset);
226 }
227 current = current.add(1);
228 }
229
230 return None;
231 }
232 }
233 }
234 }
235}
236
237#[cfg(target_arch = "aarch64")]
238mod aarch64 {
239 use core::arch::aarch64::{
240 uint8x16_t, vceqq_u8, vdupq_n_u8, vget_lane_u64, vld1q_u8, vorrq_u8, vreinterpret_u64_u8,
241 vreinterpretq_u16_u8, vshrn_n_u16,
242 };
243 use std::marker::PhantomData;
244
245 use crate::ext::Pointer;
246
247 const CHUNK_SIZE: usize = 16;
248
249 #[inline(always)]
250 unsafe fn neon_movemask(v: uint8x16_t) -> u64 {
251 let asu16s = vreinterpretq_u16_u8(v);
252 let mask = vshrn_n_u16(asu16s, 4);
253 let asu64 = vreinterpret_u64_u8(mask);
254 let scalar64 = vget_lane_u64(asu64, 0);
255
256 scalar64 & 0x8888888888888888
257 }
258
259 #[inline(always)]
260 fn first_offset(mask: u64) -> usize {
261 (mask.trailing_zeros() >> 2) as usize
262 }
263
264 #[inline(always)]
265 fn clear_least_significant_bit(mask: u64) -> u64 {
266 mask & (mask - 1)
267 }
268
269 #[derive(Debug)]
270 pub struct NeonSearcher {
271 delimiter: u8,
272 newline: u8,
273 quote: u8,
274 delimiter_splat: uint8x16_t,
275 newline_splat: uint8x16_t,
276 quote_splat: uint8x16_t,
277 }
278
279 impl NeonSearcher {
280 #[inline]
281 pub unsafe fn new(delimiter: u8, newline: u8, quote: u8) -> Self {
282 Self {
283 delimiter,
284 newline,
285 quote,
286 delimiter_splat: vdupq_n_u8(delimiter),
287 newline_splat: vdupq_n_u8(newline),
288 quote_splat: vdupq_n_u8(quote),
289 }
290 }
291
292 #[inline(always)]
293 pub fn iter<'s, 'h>(&'s self, haystack: &'h [u8]) -> NeonIndices<'s, 'h> {
294 NeonIndices::new(self, haystack)
295 }
296 }
297
298 #[derive(Debug)]
299 pub struct NeonIndices<'s, 'h> {
300 searcher: &'s NeonSearcher,
301 haystack: PhantomData<&'h [u8]>,
302 start: *const u8,
303 end: *const u8,
304 current: *const u8,
305 mask: u64,
306 }
307
308 impl<'s, 'h> NeonIndices<'s, 'h> {
309 #[inline]
310 fn new(searcher: &'s NeonSearcher, haystack: &'h [u8]) -> Self {
311 let ptr = haystack.as_ptr();
312
313 Self {
314 searcher,
315 haystack: PhantomData,
316 start: ptr,
317 end: ptr.wrapping_add(haystack.len()),
318 current: ptr,
319 mask: 0,
320 }
321 }
322 }
323
324 impl NeonIndices<'_, '_> {
325 #[inline]
326 pub unsafe fn _next_in_current_mask(&mut self) -> Option<usize> {
327 let mask = self.mask;
328 let current = self.current;
329
330 if mask != 0 {
331 let offset = current.sub(CHUNK_SIZE).add(first_offset(mask));
332 self.mask = clear_least_significant_bit(mask);
333 self.current = current;
334
335 Some(offset.distance(self.start))
336 } else {
337 None
338 }
339 }
340
341 pub unsafe fn next(&mut self) -> Option<usize> {
342 if self.start >= self.end {
343 return None;
344 }
345
346 let mut mask = self.mask;
347 let mut current = self.current;
348 let start = self.start;
349 let len = self.end.distance(start);
350 let delimiter_splat = self.searcher.delimiter_splat;
351 let newline_splat = self.searcher.newline_splat;
352 let quote_splat = self.searcher.quote_splat;
353
354 'main: loop {
355 // Processing current move mask
356 if mask != 0 {
357 let offset = current.sub(CHUNK_SIZE).add(first_offset(mask));
358 self.mask = clear_least_significant_bit(mask);
359 self.current = current;
360
361 return Some(offset.distance(start));
362 }
363
364 // Main loop of unaligned loads
365 if len >= CHUNK_SIZE {
366 let vectorized_end = self.end.sub(CHUNK_SIZE);
367
368 while current <= vectorized_end {
369 let chunk = vld1q_u8(current);
370 let cmp1 = vceqq_u8(chunk, delimiter_splat);
371 let cmp2 = vceqq_u8(chunk, newline_splat);
372 let cmp3 = vceqq_u8(chunk, quote_splat);
373 let cmp = vorrq_u8(cmp1, cmp2);
374 let cmp = vorrq_u8(cmp, cmp3);
375
376 mask = neon_movemask(cmp);
377
378 current = current.add(CHUNK_SIZE);
379
380 if mask != 0 {
381 continue 'main;
382 }
383 }
384 }
385
386 // Processing remaining bytes linearly
387 while current < self.end {
388 if *current == self.searcher.delimiter
389 || *current == self.searcher.newline
390 || *current == self.searcher.quote
391 {
392 let offset = current.distance(start);
393 self.current = current.add(1);
394 return Some(offset);
395 }
396 current = current.add(1);
397 }
398
399 return None;
400 }
401 }
402 }
403}
404
405/// Returns the SIMD instructions used by this crate's amortized `memchr`-like
406/// searcher.
407///
408/// Note that `memchr` routines, also used by this crate might use different
409/// instruction sets.
410pub fn searcher_simd_instructions() -> &'static str {
411 #[cfg(target_arch = "x86_64")]
412 {
413 "sse2"
414 }
415
416 #[cfg(target_arch = "aarch64")]
417 {
418 "neon"
419 }
420
421 #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
422 {
423 "none"
424 }
425}
426
427// #[cfg(target_arch = "x86_64")]
428// pub use x86_64::Mask;
429
430#[derive(Debug)]
431pub struct Searcher {
432 #[cfg(target_arch = "x86_64")]
433 inner: x86_64::sse2::SSE2Searcher,
434
435 #[cfg(target_arch = "aarch64")]
436 inner: aarch64::NeonSearcher,
437
438 #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
439 inner: memchr::arch::all::memchr::Three,
440}
441
442impl Searcher {
443 #[inline(always)]
444 pub fn new(delimiter: u8, newline: u8, quote: u8) -> Self {
445 #[cfg(target_arch = "x86_64")]
446 {
447 unsafe {
448 Self {
449 inner: x86_64::sse2::SSE2Searcher::new(delimiter, newline, quote),
450 }
451 }
452 }
453
454 #[cfg(target_arch = "aarch64")]
455 {
456 unsafe {
457 Self {
458 inner: aarch64::NeonSearcher::new(delimiter, newline, quote),
459 }
460 }
461 }
462
463 #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
464 {
465 Self {
466 inner: memchr::arch::all::memchr::Three::new(delimiter, newline, quote),
467 }
468 }
469 }
470
471 #[inline(always)]
472 pub fn search<'s, 'h>(&'s self, haystack: &'h [u8]) -> Indices<'s, 'h> {
473 Indices {
474 inner: self.inner.iter(haystack),
475 }
476 }
477
478 // #[inline(always)]
479 // pub fn process_chunk(&self, haystack: &[u8]) -> (usize, (Mask, Mask)) {
480 // #[cfg(target_arch = "x86_64")]
481 // unsafe {
482 // self.inner.process_chunk(haystack)
483 // }
484
485 // #[cfg(target_arch = "aarch64")]
486 // {
487 // unimplemented!()
488 // }
489
490 // #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
491 // {
492 // unimplemented!()
493 // }
494 // }
495}
496
497#[derive(Debug)]
498pub struct Indices<'s, 'h> {
499 #[cfg(target_arch = "x86_64")]
500 inner: x86_64::sse2::SSE2Indices<'s, 'h>,
501
502 #[cfg(target_arch = "aarch64")]
503 inner: aarch64::NeonIndices<'s, 'h>,
504
505 #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
506 inner: memchr::arch::all::memchr::ThreeIter<'s, 'h>,
507}
508
509impl FusedIterator for Indices<'_, '_> {}
510
511impl Iterator for Indices<'_, '_> {
512 type Item = usize;
513
514 #[inline(always)]
515 fn next(&mut self) -> Option<Self::Item> {
516 #[cfg(target_arch = "x86_64")]
517 {
518 unsafe { self.inner.next() }
519 }
520
521 #[cfg(target_arch = "aarch64")]
522 {
523 unsafe { self.inner.next() }
524 }
525
526 #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
527 {
528 self.inner.next()
529 }
530 }
531}
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536
537 use memchr::arch::all::memchr::Three;
538
539 static TEST_STRING: &[u8] = b"name,\"surname\",age,color,oper\n,\n,\nation,punctuation\nname,surname,age,color,operation,punctuation";
540 static TEST_STRING_OFFSETS: &[usize; 18] = &[
541 4, 5, 13, 14, 18, 24, 29, 30, 31, 32, 33, 39, 51, 56, 64, 68, 74, 84,
542 ];
543
544 #[test]
545 fn test_scalar_searcher() {
546 fn split(haystack: &[u8]) -> Vec<usize> {
547 let searcher = Three::new(b',', b'"', b'\n');
548 searcher.iter(haystack).collect()
549 }
550
551 let offsets = split(TEST_STRING);
552 assert_eq!(offsets, TEST_STRING_OFFSETS);
553
554 // Not found at all
555 assert!(split("b".repeat(75).as_bytes()).is_empty());
556
557 // Regular
558 assert_eq!(split("b,".repeat(75).as_bytes()).len(), 75);
559
560 // Exactly 64
561 assert_eq!(split("b,".repeat(64).as_bytes()).len(), 64);
562
563 // Less than 32
564 assert_eq!(split("b,".repeat(25).as_bytes()).len(), 25);
565
566 // Less than 16
567 assert_eq!(split("b,".repeat(13).as_bytes()).len(), 13);
568 }
569
570 #[test]
571 fn test_searcher() {
572 fn split(haystack: &[u8]) -> Vec<usize> {
573 let searcher = Searcher::new(b',', b'"', b'\n');
574 searcher.search(haystack).collect()
575 }
576
577 let offsets = split(TEST_STRING);
578 assert_eq!(offsets, TEST_STRING_OFFSETS);
579
580 // Not found at all
581 assert!(split("b".repeat(75).as_bytes()).is_empty());
582
583 // Regular
584 assert_eq!(split("b,".repeat(75).as_bytes()).len(), 75);
585
586 // Exactly 64
587 assert_eq!(split("b,".repeat(64).as_bytes()).len(), 64);
588
589 // Less than 32
590 assert_eq!(split("b,".repeat(25).as_bytes()).len(), 25);
591
592 // Less than 16
593 assert_eq!(split("b,".repeat(13).as_bytes()).len(), 13);
594
595 // Complex input
596 let complex = b"name,surname,age\n\"john\",\"landy, the \"\"everlasting\"\" bastard\",45\nlucy,rose,\"67\"\njermaine,jackson,\"89\"\n\nkarine,loucan,\"52\"\nrose,\"glib\",12\n\"guillaume\",\"plique\",\"42\"\r\n";
597 let complex_indices = split(complex);
598
599 assert!(complex_indices
600 .iter()
601 .copied()
602 .all(|c| complex[c] == b',' || complex[c] == b'\n' || complex[c] == b'"'));
603
604 assert_eq!(
605 complex_indices,
606 Three::new(b',', b'\n', b'"')
607 .iter(complex)
608 .collect::<Vec<_>>()
609 );
610 }
611
612 // #[test]
613 // #[cfg(target_arch = "x86_64")]
614 // fn test_process_chunk() {
615 // let searcher = Searcher::new(b',', b'\n', b'"');
616
617 // // Only delimiters
618 // let buffer: &[u8; 16] = b"name,surname,las";
619
620 // let (read, (delimiter_mask, structural_mask)) = searcher.process_chunk(buffer);
621
622 // assert_eq!(read, 16);
623 // assert_eq!(structural_mask.into_first_offset(), None);
624 // assert_eq!(delimiter_mask.into_iter().collect::<Vec<_>>(), vec![4, 12]);
625
626 // // Newline
627 // let buffer: &[u8; 16] = b"name,sur\nname,la";
628
629 // let (read, (delimiter_mask, structural_mask)) = searcher.process_chunk(buffer);
630
631 // assert_eq!(read, 16);
632 // assert_eq!(structural_mask.into_first_offset(), Some(8));
633 // assert_eq!(delimiter_mask.into_iter().collect::<Vec<_>>(), vec![4]);
634
635 // // Quote
636 // let buffer: &[u8; 16] = b"name,sur\"name,la";
637
638 // let (read, (delimiter_mask, structural_mask)) = searcher.process_chunk(buffer);
639
640 // assert_eq!(read, 16);
641 // assert_eq!(structural_mask.into_first_offset(), Some(8));
642 // assert_eq!(delimiter_mask.into_iter().collect::<Vec<_>>(), vec![4]);
643
644 // // Comma in first position
645 // let buffer: &[u8; 16] = b",name,sur\"name,l";
646
647 // let (read, (delimiter_mask, structural_mask)) = searcher.process_chunk(buffer);
648
649 // assert_eq!(read, 16);
650 // assert_eq!(structural_mask.into_first_offset(), Some(9));
651 // assert_eq!(delimiter_mask.into_iter().collect::<Vec<_>>(), vec![0, 5]);
652
653 // // All commas neutralized
654 // let buffer: &[u8; 16] = b"\",ame,sur\"name,l";
655
656 // let (read, (delimiter_mask, structural_mask)) = searcher.process_chunk(buffer);
657
658 // assert_eq!(read, 16);
659 // assert_eq!(structural_mask.into_first_offset(), Some(0));
660 // assert_eq!(
661 // delimiter_mask.into_iter().collect::<Vec<usize>>(),
662 // Vec::<usize>::new()
663 // );
664
665 // // Longer buffers
666 // let buffer = b"name,surname,lasbuthasotherstuffi,nthetailofthebuffer,";
667
668 // let (read, (delimiter_mask, structural_mask)) = searcher.process_chunk(buffer);
669
670 // assert_eq!(read, 16);
671 // assert_eq!(structural_mask.into_first_offset(), None);
672 // assert_eq!(delimiter_mask.into_iter().collect::<Vec<_>>(), vec![4, 12]);
673
674 // // Empty buffer
675 // let buffer = b"";
676
677 // let (read, (delimiter_mask, structural_mask)) = searcher.process_chunk(buffer);
678
679 // assert_eq!(read, 0);
680 // assert_eq!(structural_mask.into_first_offset(), None);
681 // assert_eq!(
682 // delimiter_mask.into_iter().collect::<Vec<_>>(),
683 // Vec::<usize>::new()
684 // );
685
686 // // Tail buffer
687 // let buffer = b"a,b,\nc,";
688
689 // let (read, (delimiter_mask, structural_mask)) = searcher.process_chunk(buffer);
690
691 // assert_eq!(read, 7);
692 // assert_eq!(structural_mask.into_first_offset(), Some(4));
693 // assert_eq!(delimiter_mask.into_iter().collect::<Vec<_>>(), vec![1, 3]);
694 // }
695}