Skip to main content

polars_io/csv/read/
parser.rs

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::options::{CommentPrefix, NullValuesCompiled};
16use super::splitfields::SplitFields;
17use crate::prelude::CsvReadOptions;
18use crate::prelude::streaming::read_until_start_and_infer_schema;
19use crate::utils::compression::ByteSourceReader;
20use crate::utils::stream_buf_reader::ReaderSource;
21
22/// Read the number of rows without parsing columns
23/// useful for count(*) queries
24#[allow(clippy::too_many_arguments)]
25pub fn count_rows(
26    path: PlRefPath,
27    quote_char: Option<u8>,
28    comment_prefix: Option<&CommentPrefix>,
29    eol_char: u8,
30    has_header: bool,
31    skip_lines: usize,
32    skip_rows_before_header: usize,
33    skip_rows_after_header: usize,
34    raise_if_empty: bool,
35) -> PolarsResult<usize> {
36    let file = if path.has_scheme() || polars_config::config().force_async() {
37        feature_gated!("cloud", {
38            crate::file_cache::FILE_CACHE
39                .get_entry(path)
40                // Safety: This was initialized by schema inference.
41                .unwrap()
42                .try_open_assume_latest()?
43        })
44    } else {
45        polars_utils::io::open_file(path.as_std_path())?
46    };
47
48    let mmap = MMapSemaphore::new_from_file(&file).unwrap();
49
50    count_rows_from_slice_par(
51        Buffer::from_owner(mmap),
52        quote_char,
53        comment_prefix,
54        eol_char,
55        has_header,
56        skip_lines,
57        skip_rows_before_header,
58        skip_rows_after_header,
59        raise_if_empty,
60    )
61}
62
63/// Read the number of rows without parsing columns.
64/// Useful for count(*) queries.
65/// Supports transparent decompression. Does not support truncated compressed files.
66#[allow(clippy::too_many_arguments)]
67pub fn count_rows_from_reader_par(
68    mut reader: ByteSourceReader<ReaderSource>,
69    quote_char: Option<u8>,
70    comment_prefix: Option<&CommentPrefix>,
71    eol_char: u8,
72    has_header: bool,
73    skip_lines: usize,
74    skip_rows_before_header: usize,
75    skip_rows_after_header: usize,
76    raise_if_empty: bool,
77    decompressed_size_hint: Option<usize>,
78) -> PolarsResult<usize> {
79    let reader_options = CsvReadOptions {
80        parse_options: Arc::new(CsvParseOptions {
81            quote_char,
82            comment_prefix: comment_prefix.cloned(),
83            eol_char,
84            ..Default::default()
85        }),
86        has_header,
87        skip_lines,
88        skip_rows: skip_rows_before_header,
89        skip_rows_after_header,
90        raise_if_empty,
91        ..Default::default()
92    };
93
94    let (_, mut leftover) = read_until_start_and_infer_schema(
95        &reader_options,
96        None,
97        true,
98        true,
99        decompressed_size_hint,
100        None,
101        &mut reader,
102    )?;
103
104    const BYTES_PER_CHUNK: usize = if cfg!(debug_assertions) {
105        128
106    } else {
107        512 * 1024
108    };
109
110    let count = CountLines::new(quote_char, eol_char, comment_prefix.cloned());
111    RAYON.install(|| {
112        let mut states = Vec::new();
113
114        let eof_unterminated_row = if comment_prefix.is_none() {
115            let mut last_slice = Buffer::new();
116            let mut err = None;
117
118            let streaming_iter = std::iter::from_fn(|| {
119                let (slice, read_n) =
120                    match reader.read_next_slice(&leftover, BYTES_PER_CHUNK, Some(BYTES_PER_CHUNK))
121                    {
122                        Ok(tup) => tup,
123                        Err(e) => {
124                            err = Some(e);
125                            return None;
126                        },
127                    };
128
129                leftover = Buffer::new();
130                if slice.is_empty() && read_n == 0 {
131                    return None;
132                }
133
134                last_slice = slice.clone();
135                Some(slice)
136            });
137
138            states = streaming_iter
139                .enumerate()
140                .par_bridge()
141                .map(|(id, slice)| (count.analyze_chunk(&slice), id))
142                .collect::<Vec<_>>();
143
144            if let Some(e) = err {
145                return Err(e.into());
146            }
147
148            // par_bridge does not guarantee order, but is mostly sorted so `slice::sort` is a
149            // decent fit.
150            states.sort_by_key(|(_, id)| *id);
151
152            // Technically this is broken if the input has a comment line at the end that is longer
153            // than `BYTES_PER_CHUNK`, but in practice this ought to be fine.
154            ends_in_unterminated_row(&last_slice, eol_char, comment_prefix)
155        } else {
156            // For the non-compressed case this is a zero-copy op.
157            // TODO: Implement streaming chunk logic.
158            let (bytes, _) =
159                reader.read_next_slice(&leftover, usize::MAX, decompressed_size_hint)?;
160
161            let num_chunks = bytes.len().div_ceil(BYTES_PER_CHUNK);
162            (0..num_chunks)
163                .into_par_iter()
164                .map(|chunk_idx| {
165                    let mut start_offset = chunk_idx * BYTES_PER_CHUNK;
166                    let next_start_offset = (start_offset + BYTES_PER_CHUNK).min(bytes.len());
167
168                    if start_offset != 0 {
169                        // Ensure we start at the start of a line.
170                        if let Some(nl_off) = bytes[start_offset..next_start_offset]
171                            .iter()
172                            .position(|b| *b == eol_char)
173                        {
174                            start_offset += nl_off + 1;
175                        } else {
176                            return (count.analyze_chunk(&[]), 0);
177                        }
178                    }
179
180                    let stop_offset = if let Some(nl_off) = bytes[next_start_offset..]
181                        .iter()
182                        .position(|b| *b == eol_char)
183                    {
184                        next_start_offset + nl_off + 1
185                    } else {
186                        bytes.len()
187                    };
188
189                    (count.analyze_chunk(&bytes[start_offset..stop_offset]), 0)
190                })
191                .collect_into_vec(&mut states);
192
193            ends_in_unterminated_row(&bytes, eol_char, comment_prefix)
194        };
195
196        let mut n = 0;
197        let mut in_string = false;
198        for (pair, _) in states {
199            n += pair[in_string as usize].newline_count;
200            in_string = pair[in_string as usize].end_inside_string;
201        }
202        n += eof_unterminated_row as usize;
203        Ok(n)
204    })
205}
206
207/// Read the number of rows without parsing columns.
208/// Useful for count(*) queries.
209/// Supports transparent decompression.
210#[allow(clippy::too_many_arguments)]
211pub fn count_rows_from_slice_par(
212    buffer: Buffer<u8>,
213    quote_char: Option<u8>,
214    comment_prefix: Option<&CommentPrefix>,
215    eol_char: u8,
216    has_header: bool,
217    skip_lines: usize,
218    skip_rows_before_header: usize,
219    skip_rows_after_header: usize,
220    raise_if_empty: bool,
221) -> PolarsResult<usize> {
222    const ASSUMED_COMPRESSION_RATIO: usize = 4;
223
224    let buffer_len = buffer.len();
225    let reader = ByteSourceReader::from_memory(buffer)?;
226    let decompressed_size_hint = Some(
227        buffer_len
228            * reader
229                .compression()
230                .map_or(1, |_| ASSUMED_COMPRESSION_RATIO),
231    );
232
233    count_rows_from_reader_par(
234        reader,
235        quote_char,
236        comment_prefix,
237        eol_char,
238        has_header,
239        skip_lines,
240        skip_rows_before_header,
241        skip_rows_after_header,
242        raise_if_empty,
243        decompressed_size_hint,
244    )
245}
246
247/// Checks if a line in a CSV file is a comment based on the given comment prefix configuration.
248///
249/// This function is used during CSV parsing to determine whether a line should be ignored based on its starting characters.
250#[inline]
251pub fn is_comment_line(line: &[u8], comment_prefix: Option<&CommentPrefix>) -> bool {
252    match comment_prefix {
253        Some(CommentPrefix::Single(c)) => line.first() == Some(c),
254        Some(CommentPrefix::Multi(s)) => line.starts_with(s.as_bytes()),
255        None => false,
256    }
257}
258
259/// Find the nearest next line position.
260/// Does not check for new line characters embedded in String fields.
261pub(super) fn next_line_position_naive(input: &[u8], eol_char: u8) -> Option<usize> {
262    let pos = memchr::memchr(eol_char, input)? + 1;
263    if input.len() - pos == 0 {
264        return None;
265    }
266    Some(pos)
267}
268
269/// Find the nearest next line position that is not embedded in a String field.
270pub(super) fn next_line_position(
271    mut input: &[u8],
272    mut expected_fields: Option<usize>,
273    separator: u8,
274    quote_char: Option<u8>,
275    eol_char: u8,
276) -> Option<usize> {
277    fn accept_line(
278        line: &[u8],
279        expected_fields: usize,
280        separator: u8,
281        eol_char: u8,
282        quote_char: Option<u8>,
283    ) -> bool {
284        let mut count = 0usize;
285        for (field, _) in SplitFields::new(line, separator, quote_char, eol_char) {
286            if memchr2_iter(separator, eol_char, field).count() >= expected_fields {
287                return false;
288            }
289            count += 1;
290        }
291
292        // if the latest field is missing
293        // e.g.:
294        // a,b,c
295        // vala,valb,
296        // SplitFields returns a count that is 1 less
297        // There fore we accept:
298        // expected == count
299        // and
300        // expected == count - 1
301        expected_fields.wrapping_sub(count) <= 1
302    }
303
304    // we check 3 subsequent lines for `accept_line` before we accept
305    // if 3 groups are rejected we reject completely
306    let mut rejected_line_groups = 0u8;
307
308    let mut total_pos = 0;
309    if input.is_empty() {
310        return None;
311    }
312    let mut lines_checked = 0u8;
313    loop {
314        if rejected_line_groups >= 3 {
315            return None;
316        }
317        lines_checked = lines_checked.wrapping_add(1);
318        // headers might have an extra value
319        // So if we have churned through enough lines
320        // we try one field less.
321        if lines_checked == u8::MAX {
322            if let Some(ef) = expected_fields {
323                expected_fields = Some(ef.saturating_sub(1))
324            }
325        };
326        let pos = memchr::memchr(eol_char, input)? + 1;
327        if input.len() - pos == 0 {
328            return None;
329        }
330        debug_assert!(pos <= input.len());
331        let new_input = unsafe { input.get_unchecked(pos..) };
332        let mut lines = SplitLines::new(new_input, quote_char, eol_char, None);
333        let line = lines.next();
334
335        match (line, expected_fields) {
336            // count the fields, and determine if they are equal to what we expect from the schema
337            (Some(line), Some(expected_fields)) => {
338                if accept_line(line, expected_fields, separator, eol_char, quote_char) {
339                    let mut valid = true;
340                    for line in lines.take(2) {
341                        if !accept_line(line, expected_fields, separator, eol_char, quote_char) {
342                            valid = false;
343                            break;
344                        }
345                    }
346                    if valid {
347                        return Some(total_pos + pos);
348                    } else {
349                        rejected_line_groups += 1;
350                    }
351                } else {
352                    debug_assert!(pos < input.len());
353                    unsafe {
354                        input = input.get_unchecked(pos + 1..);
355                    }
356                    total_pos += pos + 1;
357                }
358            },
359            // don't count the fields
360            (Some(_), None) => return Some(total_pos + pos),
361            // // no new line found, check latest line (without eol) for number of fields
362            _ => return None,
363        }
364    }
365}
366
367#[inline(always)]
368pub(super) fn is_whitespace(b: u8) -> bool {
369    b == b' ' || b == b'\t'
370}
371
372/// May have false-positives, but not false negatives.
373#[inline(always)]
374pub(super) fn could_be_whitespace_fast(b: u8) -> bool {
375    // We're interested in \t (ASCII 9) and " " (ASCII 32), both of which are
376    // <= 32. In that range there aren't a lot of other common symbols (besides
377    // newline), so this is a quick test which can be worth doing to avoid the
378    // exact test.
379    b <= 32
380}
381
382#[inline]
383fn skip_condition<F>(input: &[u8], f: F) -> &[u8]
384where
385    F: Fn(u8) -> bool,
386{
387    if input.is_empty() {
388        return input;
389    }
390
391    let read = input.iter().position(|b| !f(*b)).unwrap_or(input.len());
392    &input[read..]
393}
394
395/// Remove whitespace from the start of buffer.
396/// Makes sure that the bytes stream starts with
397///     'field_1,field_2'
398/// and not with
399///     '\nfield_1,field_1'
400#[inline]
401pub(super) fn skip_whitespace(input: &[u8]) -> &[u8] {
402    skip_condition(input, is_whitespace)
403}
404
405/// An adapted version of std::iter::Split.
406/// This exists solely because we cannot split the file in lines naively as
407///
408/// ```text
409///    for line in bytes.split(b'\n') {
410/// ```
411///
412/// This will fail when strings fields are have embedded end line characters.
413/// For instance: "This is a valid field\nI have multiples lines" is a valid string field, that contains multiple lines.
414pub struct SplitLines<'a> {
415    v: &'a [u8],
416    quote_char: u8,
417    eol_char: u8,
418    #[cfg(feature = "simd")]
419    simd_eol_char: SimdVec,
420    #[cfg(feature = "simd")]
421    simd_quote_char: SimdVec,
422    #[cfg(feature = "simd")]
423    previous_valid_eols: u64,
424    total_index: usize,
425    quoting: bool,
426    comment_prefix: Option<&'a CommentPrefix>,
427}
428
429#[cfg(feature = "simd")]
430const SIMD_SIZE: usize = 64;
431#[cfg(feature = "simd")]
432use std::simd::prelude::*;
433
434#[cfg(feature = "simd")]
435use polars_utils::clmul::prefix_xorsum_inclusive;
436
437#[cfg(feature = "simd")]
438type SimdVec = u8x64;
439
440impl<'a> SplitLines<'a> {
441    pub fn new(
442        slice: &'a [u8],
443        quote_char: Option<u8>,
444        eol_char: u8,
445        comment_prefix: Option<&'a CommentPrefix>,
446    ) -> Self {
447        let quoting = quote_char.is_some();
448        let quote_char = quote_char.unwrap_or(b'\"');
449        #[cfg(feature = "simd")]
450        let simd_eol_char = SimdVec::splat(eol_char);
451        #[cfg(feature = "simd")]
452        let simd_quote_char = SimdVec::splat(quote_char);
453        Self {
454            v: slice,
455            quote_char,
456            eol_char,
457            #[cfg(feature = "simd")]
458            simd_eol_char,
459            #[cfg(feature = "simd")]
460            simd_quote_char,
461            #[cfg(feature = "simd")]
462            previous_valid_eols: 0,
463            total_index: 0,
464            quoting,
465            comment_prefix,
466        }
467    }
468}
469
470impl<'a> SplitLines<'a> {
471    // scalar as in non-simd
472    fn next_scalar(&mut self) -> Option<&'a [u8]> {
473        if self.v.is_empty() {
474            return None;
475        }
476        if is_comment_line(self.v, self.comment_prefix) {
477            return self.next_comment_line();
478        }
479        {
480            let mut pos = 0u32;
481            let mut iter = self.v.iter();
482            let mut in_field = false;
483            loop {
484                match iter.next() {
485                    Some(&c) => {
486                        pos += 1;
487
488                        if self.quoting && c == self.quote_char {
489                            // toggle between string field enclosure
490                            //      if we encounter a starting '"' -> in_field = true;
491                            //      if we encounter a closing '"' -> in_field = false;
492                            in_field = !in_field;
493                        }
494                        // if we are not in a string and we encounter '\n' we can stop at this position.
495                        else if c == self.eol_char && !in_field {
496                            break;
497                        }
498                    },
499                    None => {
500                        let remainder = self.v;
501                        self.v = &[];
502                        return Some(remainder);
503                    },
504                }
505            }
506
507            unsafe {
508                debug_assert!((pos as usize) <= self.v.len());
509
510                // return line up to this position
511                let ret = Some(
512                    self.v
513                        .get_unchecked(..(self.total_index + pos as usize - 1)),
514                );
515                // skip the '\n' token and update slice.
516                self.v = self.v.get_unchecked(self.total_index + pos as usize..);
517                ret
518            }
519        }
520    }
521    fn next_comment_line(&mut self) -> Option<&'a [u8]> {
522        if let Some(pos) = next_line_position_naive(self.v, self.eol_char) {
523            unsafe {
524                // return line up to this position
525                let ret = Some(self.v.get_unchecked(..(pos - 1)));
526                // skip the '\n' token and update slice.
527                self.v = self.v.get_unchecked(pos..);
528                ret
529            }
530        } else {
531            let remainder = self.v;
532            self.v = &[];
533            Some(remainder)
534        }
535    }
536}
537
538impl<'a> Iterator for SplitLines<'a> {
539    type Item = &'a [u8];
540
541    #[inline]
542    #[cfg(not(feature = "simd"))]
543    fn next(&mut self) -> Option<&'a [u8]> {
544        self.next_scalar()
545    }
546
547    #[inline]
548    #[cfg(feature = "simd")]
549    fn next(&mut self) -> Option<&'a [u8]> {
550        // First check cached value
551        if self.previous_valid_eols != 0 {
552            let pos = self.previous_valid_eols.trailing_zeros() as usize;
553            self.previous_valid_eols >>= (pos + 1) as u64;
554
555            unsafe {
556                debug_assert!((pos) <= self.v.len());
557
558                // return line up to this position
559                let ret = Some(self.v.get_unchecked(..pos));
560                // skip the '\n' token and update slice.
561                self.v = self.v.get_unchecked(pos + 1..);
562                return ret;
563            }
564        }
565        if self.v.is_empty() {
566            return None;
567        }
568        if self.comment_prefix.is_some() {
569            return self.next_scalar();
570        }
571
572        self.total_index = 0;
573        let mut not_in_field_previous_iter = true;
574
575        loop {
576            let bytes = unsafe { self.v.get_unchecked(self.total_index..) };
577            if bytes.len() > SIMD_SIZE {
578                let lane: [u8; SIMD_SIZE] = unsafe {
579                    bytes
580                        .get_unchecked(0..SIMD_SIZE)
581                        .try_into()
582                        .unwrap_unchecked()
583                };
584                let simd_bytes = SimdVec::from(lane);
585                let eol_mask = simd_bytes.simd_eq(self.simd_eol_char).to_bitmask();
586
587                let valid_eols = if self.quoting {
588                    let quote_mask = simd_bytes.simd_eq(self.simd_quote_char).to_bitmask();
589                    let mut not_in_quote_field = prefix_xorsum_inclusive(quote_mask);
590
591                    if not_in_field_previous_iter {
592                        not_in_quote_field = !not_in_quote_field;
593                    }
594                    not_in_field_previous_iter = (not_in_quote_field & (1 << (SIMD_SIZE - 1))) > 0;
595                    eol_mask & not_in_quote_field
596                } else {
597                    eol_mask
598                };
599
600                if valid_eols != 0 {
601                    let pos = valid_eols.trailing_zeros() as usize;
602                    if pos == SIMD_SIZE - 1 {
603                        self.previous_valid_eols = 0;
604                    } else {
605                        self.previous_valid_eols = valid_eols >> (pos + 1) as u64;
606                    }
607
608                    unsafe {
609                        let pos = self.total_index + pos;
610                        debug_assert!((pos) <= self.v.len());
611
612                        // return line up to this position
613                        let ret = Some(self.v.get_unchecked(..pos));
614                        // skip the '\n' token and update slice.
615                        self.v = self.v.get_unchecked(pos + 1..);
616                        return ret;
617                    }
618                } else {
619                    self.total_index += SIMD_SIZE;
620                }
621            } else {
622                // Denotes if we are in a string field, started with a quote
623                let mut in_field = !not_in_field_previous_iter;
624                let mut pos = 0u32;
625                let mut iter = bytes.iter();
626                loop {
627                    match iter.next() {
628                        Some(&c) => {
629                            pos += 1;
630
631                            if self.quoting && c == self.quote_char {
632                                // toggle between string field enclosure
633                                //      if we encounter a starting '"' -> in_field = true;
634                                //      if we encounter a closing '"' -> in_field = false;
635                                in_field = !in_field;
636                            }
637                            // if we are not in a string and we encounter '\n' we can stop at this position.
638                            else if c == self.eol_char && !in_field {
639                                break;
640                            }
641                        },
642                        None => {
643                            let remainder = self.v;
644                            self.v = &[];
645                            return Some(remainder);
646                        },
647                    }
648                }
649
650                unsafe {
651                    debug_assert!((pos as usize) <= self.v.len());
652
653                    // return line up to this position
654                    let ret = Some(
655                        self.v
656                            .get_unchecked(..(self.total_index + pos as usize - 1)),
657                    );
658                    // skip the '\n' token and update slice.
659                    self.v = self.v.get_unchecked(self.total_index + pos as usize..);
660                    return ret;
661                }
662            }
663        }
664    }
665}
666
667pub struct CountLines {
668    quote_char: u8,
669    eol_char: u8,
670    #[cfg(feature = "simd")]
671    simd_eol_char: SimdVec,
672    #[cfg(feature = "simd")]
673    simd_quote_char: SimdVec,
674    quoting: bool,
675    comment_prefix: Option<CommentPrefix>,
676}
677
678#[derive(Copy, Clone, Debug, Default)]
679pub struct LineStats {
680    pub newline_count: usize,
681    pub last_newline_offset: usize,
682    pub end_inside_string: bool,
683}
684
685impl CountLines {
686    pub fn new(
687        quote_char: Option<u8>,
688        eol_char: u8,
689        comment_prefix: Option<CommentPrefix>,
690    ) -> Self {
691        let quoting = quote_char.is_some();
692        let quote_char = quote_char.unwrap_or(b'\"');
693        #[cfg(feature = "simd")]
694        let simd_eol_char = SimdVec::splat(eol_char);
695        #[cfg(feature = "simd")]
696        let simd_quote_char = SimdVec::splat(quote_char);
697        Self {
698            quote_char,
699            eol_char,
700            #[cfg(feature = "simd")]
701            simd_eol_char,
702            #[cfg(feature = "simd")]
703            simd_quote_char,
704            quoting,
705            comment_prefix,
706        }
707    }
708
709    /// Analyzes a chunk of CSV data.
710    ///
711    /// Returns (newline_count, last_newline_offset, end_inside_string) twice,
712    /// the first is assuming the start of the chunk is *not* inside a string,
713    /// the second assuming the start is inside a string.
714    ///
715    /// If comment_prefix is not None the start of bytes must be at the start of
716    /// a line (and thus not in the middle of a comment).
717    pub fn analyze_chunk(&self, bytes: &[u8]) -> [LineStats; 2] {
718        let mut states = [
719            LineStats {
720                newline_count: 0,
721                last_newline_offset: 0,
722                end_inside_string: false,
723            },
724            LineStats {
725                newline_count: 0,
726                last_newline_offset: 0,
727                end_inside_string: false,
728            },
729        ];
730
731        // If we have to deal with comments we can't use SIMD and have to explicitly do two passes.
732        if self.comment_prefix.is_some() {
733            states[0] = self.analyze_chunk_with_comment(bytes, false);
734            states[1] = self.analyze_chunk_with_comment(bytes, true);
735            return states;
736        }
737
738        // False if even number of quotes seen so far, true otherwise.
739        #[allow(unused_assignments)]
740        let mut global_quote_parity = false;
741        let mut scan_offset = 0;
742
743        #[cfg(feature = "simd")]
744        {
745            // 0 if even number of quotes seen so far, u64::MAX otherwise.
746            let mut global_quote_parity_mask = 0;
747            while scan_offset + 64 <= bytes.len() {
748                let block: [u8; 64] = unsafe {
749                    bytes
750                        .get_unchecked(scan_offset..scan_offset + 64)
751                        .try_into()
752                        .unwrap_unchecked()
753                };
754                let simd_bytes = SimdVec::from(block);
755                let eol_mask = simd_bytes.simd_eq(self.simd_eol_char).to_bitmask();
756                if self.quoting {
757                    let quote_mask = simd_bytes.simd_eq(self.simd_quote_char).to_bitmask();
758                    let quote_parity =
759                        prefix_xorsum_inclusive(quote_mask) ^ global_quote_parity_mask;
760                    global_quote_parity_mask = ((quote_parity as i64) >> 63) as u64;
761
762                    let start_outside_string_eol_mask = eol_mask & !quote_parity;
763                    states[0].newline_count += start_outside_string_eol_mask.count_ones() as usize;
764                    states[0].last_newline_offset = select_unpredictable(
765                        start_outside_string_eol_mask != 0,
766                        (scan_offset + 63)
767                            .wrapping_sub(start_outside_string_eol_mask.leading_zeros() as usize),
768                        states[0].last_newline_offset,
769                    );
770
771                    let start_inside_string_eol_mask = eol_mask & quote_parity;
772                    states[1].newline_count += start_inside_string_eol_mask.count_ones() as usize;
773                    states[1].last_newline_offset = select_unpredictable(
774                        start_inside_string_eol_mask != 0,
775                        (scan_offset + 63)
776                            .wrapping_sub(start_inside_string_eol_mask.leading_zeros() as usize),
777                        states[1].last_newline_offset,
778                    );
779                } else {
780                    states[0].newline_count += eol_mask.count_ones() as usize;
781                    states[0].last_newline_offset = select_unpredictable(
782                        eol_mask != 0,
783                        (scan_offset + 63).wrapping_sub(eol_mask.leading_zeros() as usize),
784                        states[0].last_newline_offset,
785                    );
786                }
787
788                scan_offset += 64;
789            }
790
791            global_quote_parity = global_quote_parity_mask > 0;
792        }
793
794        while scan_offset < bytes.len() {
795            let c = unsafe { *bytes.get_unchecked(scan_offset) };
796            global_quote_parity ^= (c == self.quote_char) & self.quoting;
797
798            let state = &mut states[global_quote_parity as usize];
799            state.newline_count += (c == self.eol_char) as usize;
800            state.last_newline_offset =
801                select_unpredictable(c == self.eol_char, scan_offset, state.last_newline_offset);
802
803            scan_offset += 1;
804        }
805
806        states[0].end_inside_string = global_quote_parity;
807        states[1].end_inside_string = !global_quote_parity;
808        states
809    }
810
811    // bytes must begin at the start of a line.
812    fn analyze_chunk_with_comment(&self, bytes: &[u8], mut in_string: bool) -> LineStats {
813        let pre_s = match self.comment_prefix.as_ref().unwrap() {
814            CommentPrefix::Single(pc) => core::slice::from_ref(pc),
815            CommentPrefix::Multi(ps) => ps.as_bytes(),
816        };
817
818        let mut state = LineStats::default();
819        let mut scan_offset = 0;
820        while scan_offset < bytes.len() {
821            // Skip comment line if needed.
822            while bytes[scan_offset..].starts_with(pre_s) {
823                scan_offset += pre_s.len();
824                let Some(nl_off) = bytes[scan_offset..]
825                    .iter()
826                    .position(|c| *c == self.eol_char)
827                else {
828                    break;
829                };
830                scan_offset += nl_off + 1;
831            }
832
833            while scan_offset < bytes.len() {
834                let c = unsafe { *bytes.get_unchecked(scan_offset) };
835                in_string ^= (c == self.quote_char) & self.quoting;
836
837                if c == self.eol_char && !in_string {
838                    state.newline_count += 1;
839                    state.last_newline_offset = scan_offset;
840                    scan_offset += 1;
841                    break;
842                } else {
843                    scan_offset += 1;
844                }
845            }
846        }
847
848        state.end_inside_string = in_string;
849        state
850    }
851
852    pub fn find_next(&self, bytes: &[u8], chunk_size: &mut usize) -> (usize, usize) {
853        loop {
854            let b = unsafe { bytes.get_unchecked(..(*chunk_size).min(bytes.len())) };
855
856            let (count, offset) = if self.comment_prefix.is_some() {
857                let stats = self.analyze_chunk_with_comment(b, false);
858                (stats.newline_count, stats.last_newline_offset)
859            } else {
860                self.count(b)
861            };
862
863            if count > 0 || b.len() == bytes.len() {
864                return (count, offset);
865            }
866
867            *chunk_size = chunk_size.saturating_mul(2);
868        }
869    }
870
871    pub fn count_rows(&self, bytes: &[u8], is_eof: bool) -> (usize, usize) {
872        let stats = if self.comment_prefix.is_some() {
873            self.analyze_chunk_with_comment(bytes, false)
874        } else {
875            self.analyze_chunk(bytes)[0]
876        };
877
878        let mut count = stats.newline_count;
879        let mut offset = stats.last_newline_offset;
880
881        if count > 0 {
882            offset = cmp::min(offset + 1, bytes.len());
883        } else {
884            debug_assert!(offset == 0);
885        }
886
887        if is_eof {
888            count += ends_in_unterminated_row(bytes, self.eol_char, self.comment_prefix.as_ref())
889                as usize;
890            offset = bytes.len();
891        }
892
893        (count, offset)
894    }
895
896    /// Returns count and offset to split for remainder in slice.
897    #[cfg(feature = "simd")]
898    pub fn count(&self, bytes: &[u8]) -> (usize, usize) {
899        let mut total_idx = 0;
900        let original_bytes = bytes;
901        let mut count = 0;
902        let mut position = 0;
903        let mut not_in_field_previous_iter = true;
904
905        loop {
906            let bytes = unsafe { original_bytes.get_unchecked(total_idx..) };
907
908            if bytes.len() > SIMD_SIZE {
909                let lane: [u8; SIMD_SIZE] = unsafe {
910                    bytes
911                        .get_unchecked(0..SIMD_SIZE)
912                        .try_into()
913                        .unwrap_unchecked()
914                };
915                let simd_bytes = SimdVec::from(lane);
916                let eol_mask = simd_bytes.simd_eq(self.simd_eol_char).to_bitmask();
917
918                let valid_eols = if self.quoting {
919                    let quote_mask = simd_bytes.simd_eq(self.simd_quote_char).to_bitmask();
920                    let mut not_in_quote_field = prefix_xorsum_inclusive(quote_mask);
921
922                    if not_in_field_previous_iter {
923                        not_in_quote_field = !not_in_quote_field;
924                    }
925                    not_in_field_previous_iter = (not_in_quote_field & (1 << (SIMD_SIZE - 1))) > 0;
926                    eol_mask & not_in_quote_field
927                } else {
928                    eol_mask
929                };
930
931                if valid_eols != 0 {
932                    count += valid_eols.count_ones() as usize;
933                    position = total_idx + 63 - valid_eols.leading_zeros() as usize;
934                    debug_assert_eq!(original_bytes[position], self.eol_char)
935                }
936                total_idx += SIMD_SIZE;
937            } else if bytes.is_empty() {
938                debug_assert!(count == 0 || original_bytes[position] == self.eol_char);
939                return (count, position);
940            } else {
941                let (c, o) = self.count_no_simd(bytes, !not_in_field_previous_iter);
942
943                let (count, position) = if c > 0 {
944                    (count + c, total_idx + o)
945                } else {
946                    (count, position)
947                };
948                debug_assert!(count == 0 || original_bytes[position] == self.eol_char);
949
950                return (count, position);
951            }
952        }
953    }
954
955    #[cfg(not(feature = "simd"))]
956    pub fn count(&self, bytes: &[u8]) -> (usize, usize) {
957        self.count_no_simd(bytes, false)
958    }
959
960    fn count_no_simd(&self, bytes: &[u8], in_field: bool) -> (usize, usize) {
961        let iter = bytes.iter();
962        let mut in_field = in_field;
963        let mut count = 0;
964        let mut position = 0;
965
966        for b in iter {
967            let c = *b;
968            if self.quoting && c == self.quote_char {
969                // toggle between string field enclosure
970                //      if we encounter a starting '"' -> in_field = true;
971                //      if we encounter a closing '"' -> in_field = false;
972                in_field = !in_field;
973            }
974            // If we are not in a string and we encounter '\n' we can stop at this position.
975            else if c == self.eol_char && !in_field {
976                position = (b as *const _ as usize) - (bytes.as_ptr() as usize);
977                count += 1;
978            }
979        }
980        debug_assert!(count == 0 || bytes[position] == self.eol_char);
981
982        (count, position)
983    }
984}
985
986fn ends_in_unterminated_row(
987    bytes: &[u8],
988    eol_char: u8,
989    comment_prefix: Option<&CommentPrefix>,
990) -> bool {
991    if !bytes.is_empty() && bytes.last().copied().unwrap() != eol_char {
992        // We can do a simple backwards-scan to find the start of last line if it is a
993        // comment line, since comment lines can't escape new-lines.
994        let last_new_line_post = memchr::memrchr(eol_char, bytes).unwrap_or(0);
995        let last_line_is_comment_line = bytes
996            .get(last_new_line_post + 1..)
997            .map(|line| is_comment_line(line, comment_prefix))
998            .unwrap_or(false);
999
1000        return !last_line_is_comment_line;
1001    }
1002
1003    false
1004}
1005
1006#[inline]
1007fn find_quoted(bytes: &[u8], quote_char: u8, needle: u8) -> Option<usize> {
1008    let mut in_field = false;
1009
1010    let mut idx = 0u32;
1011    // micro optimizations
1012    #[allow(clippy::explicit_counter_loop)]
1013    for &c in bytes.iter() {
1014        if c == quote_char {
1015            // toggle between string field enclosure
1016            //      if we encounter a starting '"' -> in_field = true;
1017            //      if we encounter a closing '"' -> in_field = false;
1018            in_field = !in_field;
1019        }
1020
1021        if !in_field && c == needle {
1022            return Some(idx as usize);
1023        }
1024        idx += 1;
1025    }
1026    None
1027}
1028
1029#[inline]
1030pub(super) fn skip_this_line(bytes: &[u8], quote: Option<u8>, eol_char: u8) -> &[u8] {
1031    let pos = match quote {
1032        Some(quote) => find_quoted(bytes, quote, eol_char),
1033        None => bytes.iter().position(|x| *x == eol_char),
1034    };
1035    match pos {
1036        None => &[],
1037        Some(pos) => &bytes[pos + 1..],
1038    }
1039}
1040
1041#[inline]
1042pub(super) fn skip_this_line_naive(input: &[u8], eol_char: u8) -> &[u8] {
1043    if let Some(pos) = next_line_position_naive(input, eol_char) {
1044        unsafe { input.get_unchecked(pos..) }
1045    } else {
1046        &[]
1047    }
1048}
1049
1050/// Parse CSV.
1051///
1052/// # Arguments
1053/// * `bytes` - input to parse
1054/// * `offset` - offset in bytes in total input. This is 0 if single threaded. If multi-threaded every
1055///   thread has a different offset.
1056/// * `projection` - Indices of the columns to project.
1057/// * `buffers` - Parsed output will be written to these buffers. Except for UTF8 data. The offsets of the
1058///   fields are written to the buffers. The UTF8 data will be parsed later.
1059///
1060/// Returns the number of bytes parsed successfully.
1061#[allow(clippy::too_many_arguments)]
1062pub(super) fn parse_lines(
1063    mut bytes: &[u8],
1064    parse_options: &CsvParseOptions,
1065    offset: usize,
1066    ignore_errors: bool,
1067    null_values: Option<&NullValuesCompiled>,
1068    projection: &[usize],
1069    buffers: &mut [Builder],
1070    n_lines: usize,
1071    // length of original schema
1072    schema_len: usize,
1073    schema: &Schema,
1074) -> PolarsResult<usize> {
1075    assert!(
1076        !projection.is_empty(),
1077        "at least one column should be projected"
1078    );
1079    let mut truncate_ragged_lines = parse_options.truncate_ragged_lines;
1080    // During projection pushdown we are not checking other csv fields.
1081    // This would be very expensive and we don't care as we only want
1082    // the projected columns.
1083    if projection.len() != schema_len {
1084        truncate_ragged_lines = true
1085    }
1086
1087    // we use the pointers to track the no of bytes read.
1088    let start = bytes.as_ptr() as usize;
1089    let original_bytes_len = bytes.len();
1090    let n_lines = n_lines as u32;
1091
1092    let mut line_count = 0u32;
1093    loop {
1094        if line_count > n_lines {
1095            let end = bytes.as_ptr() as usize;
1096            return Ok(end - start);
1097        }
1098
1099        if bytes.is_empty() {
1100            return Ok(original_bytes_len);
1101        } else if is_comment_line(bytes, parse_options.comment_prefix.as_ref()) {
1102            // deal with comments
1103            let bytes_rem = skip_this_line_naive(bytes, parse_options.eol_char);
1104            bytes = bytes_rem;
1105            continue;
1106        }
1107
1108        // Every line we only need to parse the columns that are projected.
1109        // Therefore we check if the idx of the field is in our projected columns.
1110        // If it is not, we skip the field.
1111        let mut projection_iter = projection.iter().copied();
1112        let mut next_projected = unsafe { projection_iter.next().unwrap_unchecked() };
1113        let mut processed_fields = 0;
1114
1115        let mut iter = SplitFields::new(
1116            bytes,
1117            parse_options.separator,
1118            parse_options.quote_char,
1119            parse_options.eol_char,
1120        );
1121        let mut idx = 0u32;
1122        let mut read_sol = 0;
1123        loop {
1124            match iter.next() {
1125                // end of line
1126                None => {
1127                    bytes = unsafe { bytes.get_unchecked(std::cmp::min(read_sol, bytes.len())..) };
1128                    break;
1129                },
1130                Some((mut field, needs_escaping)) => {
1131                    let field_len = field.len();
1132
1133                    // +1 is the split character that is consumed by the iterator.
1134                    read_sol += field_len + 1;
1135
1136                    if idx == next_projected as u32 {
1137                        // the iterator is finished when it encounters a `\n`
1138                        // this could be preceded by a '\r'
1139                        unsafe {
1140                            if field_len > 0 && *field.get_unchecked(field_len - 1) == b'\r' {
1141                                field = field.get_unchecked(..field_len - 1);
1142                            }
1143                        }
1144
1145                        debug_assert!(processed_fields < buffers.len());
1146                        let buf = unsafe {
1147                            // SAFETY: processed fields index can never exceed the projection indices.
1148                            buffers.get_unchecked_mut(processed_fields)
1149                        };
1150                        let mut add_null = false;
1151
1152                        // if we have null values argument, check if this field equal null value
1153                        if let Some(null_values) = null_values {
1154                            let field = if needs_escaping && !field.is_empty() {
1155                                unsafe { field.get_unchecked(1..field.len() - 1) }
1156                            } else {
1157                                field
1158                            };
1159
1160                            // SAFETY:
1161                            // process fields is in bounds
1162                            add_null = unsafe { null_values.is_null(field, idx as usize) }
1163                        }
1164                        if add_null {
1165                            buf.add_null(!parse_options.missing_is_null && field.is_empty())
1166                        } else {
1167                            buf.add(field, ignore_errors, needs_escaping, parse_options.missing_is_null)
1168                                .map_err(|e| {
1169                                    let bytes_offset = offset + field.as_ptr() as usize - start;
1170                                    let unparsable = String::from_utf8_lossy(field);
1171                                    let column_name = schema.get_at_index(idx as usize).unwrap().0;
1172                                    polars_err!(
1173                                        ComputeError:
1174                                        "could not parse `{}` as dtype `{}` at column '{}' (column number {})\n\n\
1175                                        The current offset in the file is {} bytes.\n\
1176                                        \n\
1177                                        You might want to try:\n\
1178                                        - increasing `infer_schema_length` (e.g. `infer_schema_length=10000`),\n\
1179                                        - increasing `infer_schema_files` (e.g. `infer_schema_files=50`),\n\
1180                                        - specifying correct dtype with the `schema_overrides` argument\n\
1181                                        - setting `ignore_errors` to `True`,\n\
1182                                        - adding `{}` to the `null_values` list.\n\n\
1183                                        Original error: ```{}```",
1184                                        &unparsable,
1185                                        buf.dtype(),
1186                                        column_name,
1187                                        idx + 1,
1188                                        bytes_offset,
1189                                        &unparsable,
1190                                        e
1191                                    )
1192                                })?;
1193                        }
1194                        processed_fields += 1;
1195
1196                        // if we have all projected columns we are done with this line
1197                        match projection_iter.next() {
1198                            Some(p) => next_projected = p,
1199                            None => {
1200                                if bytes.get(read_sol - 1) == Some(&parse_options.eol_char) {
1201                                    bytes = unsafe { bytes.get_unchecked(read_sol..) };
1202                                } else {
1203                                    if !truncate_ragged_lines && read_sol < bytes.len() {
1204                                        polars_bail!(ComputeError: r#"found more fields than defined in 'Schema'
1205
1206Consider setting 'truncate_ragged_lines={}'."#, polars_error::constants::TRUE)
1207                                    }
1208                                    let bytes_rem = skip_this_line(
1209                                        unsafe { bytes.get_unchecked(read_sol - 1..) },
1210                                        parse_options.quote_char,
1211                                        parse_options.eol_char,
1212                                    );
1213                                    bytes = bytes_rem;
1214                                }
1215                                break;
1216                            },
1217                        }
1218                    }
1219                    idx += 1;
1220                },
1221            }
1222        }
1223
1224        // there can be lines that miss fields (also the comma values)
1225        // this means the splitter won't process them.
1226        // We traverse them to read them as null values.
1227        while processed_fields < projection.len() {
1228            debug_assert!(processed_fields < buffers.len());
1229            let buf = unsafe {
1230                // SAFETY: processed fields index can never exceed the projection indices.
1231                buffers.get_unchecked_mut(processed_fields)
1232            };
1233            buf.add_null(!parse_options.missing_is_null);
1234            processed_fields += 1;
1235        }
1236        line_count += 1;
1237    }
1238}
1239
1240#[cfg(test)]
1241mod test {
1242    use super::SplitLines;
1243
1244    #[test]
1245    fn test_splitlines() {
1246        let input = "1,\"foo\n\"\n2,\"foo\n\"\n";
1247        let mut lines = SplitLines::new(input.as_bytes(), Some(b'"'), b'\n', None);
1248        assert_eq!(lines.next(), Some("1,\"foo\n\"".as_bytes()));
1249        assert_eq!(lines.next(), Some("2,\"foo\n\"".as_bytes()));
1250        assert_eq!(lines.next(), None);
1251
1252        let input2 = "1,'foo\n'\n2,'foo\n'\n";
1253        let mut lines2 = SplitLines::new(input2.as_bytes(), Some(b'\''), b'\n', None);
1254        assert_eq!(lines2.next(), Some("1,'foo\n'".as_bytes()));
1255        assert_eq!(lines2.next(), Some("2,'foo\n'".as_bytes()));
1256        assert_eq!(lines2.next(), None);
1257    }
1258}