1use std::cmp;
2
3use memchr::memchr2_iter;
4use polars_buffer::Buffer;
5use polars_core::prelude::*;
6use polars_core::runtime::RAYON;
7use polars_error::feature_gated;
8use polars_utils::mmap::MMapSemaphore;
9use polars_utils::pl_path::PlRefPath;
10use polars_utils::select::select_unpredictable;
11use rayon::prelude::*;
12
13use super::CsvParseOptions;
14use super::builder::Builder;
15use super::field_index::{FieldPos, LineIndexer};
16use super::options::{CommentPrefix, NullValuesCompiled};
17use super::splitfields::SplitFields;
18use crate::prelude::CsvReadOptions;
19use crate::prelude::streaming::read_until_start_and_infer_schema;
20use crate::utils::compression::ByteSourceReader;
21use crate::utils::stream_buf_reader::ReaderSource;
22
23#[allow(clippy::too_many_arguments)]
26pub fn count_rows(
27 path: PlRefPath,
28 quote_char: Option<u8>,
29 comment_prefix: Option<&CommentPrefix>,
30 eol_char: u8,
31 has_header: bool,
32 skip_lines: usize,
33 skip_rows_before_header: usize,
34 skip_rows_after_header: usize,
35 raise_if_empty: bool,
36) -> PolarsResult<usize> {
37 let file = if path.has_scheme() || polars_config::config().force_async() {
38 feature_gated!("cloud", {
39 crate::file_cache::FILE_CACHE
40 .get_entry(path)
41 .unwrap()
43 .try_open_assume_latest()?
44 })
45 } else {
46 polars_utils::io::open_file(path.as_std_path())?
47 };
48
49 let mmap = MMapSemaphore::new_from_file(&file).unwrap();
50
51 count_rows_from_slice_par(
52 Buffer::from_owner(mmap),
53 quote_char,
54 comment_prefix,
55 eol_char,
56 has_header,
57 skip_lines,
58 skip_rows_before_header,
59 skip_rows_after_header,
60 raise_if_empty,
61 )
62}
63
64#[allow(clippy::too_many_arguments)]
68pub fn count_rows_from_reader_par(
69 mut reader: ByteSourceReader<ReaderSource>,
70 quote_char: Option<u8>,
71 comment_prefix: Option<&CommentPrefix>,
72 eol_char: u8,
73 has_header: bool,
74 skip_lines: usize,
75 skip_rows_before_header: usize,
76 skip_rows_after_header: usize,
77 raise_if_empty: bool,
78 decompressed_size_hint: Option<usize>,
79) -> PolarsResult<usize> {
80 let reader_options = CsvReadOptions {
81 parse_options: Arc::new(CsvParseOptions {
82 quote_char,
83 comment_prefix: comment_prefix.cloned(),
84 eol_char,
85 ..Default::default()
86 }),
87 has_header,
88 skip_lines,
89 skip_rows: skip_rows_before_header,
90 skip_rows_after_header,
91 raise_if_empty,
92 ..Default::default()
93 };
94
95 let (_, mut leftover) = read_until_start_and_infer_schema(
96 &reader_options,
97 None,
98 true,
99 true,
100 decompressed_size_hint,
101 None,
102 &mut reader,
103 )?;
104
105 const BYTES_PER_CHUNK: usize = if cfg!(debug_assertions) {
106 128
107 } else {
108 512 * 1024
109 };
110
111 let count = CountLines::new(quote_char, eol_char, comment_prefix.cloned());
112 RAYON.install(|| {
113 let mut states = Vec::new();
114
115 let eof_unterminated_row = if comment_prefix.is_none() {
116 let mut last_slice = Buffer::new();
117 let mut err = None;
118
119 let streaming_iter = std::iter::from_fn(|| {
120 let (slice, read_n) =
121 match reader.read_next_slice(&leftover, BYTES_PER_CHUNK, Some(BYTES_PER_CHUNK))
122 {
123 Ok(tup) => tup,
124 Err(e) => {
125 err = Some(e);
126 return None;
127 },
128 };
129
130 leftover = Buffer::new();
131 if slice.is_empty() && read_n == 0 {
132 return None;
133 }
134
135 last_slice = slice.clone();
136 Some(slice)
137 });
138
139 states = streaming_iter
140 .enumerate()
141 .par_bridge()
142 .map(|(id, slice)| (count.analyze_chunk(&slice), id))
143 .collect::<Vec<_>>();
144
145 if let Some(e) = err {
146 return Err(e.into());
147 }
148
149 states.sort_by_key(|(_, id)| *id);
152
153 ends_in_unterminated_row(&last_slice, eol_char, comment_prefix)
156 } else {
157 let (bytes, _) =
160 reader.read_next_slice(&leftover, usize::MAX, decompressed_size_hint)?;
161
162 let num_chunks = bytes.len().div_ceil(BYTES_PER_CHUNK);
163 (0..num_chunks)
164 .into_par_iter()
165 .map(|chunk_idx| {
166 let mut start_offset = chunk_idx * BYTES_PER_CHUNK;
167 let next_start_offset = (start_offset + BYTES_PER_CHUNK).min(bytes.len());
168
169 if start_offset != 0 {
170 if let Some(nl_off) = bytes[start_offset..next_start_offset]
172 .iter()
173 .position(|b| *b == eol_char)
174 {
175 start_offset += nl_off + 1;
176 } else {
177 return (count.analyze_chunk(&[]), 0);
178 }
179 }
180
181 let stop_offset = if let Some(nl_off) = bytes[next_start_offset..]
182 .iter()
183 .position(|b| *b == eol_char)
184 {
185 next_start_offset + nl_off + 1
186 } else {
187 bytes.len()
188 };
189
190 (count.analyze_chunk(&bytes[start_offset..stop_offset]), 0)
191 })
192 .collect_into_vec(&mut states);
193
194 ends_in_unterminated_row(&bytes, eol_char, comment_prefix)
195 };
196
197 let mut n = 0;
198 let mut in_string = false;
199 for (pair, _) in states {
200 n += pair[in_string as usize].newline_count;
201 in_string = pair[in_string as usize].end_inside_string;
202 }
203 n += eof_unterminated_row as usize;
204 Ok(n)
205 })
206}
207
208#[allow(clippy::too_many_arguments)]
212pub fn count_rows_from_slice_par(
213 buffer: Buffer<u8>,
214 quote_char: Option<u8>,
215 comment_prefix: Option<&CommentPrefix>,
216 eol_char: u8,
217 has_header: bool,
218 skip_lines: usize,
219 skip_rows_before_header: usize,
220 skip_rows_after_header: usize,
221 raise_if_empty: bool,
222) -> PolarsResult<usize> {
223 const ASSUMED_COMPRESSION_RATIO: usize = 4;
224
225 let buffer_len = buffer.len();
226 let reader = ByteSourceReader::from_memory(buffer)?;
227 let decompressed_size_hint = Some(
228 buffer_len
229 * reader
230 .compression()
231 .map_or(1, |_| ASSUMED_COMPRESSION_RATIO),
232 );
233
234 count_rows_from_reader_par(
235 reader,
236 quote_char,
237 comment_prefix,
238 eol_char,
239 has_header,
240 skip_lines,
241 skip_rows_before_header,
242 skip_rows_after_header,
243 raise_if_empty,
244 decompressed_size_hint,
245 )
246}
247
248#[inline]
252pub fn is_comment_line(line: &[u8], comment_prefix: Option<&CommentPrefix>) -> bool {
253 match comment_prefix {
254 Some(CommentPrefix::Single(c)) => line.first() == Some(c),
255 Some(CommentPrefix::Multi(s)) => line.starts_with(s.as_bytes()),
256 None => false,
257 }
258}
259
260pub(super) fn next_line_position_naive(input: &[u8], eol_char: u8) -> Option<usize> {
263 let pos = memchr::memchr(eol_char, input)? + 1;
264 if input.len() - pos == 0 {
265 return None;
266 }
267 Some(pos)
268}
269
270pub(super) fn next_line_position(
272 mut input: &[u8],
273 mut expected_fields: Option<usize>,
274 separator: u8,
275 quote_char: Option<u8>,
276 eol_char: u8,
277) -> Option<usize> {
278 fn accept_line(
279 line: &[u8],
280 expected_fields: usize,
281 separator: u8,
282 eol_char: u8,
283 quote_char: Option<u8>,
284 ) -> bool {
285 let mut count = 0usize;
286 for (field, _) in SplitFields::new(line, separator, quote_char, eol_char) {
287 if memchr2_iter(separator, eol_char, field).count() >= expected_fields {
288 return false;
289 }
290 count += 1;
291 }
292
293 expected_fields.wrapping_sub(count) <= 1
303 }
304
305 let mut rejected_line_groups = 0u8;
308
309 let mut total_pos = 0;
310 if input.is_empty() {
311 return None;
312 }
313 let mut lines_checked = 0u8;
314 loop {
315 if rejected_line_groups >= 3 {
316 return None;
317 }
318 lines_checked = lines_checked.wrapping_add(1);
319 if lines_checked == u8::MAX {
323 if let Some(ef) = expected_fields {
324 expected_fields = Some(ef.saturating_sub(1))
325 }
326 };
327 let pos = memchr::memchr(eol_char, input)? + 1;
328 if input.len() - pos == 0 {
329 return None;
330 }
331 debug_assert!(pos <= input.len());
332 let new_input = unsafe { input.get_unchecked(pos..) };
333 let mut lines = SplitLines::new(new_input, quote_char, eol_char, None);
334 let line = lines.next();
335
336 match (line, expected_fields) {
337 (Some(line), Some(expected_fields)) => {
339 if accept_line(line, expected_fields, separator, eol_char, quote_char) {
340 let mut valid = true;
341 for line in lines.take(2) {
342 if !accept_line(line, expected_fields, separator, eol_char, quote_char) {
343 valid = false;
344 break;
345 }
346 }
347 if valid {
348 return Some(total_pos + pos);
349 } else {
350 rejected_line_groups += 1;
351 }
352 } else {
353 debug_assert!(pos < input.len());
354 unsafe {
355 input = input.get_unchecked(pos + 1..);
356 }
357 total_pos += pos + 1;
358 }
359 },
360 (Some(_), None) => return Some(total_pos + pos),
362 _ => return None,
364 }
365 }
366}
367
368#[inline(always)]
369pub(super) fn is_whitespace(b: u8) -> bool {
370 b == b' ' || b == b'\t'
371}
372
373#[inline(always)]
375pub(super) fn could_be_whitespace_fast(b: u8) -> bool {
376 b <= 32
381}
382
383#[inline]
384fn skip_condition<F>(input: &[u8], f: F) -> &[u8]
385where
386 F: Fn(u8) -> bool,
387{
388 if input.is_empty() {
389 return input;
390 }
391
392 let read = input.iter().position(|b| !f(*b)).unwrap_or(input.len());
393 &input[read..]
394}
395
396#[inline]
402pub(super) fn skip_whitespace(input: &[u8]) -> &[u8] {
403 skip_condition(input, is_whitespace)
404}
405
406pub struct SplitLines<'a> {
416 v: &'a [u8],
417 quote_char: u8,
418 eol_char: u8,
419 #[cfg(feature = "simd")]
420 simd_eol_char: SimdVec,
421 #[cfg(feature = "simd")]
422 simd_quote_char: SimdVec,
423 #[cfg(feature = "simd")]
424 previous_valid_eols: u64,
425 total_index: usize,
426 quoting: bool,
427 comment_prefix: Option<&'a CommentPrefix>,
428}
429
430#[cfg(feature = "simd")]
431const SIMD_SIZE: usize = 64;
432#[cfg(feature = "simd")]
433use std::simd::prelude::*;
434
435#[cfg(feature = "simd")]
436use polars_utils::clmul::prefix_xorsum_inclusive;
437
438#[cfg(feature = "simd")]
439type SimdVec = u8x64;
440
441impl<'a> SplitLines<'a> {
442 pub fn new(
443 slice: &'a [u8],
444 quote_char: Option<u8>,
445 eol_char: u8,
446 comment_prefix: Option<&'a CommentPrefix>,
447 ) -> Self {
448 let quoting = quote_char.is_some();
449 let quote_char = quote_char.unwrap_or(b'\"');
450 #[cfg(feature = "simd")]
451 let simd_eol_char = SimdVec::splat(eol_char);
452 #[cfg(feature = "simd")]
453 let simd_quote_char = SimdVec::splat(quote_char);
454 Self {
455 v: slice,
456 quote_char,
457 eol_char,
458 #[cfg(feature = "simd")]
459 simd_eol_char,
460 #[cfg(feature = "simd")]
461 simd_quote_char,
462 #[cfg(feature = "simd")]
463 previous_valid_eols: 0,
464 total_index: 0,
465 quoting,
466 comment_prefix,
467 }
468 }
469}
470
471impl<'a> SplitLines<'a> {
472 fn next_scalar(&mut self) -> Option<&'a [u8]> {
474 if self.v.is_empty() {
475 return None;
476 }
477 if is_comment_line(self.v, self.comment_prefix) {
478 return self.next_comment_line();
479 }
480 {
481 let mut pos = 0u32;
482 let mut iter = self.v.iter();
483 let mut in_field = false;
484 loop {
485 match iter.next() {
486 Some(&c) => {
487 pos += 1;
488
489 if self.quoting && c == self.quote_char {
490 in_field = !in_field;
494 }
495 else if c == self.eol_char && !in_field {
497 break;
498 }
499 },
500 None => {
501 let remainder = self.v;
502 self.v = &[];
503 return Some(remainder);
504 },
505 }
506 }
507
508 unsafe {
509 debug_assert!((pos as usize) <= self.v.len());
510
511 let ret = Some(
513 self.v
514 .get_unchecked(..(self.total_index + pos as usize - 1)),
515 );
516 self.v = self.v.get_unchecked(self.total_index + pos as usize..);
518 ret
519 }
520 }
521 }
522 fn next_comment_line(&mut self) -> Option<&'a [u8]> {
523 if let Some(pos) = next_line_position_naive(self.v, self.eol_char) {
524 unsafe {
525 let ret = Some(self.v.get_unchecked(..(pos - 1)));
527 self.v = self.v.get_unchecked(pos..);
529 ret
530 }
531 } else {
532 let remainder = self.v;
533 self.v = &[];
534 Some(remainder)
535 }
536 }
537}
538
539impl<'a> Iterator for SplitLines<'a> {
540 type Item = &'a [u8];
541
542 #[inline]
543 #[cfg(not(feature = "simd"))]
544 fn next(&mut self) -> Option<&'a [u8]> {
545 self.next_scalar()
546 }
547
548 #[inline]
549 #[cfg(feature = "simd")]
550 fn next(&mut self) -> Option<&'a [u8]> {
551 if self.previous_valid_eols != 0 {
553 let pos = self.previous_valid_eols.trailing_zeros() as usize;
554 self.previous_valid_eols >>= (pos + 1) as u64;
555
556 unsafe {
557 debug_assert!((pos) <= self.v.len());
558
559 let ret = Some(self.v.get_unchecked(..pos));
561 self.v = self.v.get_unchecked(pos + 1..);
563 return ret;
564 }
565 }
566 if self.v.is_empty() {
567 return None;
568 }
569 if self.comment_prefix.is_some() {
570 return self.next_scalar();
571 }
572
573 self.total_index = 0;
574 let mut not_in_field_previous_iter = true;
575
576 loop {
577 let bytes = unsafe { self.v.get_unchecked(self.total_index..) };
578 if bytes.len() > SIMD_SIZE {
579 let lane: [u8; SIMD_SIZE] = unsafe {
580 bytes
581 .get_unchecked(0..SIMD_SIZE)
582 .try_into()
583 .unwrap_unchecked()
584 };
585 let simd_bytes = SimdVec::from(lane);
586 let eol_mask = simd_bytes.simd_eq(self.simd_eol_char).to_bitmask();
587
588 let valid_eols = if self.quoting {
589 let quote_mask = simd_bytes.simd_eq(self.simd_quote_char).to_bitmask();
590 let mut not_in_quote_field = prefix_xorsum_inclusive(quote_mask);
591
592 if not_in_field_previous_iter {
593 not_in_quote_field = !not_in_quote_field;
594 }
595 not_in_field_previous_iter = (not_in_quote_field & (1 << (SIMD_SIZE - 1))) > 0;
596 eol_mask & not_in_quote_field
597 } else {
598 eol_mask
599 };
600
601 if valid_eols != 0 {
602 let pos = valid_eols.trailing_zeros() as usize;
603 if pos == SIMD_SIZE - 1 {
604 self.previous_valid_eols = 0;
605 } else {
606 self.previous_valid_eols = valid_eols >> (pos + 1) as u64;
607 }
608
609 unsafe {
610 let pos = self.total_index + pos;
611 debug_assert!((pos) <= self.v.len());
612
613 let ret = Some(self.v.get_unchecked(..pos));
615 self.v = self.v.get_unchecked(pos + 1..);
617 return ret;
618 }
619 } else {
620 self.total_index += SIMD_SIZE;
621 }
622 } else {
623 let mut in_field = !not_in_field_previous_iter;
625 let mut pos = 0u32;
626 let mut iter = bytes.iter();
627 loop {
628 match iter.next() {
629 Some(&c) => {
630 pos += 1;
631
632 if self.quoting && c == self.quote_char {
633 in_field = !in_field;
637 }
638 else if c == self.eol_char && !in_field {
640 break;
641 }
642 },
643 None => {
644 let remainder = self.v;
645 self.v = &[];
646 return Some(remainder);
647 },
648 }
649 }
650
651 unsafe {
652 debug_assert!((pos as usize) <= self.v.len());
653
654 let ret = Some(
656 self.v
657 .get_unchecked(..(self.total_index + pos as usize - 1)),
658 );
659 self.v = self.v.get_unchecked(self.total_index + pos as usize..);
661 return ret;
662 }
663 }
664 }
665 }
666}
667
668#[derive(Clone)]
669pub struct CountLines {
670 quote_char: u8,
671 eol_char: u8,
672 #[cfg(feature = "simd")]
673 simd_eol_char: SimdVec,
674 #[cfg(feature = "simd")]
675 simd_quote_char: SimdVec,
676 quoting: bool,
677 comment_prefix: Option<CommentPrefix>,
678}
679
680#[derive(Copy, Clone, Debug, Default)]
681pub struct LineStats {
682 pub newline_count: usize,
683 pub last_newline_offset: usize,
684 pub end_inside_string: bool,
685}
686
687impl CountLines {
688 pub fn new(
689 quote_char: Option<u8>,
690 eol_char: u8,
691 comment_prefix: Option<CommentPrefix>,
692 ) -> Self {
693 let quoting = quote_char.is_some();
694 let quote_char = quote_char.unwrap_or(b'\"');
695 #[cfg(feature = "simd")]
696 let simd_eol_char = SimdVec::splat(eol_char);
697 #[cfg(feature = "simd")]
698 let simd_quote_char = SimdVec::splat(quote_char);
699 Self {
700 quote_char,
701 eol_char,
702 #[cfg(feature = "simd")]
703 simd_eol_char,
704 #[cfg(feature = "simd")]
705 simd_quote_char,
706 quoting,
707 comment_prefix,
708 }
709 }
710
711 pub fn has_comment_prefix(&self) -> bool {
712 self.comment_prefix.is_some()
713 }
714
715 pub fn analyze_chunk(&self, bytes: &[u8]) -> [LineStats; 2] {
724 let mut states = [
725 LineStats {
726 newline_count: 0,
727 last_newline_offset: 0,
728 end_inside_string: false,
729 },
730 LineStats {
731 newline_count: 0,
732 last_newline_offset: 0,
733 end_inside_string: false,
734 },
735 ];
736
737 if self.comment_prefix.is_some() {
739 states[0] = self.analyze_chunk_with_comment(bytes, false);
740 states[1] = self.analyze_chunk_with_comment(bytes, true);
741 return states;
742 }
743
744 #[allow(unused_assignments)]
746 let mut global_quote_parity = false;
747 let mut scan_offset = 0;
748
749 #[cfg(feature = "simd")]
750 {
751 let mut global_quote_parity_mask = 0;
753 while scan_offset + 64 <= bytes.len() {
754 let block: [u8; 64] = unsafe {
755 bytes
756 .get_unchecked(scan_offset..scan_offset + 64)
757 .try_into()
758 .unwrap_unchecked()
759 };
760 let simd_bytes = SimdVec::from(block);
761 let eol_mask = simd_bytes.simd_eq(self.simd_eol_char).to_bitmask();
762 if self.quoting {
763 let quote_mask = simd_bytes.simd_eq(self.simd_quote_char).to_bitmask();
764 let quote_parity =
765 prefix_xorsum_inclusive(quote_mask) ^ global_quote_parity_mask;
766 global_quote_parity_mask = ((quote_parity as i64) >> 63) as u64;
767
768 let start_outside_string_eol_mask = eol_mask & !quote_parity;
769 states[0].newline_count += start_outside_string_eol_mask.count_ones() as usize;
770 states[0].last_newline_offset = select_unpredictable(
771 start_outside_string_eol_mask != 0,
772 (scan_offset + 63)
773 .wrapping_sub(start_outside_string_eol_mask.leading_zeros() as usize),
774 states[0].last_newline_offset,
775 );
776
777 let start_inside_string_eol_mask = eol_mask & quote_parity;
778 states[1].newline_count += start_inside_string_eol_mask.count_ones() as usize;
779 states[1].last_newline_offset = select_unpredictable(
780 start_inside_string_eol_mask != 0,
781 (scan_offset + 63)
782 .wrapping_sub(start_inside_string_eol_mask.leading_zeros() as usize),
783 states[1].last_newline_offset,
784 );
785 } else {
786 states[0].newline_count += eol_mask.count_ones() as usize;
787 states[0].last_newline_offset = select_unpredictable(
788 eol_mask != 0,
789 (scan_offset + 63).wrapping_sub(eol_mask.leading_zeros() as usize),
790 states[0].last_newline_offset,
791 );
792 }
793
794 scan_offset += 64;
795 }
796
797 global_quote_parity = global_quote_parity_mask > 0;
798 }
799
800 while scan_offset < bytes.len() {
801 let c = unsafe { *bytes.get_unchecked(scan_offset) };
802 global_quote_parity ^= (c == self.quote_char) & self.quoting;
803
804 let state = &mut states[global_quote_parity as usize];
805 state.newline_count += (c == self.eol_char) as usize;
806 state.last_newline_offset =
807 select_unpredictable(c == self.eol_char, scan_offset, state.last_newline_offset);
808
809 scan_offset += 1;
810 }
811
812 states[0].end_inside_string = global_quote_parity;
813 states[1].end_inside_string = !global_quote_parity;
814 states
815 }
816
817 fn analyze_chunk_with_comment(&self, bytes: &[u8], mut in_string: bool) -> LineStats {
819 let pre_s = match self.comment_prefix.as_ref().unwrap() {
820 CommentPrefix::Single(pc) => core::slice::from_ref(pc),
821 CommentPrefix::Multi(ps) => ps.as_bytes(),
822 };
823
824 let mut state = LineStats::default();
825 let mut scan_offset = 0;
826 while scan_offset < bytes.len() {
827 while bytes[scan_offset..].starts_with(pre_s) {
829 scan_offset += pre_s.len();
830 let Some(nl_off) = bytes[scan_offset..]
831 .iter()
832 .position(|c| *c == self.eol_char)
833 else {
834 break;
835 };
836 scan_offset += nl_off + 1;
837 }
838
839 while scan_offset < bytes.len() {
840 let c = unsafe { *bytes.get_unchecked(scan_offset) };
841 in_string ^= (c == self.quote_char) & self.quoting;
842
843 if c == self.eol_char && !in_string {
844 state.newline_count += 1;
845 state.last_newline_offset = scan_offset;
846 scan_offset += 1;
847 break;
848 } else {
849 scan_offset += 1;
850 }
851 }
852 }
853
854 state.end_inside_string = in_string;
855 state
856 }
857
858 pub fn find_next(&self, bytes: &[u8], chunk_size: &mut usize) -> (usize, usize) {
859 loop {
860 let b = unsafe { bytes.get_unchecked(..(*chunk_size).min(bytes.len())) };
861
862 let (count, offset) = if self.comment_prefix.is_some() {
863 let stats = self.analyze_chunk_with_comment(b, false);
864 (stats.newline_count, stats.last_newline_offset)
865 } else {
866 self.count(b)
867 };
868
869 if count > 0 || b.len() == bytes.len() {
870 return (count, offset);
871 }
872
873 *chunk_size = chunk_size.saturating_mul(2);
874 }
875 }
876
877 pub fn count_rows(&self, bytes: &[u8], is_eof: bool) -> (usize, usize) {
878 let stats = if self.comment_prefix.is_some() {
879 self.analyze_chunk_with_comment(bytes, false)
880 } else {
881 self.analyze_chunk(bytes)[0]
882 };
883
884 let mut count = stats.newline_count;
885 let mut offset = stats.last_newline_offset;
886
887 if count > 0 {
888 offset = cmp::min(offset + 1, bytes.len());
889 } else {
890 debug_assert!(offset == 0);
891 }
892
893 if is_eof {
894 count += ends_in_unterminated_row(bytes, self.eol_char, self.comment_prefix.as_ref())
895 as usize;
896 offset = bytes.len();
897 }
898
899 (count, offset)
900 }
901
902 #[cfg(feature = "simd")]
904 pub fn count(&self, bytes: &[u8]) -> (usize, usize) {
905 let mut total_idx = 0;
906 let original_bytes = bytes;
907 let mut count = 0;
908 let mut position = 0;
909 let mut not_in_field_previous_iter = true;
910
911 loop {
912 let bytes = unsafe { original_bytes.get_unchecked(total_idx..) };
913
914 if bytes.len() > SIMD_SIZE {
915 let lane: [u8; SIMD_SIZE] = unsafe {
916 bytes
917 .get_unchecked(0..SIMD_SIZE)
918 .try_into()
919 .unwrap_unchecked()
920 };
921 let simd_bytes = SimdVec::from(lane);
922 let eol_mask = simd_bytes.simd_eq(self.simd_eol_char).to_bitmask();
923
924 let valid_eols = if self.quoting {
925 let quote_mask = simd_bytes.simd_eq(self.simd_quote_char).to_bitmask();
926 let mut not_in_quote_field = prefix_xorsum_inclusive(quote_mask);
927
928 if not_in_field_previous_iter {
929 not_in_quote_field = !not_in_quote_field;
930 }
931 not_in_field_previous_iter = (not_in_quote_field & (1 << (SIMD_SIZE - 1))) > 0;
932 eol_mask & not_in_quote_field
933 } else {
934 eol_mask
935 };
936
937 if valid_eols != 0 {
938 count += valid_eols.count_ones() as usize;
939 position = total_idx + 63 - valid_eols.leading_zeros() as usize;
940 debug_assert_eq!(original_bytes[position], self.eol_char)
941 }
942 total_idx += SIMD_SIZE;
943 } else if bytes.is_empty() {
944 debug_assert!(count == 0 || original_bytes[position] == self.eol_char);
945 return (count, position);
946 } else {
947 let (c, o) = self.count_no_simd(bytes, !not_in_field_previous_iter);
948
949 let (count, position) = if c > 0 {
950 (count + c, total_idx + o)
951 } else {
952 (count, position)
953 };
954 debug_assert!(count == 0 || original_bytes[position] == self.eol_char);
955
956 return (count, position);
957 }
958 }
959 }
960
961 #[cfg(not(feature = "simd"))]
962 pub fn count(&self, bytes: &[u8]) -> (usize, usize) {
963 self.count_no_simd(bytes, false)
964 }
965
966 fn count_no_simd(&self, bytes: &[u8], in_field: bool) -> (usize, usize) {
967 let iter = bytes.iter();
968 let mut in_field = in_field;
969 let mut count = 0;
970 let mut position = 0;
971
972 for b in iter {
973 let c = *b;
974 if self.quoting && c == self.quote_char {
975 in_field = !in_field;
979 }
980 else if c == self.eol_char && !in_field {
982 position = (b as *const _ as usize) - (bytes.as_ptr() as usize);
983 count += 1;
984 }
985 }
986 debug_assert!(count == 0 || bytes[position] == self.eol_char);
987
988 (count, position)
989 }
990}
991
992pub fn complete_rows_len(
997 bytes: &[u8],
998 quote_char: Option<u8>,
999 comment_prefix: Option<&CommentPrefix>,
1000 eol_char: u8,
1001 skip_lines: usize,
1002) -> usize {
1003 let mut start = 0;
1004 for _ in 0..skip_lines {
1005 match memchr::memchr(eol_char, &bytes[start..]) {
1006 Some(pos) => start += pos + 1,
1007 None => return start,
1008 }
1009 }
1010
1011 const UTF8_BOM_MARKER: &[u8] = b"\xef\xbb\xbf";
1012 if bytes[start..].starts_with(UTF8_BOM_MARKER) {
1013 start += UTF8_BOM_MARKER.len();
1014 }
1015
1016 let count = CountLines::new(quote_char, eol_char, comment_prefix.cloned());
1017 let (_, offset) = count.count_rows(&bytes[start..], false);
1018 start + offset
1019}
1020
1021fn ends_in_unterminated_row(
1022 bytes: &[u8],
1023 eol_char: u8,
1024 comment_prefix: Option<&CommentPrefix>,
1025) -> bool {
1026 if !bytes.is_empty() && bytes.last().copied().unwrap() != eol_char {
1027 let last_new_line_pos = memchr::memrchr(eol_char, bytes).unwrap_or(0);
1030 let last_line_is_comment_line = bytes
1031 .get(last_new_line_pos + 1..)
1032 .map(|line| is_comment_line(line, comment_prefix))
1033 .unwrap_or(false);
1034
1035 return !last_line_is_comment_line;
1036 }
1037
1038 false
1039}
1040
1041#[inline]
1042fn find_quoted(bytes: &[u8], quote_char: u8, needle: u8) -> Option<usize> {
1043 let mut in_field = false;
1044
1045 let mut idx = 0u32;
1046 #[allow(clippy::explicit_counter_loop)]
1048 for &c in bytes.iter() {
1049 if c == quote_char {
1050 in_field = !in_field;
1054 }
1055
1056 if !in_field && c == needle {
1057 return Some(idx as usize);
1058 }
1059 idx += 1;
1060 }
1061 None
1062}
1063
1064#[inline]
1065pub(super) fn skip_this_line(bytes: &[u8], quote: Option<u8>, eol_char: u8) -> &[u8] {
1066 let pos = match quote {
1067 Some(quote) => find_quoted(bytes, quote, eol_char),
1068 None => bytes.iter().position(|x| *x == eol_char),
1069 };
1070 match pos {
1071 None => &[],
1072 Some(pos) => &bytes[pos + 1..],
1073 }
1074}
1075
1076#[inline]
1077pub(super) fn skip_this_line_naive(input: &[u8], eol_char: u8) -> &[u8] {
1078 if let Some(pos) = next_line_position_naive(input, eol_char) {
1079 unsafe { input.get_unchecked(pos..) }
1080 } else {
1081 &[]
1082 }
1083}
1084
1085#[allow(clippy::too_many_arguments)]
1091unsafe fn add_column(
1092 buf: &mut Builder,
1093 column_idx: usize,
1094 batch: &[u8],
1095 column: impl Iterator<Item = FieldPos>,
1096 quote_char: Option<u8>,
1097 null_values: Option<&NullValuesCompiled>,
1098 ignore_errors: bool,
1099 missing_is_null: bool,
1100) -> Result<(), (usize, PolarsError)> {
1101 let column = column.map(|pos| {
1102 unsafe { pos.get(batch) }
1103 .map(|field| (field, quote_char.is_some_and(|q| field.first() == Some(&q))))
1104 });
1105 unsafe {
1106 buf.add_column(
1107 column,
1108 column_idx,
1109 null_values,
1110 ignore_errors,
1111 missing_is_null,
1112 )
1113 }
1114}
1115
1116const BATCH_BYTES: usize = 16 * 1024;
1119const BATCH_FIELDS: usize = 2 * 1024;
1121
1122#[allow(clippy::too_many_arguments)]
1134pub(super) fn parse_lines(
1135 mut bytes: &[u8],
1136 parse_options: &CsvParseOptions,
1137 offset: usize,
1138 ignore_errors: bool,
1139 null_values: Option<&NullValuesCompiled>,
1140 projection: &[usize],
1141 buffers: &mut [Builder],
1142 n_lines: usize,
1143 schema_len: usize,
1145 schema: &Schema,
1146) -> PolarsResult<usize> {
1147 assert!(
1148 !projection.is_empty(),
1149 "at least one column should be projected"
1150 );
1151 let mut truncate_ragged_lines = parse_options.truncate_ragged_lines;
1152 if projection.len() != schema_len {
1156 truncate_ragged_lines = true
1157 }
1158
1159 let start = bytes.as_ptr() as usize;
1161 let original_bytes_len = bytes.len();
1162 let n_lines = n_lines as u32;
1163
1164 let parse_error = |buf: &Builder, field: &[u8], column_idx: usize, e: PolarsError| {
1165 let bytes_offset = offset + field.as_ptr() as usize - start;
1166 let unparsable = String::from_utf8_lossy(field);
1167 let column_name = schema.get_at_index(column_idx).unwrap().0;
1168 polars_err!(
1169 ComputeError:
1170 "could not parse `{}` as dtype `{}` at column '{}' (column number {})\n\n\
1171 The current offset in the file is {} bytes.\n\
1172 \n\
1173 You might want to try:\n\
1174 - increasing `infer_schema_length` (e.g. `infer_schema_length=10000`),\n\
1175 - increasing `infer_schema_files` (e.g. `infer_schema_files=50`),\n\
1176 - specifying correct dtype with the `schema_overrides` argument\n\
1177 - setting `ignore_errors` to `True`,\n\
1178 - adding `{}` to the `null_values` list.\n\n\
1179 Original error: ```{}```",
1180 &unparsable,
1181 buf.dtype(),
1182 column_name,
1183 column_idx + 1,
1184 bytes_offset,
1185 &unparsable,
1186 e
1187 )
1188 };
1189
1190 let n_fields = projection.len();
1191 let quote_char = parse_options.quote_char;
1192 let by_row = buffers.iter().filter(|buf| buf.is_categorical()).count() > 1;
1194 macro_rules! add_column {
1195 ($buf:expr, $column_idx:expr, $batch:expr, $column:expr) => {
1196 unsafe {
1199 add_column(
1200 $buf,
1201 $column_idx,
1202 $batch,
1203 $column,
1204 quote_char,
1205 null_values,
1206 ignore_errors,
1207 parse_options.missing_is_null,
1208 )
1209 }
1210 };
1211 }
1212 fn field_at<'a>(
1213 batch: &'a [u8],
1214 fields: &[FieldPos],
1215 n_fields: usize,
1216 row: usize,
1217 i: usize,
1218 ) -> &'a [u8] {
1219 unsafe { fields[row * n_fields + i].get(batch).unwrap_unchecked() }
1221 }
1222
1223 let flush = |batch: &[u8], fields: &mut Vec<FieldPos>, buffers: &mut [Builder]| {
1225 if by_row {
1226 for row in 0..fields.len() / n_fields {
1227 for i in 0..n_fields {
1228 let column = std::iter::once(fields[row * n_fields + i]);
1229 add_column!(&mut buffers[i], projection[i], batch, column).map_err(
1230 |(_, e)| {
1231 parse_error(
1232 &buffers[i],
1233 field_at(batch, fields, n_fields, row, i),
1234 projection[i],
1235 e,
1236 )
1237 },
1238 )?;
1239 }
1240 }
1241 } else {
1242 for i in 0..n_fields {
1243 let column = fields.iter().skip(i).step_by(n_fields).copied();
1244 add_column!(&mut buffers[i], projection[i], batch, column).map_err(
1245 |(row, e)| {
1246 let (row, i, e) = (0..row)
1248 .find_map(|row| {
1249 (i + 1..n_fields).find_map(|j| {
1250 let column = std::iter::once(fields[row * n_fields + j]);
1251 add_column!(&mut buffers[j], projection[j], batch, column)
1252 .err()
1253 .map(|(_, e)| (row, j, e))
1254 })
1255 })
1256 .unwrap_or((row, i, e));
1257 parse_error(
1258 &buffers[i],
1259 field_at(batch, fields, n_fields, row, i),
1260 projection[i],
1261 e,
1262 )
1263 },
1264 )?;
1265 }
1266 }
1267 fields.clear();
1268 PolarsResult::Ok(())
1269 };
1270
1271 let mut fields: Vec<FieldPos> = Vec::with_capacity(BATCH_FIELDS + projection.len());
1272 let mut batch = bytes;
1273
1274 let use_indexer = parse_options.comment_prefix.is_none()
1277 && parse_options.quote_char != Some(parse_options.separator);
1278 let indexer = use_indexer.then(|| LineIndexer {
1279 separator: parse_options.separator,
1280 eol_char: parse_options.eol_char,
1281 quote_char: parse_options.quote_char.unwrap_or(b'"'),
1282 quoting: parse_options.quote_char.is_some(),
1283 projection,
1284 schema_len,
1285 truncate_ragged_lines,
1286 });
1287
1288 let mut iter = SplitFields::new(
1289 bytes,
1290 parse_options.separator,
1291 parse_options.quote_char,
1292 parse_options.eol_char,
1293 );
1294 let mut line_count = 0u32;
1295 let read = 'lines: loop {
1296 if line_count > n_lines {
1297 break bytes.as_ptr() as usize - start;
1298 }
1299
1300 if bytes.is_empty() {
1301 break original_bytes_len;
1302 } else if is_comment_line(bytes, parse_options.comment_prefix.as_ref()) {
1303 let bytes_rem = skip_this_line_naive(bytes, parse_options.eol_char);
1305 bytes = bytes_rem;
1306 continue;
1307 }
1308
1309 let batch_len = bytes.as_ptr() as usize - batch.as_ptr() as usize;
1310 if batch_len >= BATCH_BYTES || fields.len() >= BATCH_FIELDS {
1311 flush(batch, &mut fields, buffers)?;
1312 batch = bytes;
1313 }
1314 let line_start = bytes.as_ptr() as usize - batch.as_ptr() as usize;
1315
1316 if let Some(indexer) = &indexer {
1317 let (n_bytes, n) = indexer.index_lines(
1318 bytes,
1319 line_start,
1320 &mut fields,
1321 (n_lines - line_count).saturating_add(1),
1322 BATCH_BYTES,
1323 BATCH_FIELDS,
1324 );
1325 if n > 0 {
1326 bytes = &bytes[n_bytes..];
1327 line_count += n;
1328 continue;
1329 }
1330 }
1331
1332 let mut projection_iter = projection.iter().copied();
1336 let mut next_projected = unsafe { projection_iter.next().unwrap_unchecked() };
1337 let mut processed_fields = 0;
1338
1339 iter.next_line(bytes);
1340 let mut idx = 0u32;
1341 let mut read_sol = 0;
1342 loop {
1343 match iter.next() {
1344 None => {
1346 bytes = unsafe { bytes.get_unchecked(std::cmp::min(read_sol, bytes.len())..) };
1347 break;
1348 },
1349 Some((mut field, _)) => {
1350 let field_len = field.len();
1351 let field_start = line_start + read_sol;
1352
1353 read_sol += field_len + 1;
1355
1356 if idx == next_projected as u32 {
1357 unsafe {
1360 if field_len > 0 && *field.get_unchecked(field_len - 1) == b'\r' {
1361 field = field.get_unchecked(..field_len - 1);
1362 }
1363 }
1364
1365 let Some(pos) = FieldPos::new(field_start, field.len()) else {
1366 if line_start == 0 {
1367 let n_missing = projection.len() - processed_fields;
1369 fields.extend(std::iter::repeat_n(FieldPos::MISSING, n_missing));
1370 flush(batch, &mut fields, buffers)?;
1371 polars_bail!(ComputeError: "CSV line is too long");
1372 }
1373 fields.truncate(fields.len() - processed_fields);
1374 flush(batch, &mut fields, buffers)?;
1375 batch = bytes;
1376 continue 'lines;
1377 };
1378 fields.push(pos);
1379 processed_fields += 1;
1380
1381 match projection_iter.next() {
1383 Some(p) => next_projected = p,
1384 None => {
1385 if bytes.get(read_sol - 1) == Some(&parse_options.eol_char) {
1386 bytes = unsafe { bytes.get_unchecked(read_sol..) };
1387 } else {
1388 if !truncate_ragged_lines && read_sol < bytes.len() {
1389 flush(batch, &mut fields, buffers)?;
1391 polars_bail!(ComputeError: r#"found more fields than defined in 'Schema'
1392
1393Consider setting 'truncate_ragged_lines={}'."#, polars_error::constants::TRUE)
1394 }
1395 let bytes_rem = skip_this_line(
1396 unsafe { bytes.get_unchecked(read_sol - 1..) },
1397 parse_options.quote_char,
1398 parse_options.eol_char,
1399 );
1400 bytes = bytes_rem;
1401 }
1402 break;
1403 },
1404 }
1405 }
1406 idx += 1;
1407 },
1408 }
1409 }
1410
1411 for _ in processed_fields..projection.len() {
1415 fields.push(FieldPos::MISSING);
1416 }
1417 line_count += 1;
1418 };
1419 flush(batch, &mut fields, buffers)?;
1420 Ok(read)
1421}
1422
1423#[cfg(test)]
1424mod test {
1425 use super::SplitLines;
1426
1427 #[test]
1428 fn test_splitlines() {
1429 let input = "1,\"foo\n\"\n2,\"foo\n\"\n";
1430 let mut lines = SplitLines::new(input.as_bytes(), Some(b'"'), b'\n', None);
1431 assert_eq!(lines.next(), Some("1,\"foo\n\"".as_bytes()));
1432 assert_eq!(lines.next(), Some("2,\"foo\n\"".as_bytes()));
1433 assert_eq!(lines.next(), None);
1434
1435 let input2 = "1,'foo\n'\n2,'foo\n'\n";
1436 let mut lines2 = SplitLines::new(input2.as_bytes(), Some(b'\''), b'\n', None);
1437 assert_eq!(lines2.next(), Some("1,'foo\n'".as_bytes()));
1438 assert_eq!(lines2.next(), Some("2,'foo\n'".as_bytes()));
1439 assert_eq!(lines2.next(), None);
1440 }
1441}