Skip to main content

polars_io/csv/read/
builder.rs

1use polars_arrow::array::MutableBinaryViewArray;
2#[cfg(feature = "dtype-decimal")]
3use polars_compute::decimal::str_to_dec128;
4#[cfg(feature = "dtype-categorical")]
5use polars_core::chunked_array::builder::CategoricalChunkedBuilder;
6#[cfg(any(feature = "dtype-datetime", feature = "dtype-date"))]
7use polars_core::chunked_array::temporal::string::infer::{
8    DatetimeInfer, StrpTimeParser, TryFromWithUnit, infer_pattern_single,
9};
10#[cfg(any(feature = "dtype-datetime", feature = "dtype-date"))]
11use polars_core::chunked_array::temporal::string::patterns::Pattern;
12use polars_core::prelude::*;
13use polars_error::to_compute_err;
14#[cfg(feature = "dtype-f16")]
15use polars_utils::float16::pf16;
16use polars_utils::vec::PushUnchecked;
17
18use super::options::{CsvEncoding, NullValuesCompiled};
19use super::parser::{could_be_whitespace_fast, skip_whitespace};
20use super::utils::unescape_field;
21
22pub(crate) trait PrimitiveParser: PolarsNumericType {
23    fn parse(bytes: &[u8]) -> Option<Self::Native>;
24}
25
26#[cfg(feature = "dtype-f16")]
27impl PrimitiveParser for Float16Type {
28    #[inline]
29    fn parse(bytes: &[u8]) -> Option<pf16> {
30        use num_traits::FromPrimitive;
31
32        pf16::from_f32(fast_float2::parse(bytes).ok()?)
33    }
34}
35
36impl PrimitiveParser for Float32Type {
37    #[inline]
38    fn parse(bytes: &[u8]) -> Option<f32> {
39        fast_float2::parse(bytes).ok()
40    }
41}
42impl PrimitiveParser for Float64Type {
43    #[inline]
44    fn parse(bytes: &[u8]) -> Option<f64> {
45        fast_float2::parse(bytes).ok()
46    }
47}
48
49#[cfg(feature = "dtype-u8")]
50impl PrimitiveParser for UInt8Type {
51    #[inline]
52    fn parse(bytes: &[u8]) -> Option<u8> {
53        atoi_simd::parse::<_, true, true>(bytes).ok()
54    }
55}
56#[cfg(feature = "dtype-u16")]
57impl PrimitiveParser for UInt16Type {
58    #[inline]
59    fn parse(bytes: &[u8]) -> Option<u16> {
60        atoi_simd::parse::<_, true, true>(bytes).ok()
61    }
62}
63impl PrimitiveParser for UInt32Type {
64    #[inline]
65    fn parse(bytes: &[u8]) -> Option<u32> {
66        atoi_simd::parse::<_, true, true>(bytes).ok()
67    }
68}
69impl PrimitiveParser for UInt64Type {
70    #[inline]
71    fn parse(bytes: &[u8]) -> Option<u64> {
72        atoi_simd::parse::<_, true, true>(bytes).ok()
73    }
74}
75#[cfg(feature = "dtype-u128")]
76impl PrimitiveParser for UInt128Type {
77    #[inline]
78    fn parse(bytes: &[u8]) -> Option<u128> {
79        atoi_simd::parse::<_, true, true>(bytes).ok()
80    }
81}
82#[cfg(feature = "dtype-i8")]
83impl PrimitiveParser for Int8Type {
84    #[inline]
85    fn parse(bytes: &[u8]) -> Option<i8> {
86        atoi_simd::parse::<_, true, true>(bytes).ok()
87    }
88}
89#[cfg(feature = "dtype-i16")]
90impl PrimitiveParser for Int16Type {
91    #[inline]
92    fn parse(bytes: &[u8]) -> Option<i16> {
93        atoi_simd::parse::<_, true, true>(bytes).ok()
94    }
95}
96impl PrimitiveParser for Int32Type {
97    #[inline]
98    fn parse(bytes: &[u8]) -> Option<i32> {
99        atoi_simd::parse::<_, true, true>(bytes).ok()
100    }
101}
102impl PrimitiveParser for Int64Type {
103    #[inline]
104    fn parse(bytes: &[u8]) -> Option<i64> {
105        atoi_simd::parse::<_, true, true>(bytes).ok()
106    }
107}
108#[cfg(feature = "dtype-i128")]
109impl PrimitiveParser for Int128Type {
110    #[inline]
111    fn parse(bytes: &[u8]) -> Option<i128> {
112        atoi_simd::parse::<_, true, true>(bytes).ok()
113    }
114}
115
116trait ParsedBuilder {
117    fn parse_bytes(
118        &mut self,
119        bytes: &[u8],
120        ignore_errors: bool,
121        _needs_escaping: bool,
122        _missing_is_null: bool,
123        _time_unit: Option<TimeUnit>,
124    ) -> PolarsResult<()>;
125}
126
127impl<T> ParsedBuilder for PrimitiveChunkedBuilder<T>
128where
129    T: PolarsNumericType + PrimitiveParser,
130{
131    #[inline]
132    fn parse_bytes(
133        &mut self,
134        mut bytes: &[u8],
135        ignore_errors: bool,
136        needs_escaping: bool,
137        _missing_is_null: bool,
138        _time_unit: Option<TimeUnit>,
139    ) -> PolarsResult<()> {
140        if !bytes.is_empty() && needs_escaping {
141            bytes = &bytes[1..bytes.len() - 1];
142        }
143
144        if !bytes.is_empty() && could_be_whitespace_fast(bytes[0]) {
145            bytes = skip_whitespace(bytes);
146        }
147
148        if bytes.is_empty() {
149            self.append_null();
150            return Ok(());
151        }
152
153        match T::parse(bytes) {
154            Some(value) => self.append_value(value),
155            None => {
156                if ignore_errors {
157                    self.append_null()
158                } else {
159                    polars_bail!(ComputeError: "invalid primitive value found during CSV parsing")
160                }
161            },
162        }
163        Ok(())
164    }
165}
166
167pub struct Utf8Field {
168    name: PlSmallStr,
169    mutable: MutableBinaryViewArray<[u8]>,
170    scratch: Vec<u8>,
171    quote_char: u8,
172    encoding: CsvEncoding,
173}
174
175impl Utf8Field {
176    fn new(
177        name: PlSmallStr,
178        capacity: usize,
179        quote_char: Option<u8>,
180        encoding: CsvEncoding,
181    ) -> Self {
182        Self {
183            name,
184            mutable: MutableBinaryViewArray::with_capacity(capacity),
185            scratch: vec![],
186            quote_char: quote_char.unwrap_or(b'"'),
187            encoding,
188        }
189    }
190}
191
192#[inline]
193pub fn validate_utf8(bytes: &[u8]) -> bool {
194    simdutf8::basic::from_utf8(bytes).is_ok()
195}
196
197impl ParsedBuilder for Utf8Field {
198    #[inline(always)]
199    fn parse_bytes(
200        &mut self,
201        bytes: &[u8],
202        ignore_errors: bool,
203        needs_escaping: bool,
204        missing_is_null: bool,
205        _time_unit: Option<TimeUnit>,
206    ) -> PolarsResult<()> {
207        if bytes.is_empty() {
208            if missing_is_null {
209                self.mutable.push_null()
210            } else {
211                self.mutable.push(Some([]))
212            }
213            return Ok(());
214        }
215
216        // note that one branch writes without updating the length, so we must do that later.
217        let escaped_bytes = if needs_escaping {
218            polars_ensure!(bytes.len() > 1 && bytes.last() == Some(&self.quote_char), ComputeError: "invalid csv file\n\nField `{}` is not properly escaped.", std::str::from_utf8(bytes).map_err(to_compute_err)?);
219            let inner = &bytes[1..bytes.len() - 1];
220            self.scratch.clear();
221            self.scratch.reserve(inner.len());
222
223            // SAFETY:
224            // we just allocated enough capacity and data_len is correct.
225            unsafe {
226                let n_written =
227                    unescape_field(inner, self.quote_char, self.scratch.spare_capacity_mut());
228                self.scratch.set_len(n_written);
229            }
230
231            self.scratch.as_slice()
232        } else {
233            bytes
234        };
235
236        if matches!(self.encoding, CsvEncoding::LossyUtf8) | ignore_errors {
237            // It is important that this happens after escaping, as invalid escaped string can produce
238            // invalid utf8.
239            let parse_result = validate_utf8(escaped_bytes);
240
241            match parse_result {
242                true => {
243                    let value = escaped_bytes;
244                    self.mutable.push_value(value)
245                },
246                false => {
247                    if matches!(self.encoding, CsvEncoding::LossyUtf8) {
248                        // TODO! do this without allocating
249                        let s = String::from_utf8_lossy(escaped_bytes);
250                        self.mutable.push_value(s.as_ref().as_bytes())
251                    } else if ignore_errors {
252                        self.mutable.push_null()
253                    } else {
254                        // If field before escaping is valid utf8, the escaping is incorrect.
255                        if needs_escaping && validate_utf8(bytes) {
256                            polars_bail!(ComputeError: "string field is not properly escaped");
257                        } else {
258                            polars_bail!(ComputeError: "invalid utf-8 sequence");
259                        }
260                    }
261                },
262            }
263        } else {
264            self.mutable.push_value(escaped_bytes)
265        }
266
267        Ok(())
268    }
269}
270
271#[cfg(feature = "dtype-categorical")]
272pub struct CategoricalField<T: PolarsCategoricalType> {
273    escape_scratch: Vec<u8>,
274    quote_char: u8,
275    builder: CategoricalChunkedBuilder<T>,
276}
277
278#[cfg(feature = "dtype-categorical")]
279impl<T: PolarsCategoricalType> CategoricalField<T> {
280    fn new(name: PlSmallStr, capacity: usize, quote_char: Option<u8>, dtype: DataType) -> Self {
281        let mut builder = CategoricalChunkedBuilder::new(name, dtype);
282        builder.reserve(capacity);
283
284        Self {
285            escape_scratch: vec![],
286            quote_char: quote_char.unwrap_or(b'"'),
287            builder,
288        }
289    }
290
291    #[inline]
292    fn parse_bytes(
293        &mut self,
294        bytes: &[u8],
295        ignore_errors: bool,
296        needs_escaping: bool,
297        _missing_is_null: bool,
298        _time_unit: Option<TimeUnit>,
299    ) -> PolarsResult<()> {
300        if bytes.is_empty() {
301            self.builder.append_null();
302            return Ok(());
303        }
304        let escaped_bytes = if needs_escaping {
305            polars_ensure!(bytes.len() > 1 && bytes.last() == Some(&self.quote_char), ComputeError: "invalid csv file\n\nField `{}` is not properly escaped.", std::str::from_utf8(bytes).map_err(to_compute_err)?);
306            let inner = &bytes[1..bytes.len() - 1];
307            self.escape_scratch.clear();
308            self.escape_scratch.reserve(inner.len());
309            // SAFETY: we just allocated enough capacity and data_len is correct.
310            unsafe {
311                let n_written = unescape_field(
312                    inner,
313                    self.quote_char,
314                    self.escape_scratch.spare_capacity_mut(),
315                );
316                self.escape_scratch.set_len(n_written);
317            }
318            self.escape_scratch.as_slice()
319        } else {
320            bytes
321        };
322
323        match simdutf8::basic::from_utf8(escaped_bytes) {
324            Ok(key) => self.builder.append_str(key)?,
325            Err(_) if ignore_errors => self.builder.append_null(),
326            Err(_) => polars_bail!(ComputeError: "invalid utf-8 sequence"),
327        }
328        Ok(())
329    }
330}
331
332impl ParsedBuilder for BooleanChunkedBuilder {
333    #[inline]
334    fn parse_bytes(
335        &mut self,
336        bytes: &[u8],
337        ignore_errors: bool,
338        needs_escaping: bool,
339        _missing_is_null: bool,
340        _time_unit: Option<TimeUnit>,
341    ) -> PolarsResult<()> {
342        let bytes = if needs_escaping {
343            &bytes[1..bytes.len() - 1]
344        } else {
345            bytes
346        };
347        if bytes.eq_ignore_ascii_case(b"false") {
348            self.append_value(false);
349        } else if bytes.eq_ignore_ascii_case(b"true") {
350            self.append_value(true);
351        } else if ignore_errors || bytes.is_empty() {
352            self.append_null();
353        } else {
354            polars_bail!(
355                ComputeError: "error while parsing value {} as boolean",
356                String::from_utf8_lossy(bytes),
357            );
358        }
359        Ok(())
360    }
361}
362
363#[cfg(feature = "dtype-decimal")]
364pub struct DecimalField {
365    builder: PrimitiveChunkedBuilder<Int128Type>,
366    precision: usize,
367    scale: usize,
368    decimal_comma: bool,
369}
370
371#[cfg(feature = "dtype-decimal")]
372impl DecimalField {
373    fn new(
374        name: PlSmallStr,
375        capacity: usize,
376        precision: usize,
377        scale: usize,
378        decimal_comma: bool,
379    ) -> Self {
380        let builder = PrimitiveChunkedBuilder::<Int128Type>::new(name, capacity);
381        Self {
382            builder,
383            precision,
384            scale,
385            decimal_comma,
386        }
387    }
388}
389
390#[cfg(feature = "dtype-decimal")]
391impl ParsedBuilder for DecimalField {
392    #[inline]
393    fn parse_bytes(
394        &mut self,
395        mut bytes: &[u8],
396        ignore_errors: bool,
397        needs_escaping: bool,
398        _missing_is_null: bool,
399        _time_unit: Option<TimeUnit>,
400    ) -> PolarsResult<()> {
401        if !bytes.is_empty() && needs_escaping {
402            bytes = &bytes[1..bytes.len() - 1];
403        }
404
405        if !bytes.is_empty() && could_be_whitespace_fast(bytes[0]) {
406            bytes = skip_whitespace(bytes);
407        }
408
409        if bytes.is_empty() {
410            self.builder.append_null();
411            return Ok(());
412        }
413
414        match str_to_dec128(bytes, self.precision, self.scale, self.decimal_comma) {
415            Some(value) => self.builder.append_value(value),
416            None => {
417                if ignore_errors {
418                    self.builder.append_null()
419                } else {
420                    polars_bail!(ComputeError: "invalid decimal value found during CSV parsing")
421                }
422            },
423        }
424
425        Ok(())
426    }
427}
428
429#[cfg(any(feature = "dtype-datetime", feature = "dtype-date"))]
430pub struct DatetimeField<T: PolarsNumericType> {
431    compiled: Option<DatetimeInfer<T>>,
432    builder: PrimitiveChunkedBuilder<T>,
433}
434
435#[cfg(any(feature = "dtype-datetime", feature = "dtype-date"))]
436impl<T: PolarsNumericType> DatetimeField<T> {
437    fn new(name: PlSmallStr, capacity: usize) -> Self {
438        let builder = PrimitiveChunkedBuilder::<T>::new(name, capacity);
439        Self {
440            compiled: None,
441            builder,
442        }
443    }
444}
445
446#[cfg(any(feature = "dtype-datetime", feature = "dtype-date"))]
447fn slow_datetime_parser<T>(
448    buf: &mut DatetimeField<T>,
449    bytes: &[u8],
450    time_unit: Option<TimeUnit>,
451    ignore_errors: bool,
452) -> PolarsResult<()>
453where
454    T: PolarsNumericType,
455    DatetimeInfer<T>: TryFromWithUnit<Pattern>,
456{
457    let val = if bytes.is_ascii() {
458        // SAFETY:
459        // we just checked it is ascii
460        unsafe { std::str::from_utf8_unchecked(bytes) }
461    } else {
462        match std::str::from_utf8(bytes) {
463            Ok(val) => val,
464            Err(_) => {
465                if ignore_errors {
466                    buf.builder.append_null();
467                    return Ok(());
468                } else {
469                    polars_bail!(ComputeError: "invalid utf-8 sequence");
470                }
471            },
472        }
473    };
474
475    let pattern;
476    let parsed = match &mut buf.compiled {
477        // Retain the inferred candidate state across byte-parser misses. Rebuilding
478        // from `Pattern` here would reset the preferred format for every value.
479        Some(infer) => {
480            pattern = infer.pattern;
481            infer.parse(val)
482        },
483        None => {
484            pattern = match infer_pattern_single(val) {
485                Some(pattern) => pattern,
486                None => {
487                    if ignore_errors {
488                        buf.builder.append_null();
489                        return Ok(());
490                    } else {
491                        polars_bail!(ComputeError: "could not find a 'date/datetime' pattern for '{}'", val)
492                    }
493                },
494            };
495
496            let mut infer = match DatetimeInfer::try_from_with_unit(pattern, time_unit) {
497                Ok(infer) => infer,
498                Err(err) => {
499                    if ignore_errors {
500                        buf.builder.append_null();
501                        return Ok(());
502                    } else {
503                        return Err(err);
504                    }
505                },
506            };
507            let parsed = infer.parse(val);
508            if parsed.is_some() {
509                // Match the previous initialization behavior: only retain a parser
510                // after it has successfully parsed a value.
511                buf.compiled = Some(infer);
512            }
513            parsed
514        },
515    };
516
517    match parsed {
518        Some(parsed) => {
519            buf.builder.append_value(parsed);
520            Ok(())
521        },
522        None => {
523            if ignore_errors {
524                buf.builder.append_null();
525                Ok(())
526            } else {
527                polars_bail!(ComputeError: "could not parse '{}' with pattern '{:?}'", val, pattern)
528            }
529        },
530    }
531}
532
533#[cfg(any(feature = "dtype-datetime", feature = "dtype-date"))]
534impl<T> ParsedBuilder for DatetimeField<T>
535where
536    T: PolarsNumericType,
537    DatetimeInfer<T>: TryFromWithUnit<Pattern> + StrpTimeParser<T::Native>,
538{
539    #[inline]
540    fn parse_bytes(
541        &mut self,
542        mut bytes: &[u8],
543        ignore_errors: bool,
544        needs_escaping: bool,
545        _missing_is_null: bool,
546        time_unit: Option<TimeUnit>,
547    ) -> PolarsResult<()> {
548        if needs_escaping && bytes.len() >= 2 {
549            bytes = &bytes[1..bytes.len() - 1]
550        }
551
552        if bytes.is_empty() {
553            // for types other than string `_missing_is_null` is irrelevant; we always append null
554            self.builder.append_null();
555            return Ok(());
556        }
557
558        match &mut self.compiled {
559            None => slow_datetime_parser(self, bytes, time_unit, ignore_errors),
560            Some(compiled) => {
561                match compiled.parse_bytes(bytes, time_unit) {
562                    Some(parsed) => {
563                        self.builder.append_value(parsed);
564                        Ok(())
565                    },
566                    // fall back on chrono parser
567                    // this is a lot slower, we need to do utf8 checking and use
568                    // the slower parser
569                    None => slow_datetime_parser(self, bytes, time_unit, ignore_errors),
570                }
571            },
572        }
573    }
574}
575
576pub fn init_builders(
577    projection: &[usize],
578    capacity: usize,
579    schema: &Schema,
580    quote_char: Option<u8>,
581    encoding: CsvEncoding,
582    decimal_comma: bool,
583) -> PolarsResult<Vec<Builder>> {
584    projection
585        .iter()
586        .map(|&i| {
587            let (name, dtype) = schema.get_at_index(i).unwrap();
588            let name = name.clone();
589            let builder = match dtype {
590                &DataType::Boolean => Builder::Boolean(BooleanChunkedBuilder::new(name, capacity)),
591                #[cfg(feature = "dtype-i8")]
592                &DataType::Int8 => Builder::Int8(PrimitiveChunkedBuilder::new(name, capacity)),
593                #[cfg(feature = "dtype-i16")]
594                &DataType::Int16 => Builder::Int16(PrimitiveChunkedBuilder::new(name, capacity)),
595                &DataType::Int32 => Builder::Int32(PrimitiveChunkedBuilder::new(name, capacity)),
596                &DataType::Int64 => Builder::Int64(PrimitiveChunkedBuilder::new(name, capacity)),
597                #[cfg(feature = "dtype-i128")]
598                &DataType::Int128 => Builder::Int128(PrimitiveChunkedBuilder::new(name, capacity)),
599                #[cfg(feature = "dtype-u8")]
600                &DataType::UInt8 => Builder::UInt8(PrimitiveChunkedBuilder::new(name, capacity)),
601                #[cfg(feature = "dtype-u16")]
602                &DataType::UInt16 => Builder::UInt16(PrimitiveChunkedBuilder::new(name, capacity)),
603                &DataType::UInt32 => Builder::UInt32(PrimitiveChunkedBuilder::new(name, capacity)),
604                &DataType::UInt64 => Builder::UInt64(PrimitiveChunkedBuilder::new(name, capacity)),
605                #[cfg(feature = "dtype-u128")]
606                &DataType::UInt128 => {
607                    Builder::UInt128(PrimitiveChunkedBuilder::new(name, capacity))
608                },
609                #[cfg(feature = "dtype-f16")]
610                &DataType::Float16 => {
611                    if decimal_comma {
612                        Builder::DecimalFloat16(
613                            PrimitiveChunkedBuilder::new(name, capacity),
614                            Default::default(),
615                        )
616                    } else {
617                        Builder::Float16(PrimitiveChunkedBuilder::new(name, capacity))
618                    }
619                },
620                &DataType::Float32 => {
621                    if decimal_comma {
622                        Builder::DecimalFloat32(
623                            PrimitiveChunkedBuilder::new(name, capacity),
624                            Default::default(),
625                        )
626                    } else {
627                        Builder::Float32(PrimitiveChunkedBuilder::new(name, capacity))
628                    }
629                },
630                &DataType::Float64 => {
631                    if decimal_comma {
632                        Builder::DecimalFloat64(
633                            PrimitiveChunkedBuilder::new(name, capacity),
634                            Default::default(),
635                        )
636                    } else {
637                        Builder::Float64(PrimitiveChunkedBuilder::new(name, capacity))
638                    }
639                },
640                #[cfg(feature = "dtype-decimal")]
641                &DataType::Decimal(precision, scale) => Builder::Decimal(DecimalField::new(
642                    name,
643                    capacity,
644                    precision,
645                    scale,
646                    decimal_comma,
647                )),
648                &DataType::String => {
649                    Builder::Utf8(Utf8Field::new(name, capacity, quote_char, encoding))
650                },
651                #[cfg(feature = "dtype-datetime")]
652                DataType::Datetime(time_unit, time_zone) => Builder::Datetime {
653                    buf: DatetimeField::new(name, capacity),
654                    time_unit: *time_unit,
655                    time_zone: time_zone.clone(),
656                },
657                #[cfg(feature = "dtype-date")]
658                &DataType::Date => Builder::Date(DatetimeField::new(name, capacity)),
659                #[cfg(feature = "dtype-categorical")]
660                DataType::Categorical(_, _) | DataType::Enum(_, _) => {
661                    match dtype.cat_physical().unwrap() {
662                        CategoricalPhysical::U8 => {
663                            Builder::Categorical8(CategoricalField::<Categorical8Type>::new(
664                                name,
665                                capacity,
666                                quote_char,
667                                dtype.clone(),
668                            ))
669                        },
670                        CategoricalPhysical::U16 => {
671                            Builder::Categorical16(CategoricalField::<Categorical16Type>::new(
672                                name,
673                                capacity,
674                                quote_char,
675                                dtype.clone(),
676                            ))
677                        },
678                        CategoricalPhysical::U32 => {
679                            Builder::Categorical32(CategoricalField::<Categorical32Type>::new(
680                                name,
681                                capacity,
682                                quote_char,
683                                dtype.clone(),
684                            ))
685                        },
686                    }
687                },
688                dt => polars_bail!(
689                    ComputeError: "unsupported data type when reading CSV: {}", dt,
690                ),
691            };
692            Ok(builder)
693        })
694        .collect()
695}
696
697#[allow(clippy::large_enum_variant)]
698pub enum Builder {
699    Boolean(BooleanChunkedBuilder),
700    #[cfg(feature = "dtype-i8")]
701    Int8(PrimitiveChunkedBuilder<Int8Type>),
702    #[cfg(feature = "dtype-i16")]
703    Int16(PrimitiveChunkedBuilder<Int16Type>),
704    Int32(PrimitiveChunkedBuilder<Int32Type>),
705    Int64(PrimitiveChunkedBuilder<Int64Type>),
706    #[cfg(feature = "dtype-i128")]
707    Int128(PrimitiveChunkedBuilder<Int128Type>),
708    #[cfg(feature = "dtype-u8")]
709    UInt8(PrimitiveChunkedBuilder<UInt8Type>),
710    #[cfg(feature = "dtype-u16")]
711    UInt16(PrimitiveChunkedBuilder<UInt16Type>),
712    UInt32(PrimitiveChunkedBuilder<UInt32Type>),
713    UInt64(PrimitiveChunkedBuilder<UInt64Type>),
714    #[cfg(feature = "dtype-u128")]
715    UInt128(PrimitiveChunkedBuilder<UInt128Type>),
716    #[cfg(feature = "dtype-f16")]
717    Float16(PrimitiveChunkedBuilder<Float16Type>),
718    Float32(PrimitiveChunkedBuilder<Float32Type>),
719    Float64(PrimitiveChunkedBuilder<Float64Type>),
720    #[cfg(feature = "dtype-decimal")]
721    Decimal(DecimalField),
722    /// Stores the Utf8 fields and the total string length seen for that column
723    Utf8(Utf8Field),
724    #[cfg(feature = "dtype-datetime")]
725    Datetime {
726        buf: DatetimeField<Int64Type>,
727        time_unit: TimeUnit,
728        time_zone: Option<TimeZone>,
729    },
730    #[cfg(feature = "dtype-date")]
731    Date(DatetimeField<Int32Type>),
732    #[cfg(feature = "dtype-categorical")]
733    Categorical8(CategoricalField<Categorical8Type>),
734    #[cfg(feature = "dtype-categorical")]
735    Categorical16(CategoricalField<Categorical16Type>),
736    #[cfg(feature = "dtype-categorical")]
737    Categorical32(CategoricalField<Categorical32Type>),
738    #[cfg(feature = "dtype-f16")]
739    DecimalFloat16(PrimitiveChunkedBuilder<Float16Type>, Vec<u8>),
740    DecimalFloat32(PrimitiveChunkedBuilder<Float32Type>, Vec<u8>),
741    DecimalFloat64(PrimitiveChunkedBuilder<Float64Type>, Vec<u8>),
742}
743
744impl Builder {
745    pub fn into_series(self) -> PolarsResult<Series> {
746        let s = match self {
747            Builder::Boolean(v) => v.finish().into_series(),
748            #[cfg(feature = "dtype-i8")]
749            Builder::Int8(v) => v.finish().into_series(),
750            #[cfg(feature = "dtype-i16")]
751            Builder::Int16(v) => v.finish().into_series(),
752            Builder::Int32(v) => v.finish().into_series(),
753            Builder::Int64(v) => v.finish().into_series(),
754            #[cfg(feature = "dtype-i128")]
755            Builder::Int128(v) => v.finish().into_series(),
756            #[cfg(feature = "dtype-u8")]
757            Builder::UInt8(v) => v.finish().into_series(),
758            #[cfg(feature = "dtype-u16")]
759            Builder::UInt16(v) => v.finish().into_series(),
760            Builder::UInt32(v) => v.finish().into_series(),
761            Builder::UInt64(v) => v.finish().into_series(),
762            #[cfg(feature = "dtype-u128")]
763            Builder::UInt128(v) => v.finish().into_series(),
764            #[cfg(feature = "dtype-f16")]
765            Builder::Float16(v) => v.finish().into_series(),
766            Builder::Float32(v) => v.finish().into_series(),
767            Builder::Float64(v) => v.finish().into_series(),
768            #[cfg(feature = "dtype-f16")]
769            Builder::DecimalFloat16(v, _) => v.finish().into_series(),
770            Builder::DecimalFloat32(v, _) => v.finish().into_series(),
771            Builder::DecimalFloat64(v, _) => v.finish().into_series(),
772            #[cfg(feature = "dtype-decimal")]
773            Builder::Decimal(DecimalField {
774                builder,
775                precision,
776                scale,
777                ..
778            }) => unsafe {
779                builder
780                    .finish()
781                    .into_series()
782                    .from_physical_unchecked(&DataType::Decimal(precision, scale))
783                    .unwrap()
784            },
785            #[cfg(feature = "dtype-datetime")]
786            Builder::Datetime {
787                buf,
788                time_unit,
789                time_zone,
790            } => buf
791                .builder
792                .finish()
793                .into_series()
794                .cast(&DataType::Datetime(time_unit, time_zone))
795                .unwrap(),
796            #[cfg(feature = "dtype-date")]
797            Builder::Date(v) => v
798                .builder
799                .finish()
800                .into_series()
801                .cast(&DataType::Date)
802                .unwrap(),
803
804            Builder::Utf8(v) => {
805                let arr = v.mutable.freeze();
806                StringChunked::with_chunk(v.name, unsafe { arr.to_utf8view_unchecked() })
807                    .into_series()
808            },
809            #[cfg(feature = "dtype-categorical")]
810            Builder::Categorical8(buf) => buf.builder.finish().into_series(),
811            #[cfg(feature = "dtype-categorical")]
812            Builder::Categorical16(buf) => buf.builder.finish().into_series(),
813            #[cfg(feature = "dtype-categorical")]
814            Builder::Categorical32(buf) => buf.builder.finish().into_series(),
815        };
816        Ok(s)
817    }
818
819    pub fn add_null(&mut self, valid: bool) {
820        match self {
821            Builder::Boolean(v) => v.append_null(),
822            #[cfg(feature = "dtype-i8")]
823            Builder::Int8(v) => v.append_null(),
824            #[cfg(feature = "dtype-i16")]
825            Builder::Int16(v) => v.append_null(),
826            Builder::Int32(v) => v.append_null(),
827            Builder::Int64(v) => v.append_null(),
828            #[cfg(feature = "dtype-i128")]
829            Builder::Int128(v) => v.append_null(),
830            #[cfg(feature = "dtype-u8")]
831            Builder::UInt8(v) => v.append_null(),
832            #[cfg(feature = "dtype-u16")]
833            Builder::UInt16(v) => v.append_null(),
834            Builder::UInt32(v) => v.append_null(),
835            Builder::UInt64(v) => v.append_null(),
836            #[cfg(feature = "dtype-u128")]
837            Builder::UInt128(v) => v.append_null(),
838            #[cfg(feature = "dtype-f16")]
839            Builder::Float16(v) => v.append_null(),
840            Builder::Float32(v) => v.append_null(),
841            Builder::Float64(v) => v.append_null(),
842            #[cfg(feature = "dtype-decimal")]
843            Builder::Decimal(buf) => buf.builder.append_null(),
844            #[cfg(feature = "dtype-f16")]
845            Builder::DecimalFloat16(v, _) => v.append_null(),
846            Builder::DecimalFloat32(v, _) => v.append_null(),
847            Builder::DecimalFloat64(v, _) => v.append_null(),
848            Builder::Utf8(v) => {
849                if valid {
850                    v.mutable.push_value("")
851                } else {
852                    v.mutable.push_null()
853                }
854            },
855            #[cfg(feature = "dtype-datetime")]
856            Builder::Datetime { buf, .. } => buf.builder.append_null(),
857            #[cfg(feature = "dtype-date")]
858            Builder::Date(v) => v.builder.append_null(),
859            #[cfg(feature = "dtype-categorical")]
860            Builder::Categorical8(buf) => buf.builder.append_null(),
861            #[cfg(feature = "dtype-categorical")]
862            Builder::Categorical16(buf) => buf.builder.append_null(),
863            #[cfg(feature = "dtype-categorical")]
864            Builder::Categorical32(buf) => buf.builder.append_null(),
865        };
866    }
867
868    pub fn dtype(&self) -> DataType {
869        match self {
870            Builder::Boolean(_) => DataType::Boolean,
871            #[cfg(feature = "dtype-i8")]
872            Builder::Int8(_) => DataType::Int8,
873            #[cfg(feature = "dtype-i16")]
874            Builder::Int16(_) => DataType::Int16,
875            Builder::Int32(_) => DataType::Int32,
876            Builder::Int64(_) => DataType::Int64,
877            #[cfg(feature = "dtype-i128")]
878            Builder::Int128(_) => DataType::Int128,
879            #[cfg(feature = "dtype-u8")]
880            Builder::UInt8(_) => DataType::UInt8,
881            #[cfg(feature = "dtype-u16")]
882            Builder::UInt16(_) => DataType::UInt16,
883            Builder::UInt32(_) => DataType::UInt32,
884            Builder::UInt64(_) => DataType::UInt64,
885            #[cfg(feature = "dtype-u128")]
886            Builder::UInt128(_) => DataType::UInt128,
887            #[cfg(feature = "dtype-f16")]
888            Builder::Float16(_) | Builder::DecimalFloat16(_, _) => DataType::Float16,
889            Builder::Float32(_) | Builder::DecimalFloat32(_, _) => DataType::Float32,
890            Builder::Float64(_) | Builder::DecimalFloat64(_, _) => DataType::Float64,
891            #[cfg(feature = "dtype-decimal")]
892            Builder::Decimal(DecimalField {
893                precision, scale, ..
894            }) => DataType::Decimal(*precision, *scale),
895            Builder::Utf8(_) => DataType::String,
896            #[cfg(feature = "dtype-datetime")]
897            Builder::Datetime { time_unit, .. } => DataType::Datetime(*time_unit, None),
898            #[cfg(feature = "dtype-date")]
899            Builder::Date(_) => DataType::Date,
900            #[cfg(feature = "dtype-categorical")]
901            Builder::Categorical8(buf) => buf.builder.dtype().clone(),
902            #[cfg(feature = "dtype-categorical")]
903            Builder::Categorical16(buf) => buf.builder.dtype().clone(),
904            #[cfg(feature = "dtype-categorical")]
905            Builder::Categorical32(buf) => buf.builder.dtype().clone(),
906        }
907    }
908
909    #[inline]
910    pub fn add(
911        &mut self,
912        bytes: &[u8],
913        ignore_errors: bool,
914        needs_escaping: bool,
915        missing_is_null: bool,
916    ) -> PolarsResult<()> {
917        use Builder::*;
918        match self {
919            Boolean(buf) => <BooleanChunkedBuilder as ParsedBuilder>::parse_bytes(
920                buf,
921                bytes,
922                ignore_errors,
923                needs_escaping,
924                missing_is_null,
925                None,
926            ),
927            #[cfg(feature = "dtype-i8")]
928            Int8(buf) => <PrimitiveChunkedBuilder<Int8Type> as ParsedBuilder>::parse_bytes(
929                buf,
930                bytes,
931                ignore_errors,
932                needs_escaping,
933                missing_is_null,
934                None,
935            ),
936            #[cfg(feature = "dtype-i16")]
937            Int16(buf) => <PrimitiveChunkedBuilder<Int16Type> as ParsedBuilder>::parse_bytes(
938                buf,
939                bytes,
940                ignore_errors,
941                needs_escaping,
942                missing_is_null,
943                None,
944            ),
945            Int32(buf) => <PrimitiveChunkedBuilder<Int32Type> as ParsedBuilder>::parse_bytes(
946                buf,
947                bytes,
948                ignore_errors,
949                needs_escaping,
950                missing_is_null,
951                None,
952            ),
953            Int64(buf) => <PrimitiveChunkedBuilder<Int64Type> as ParsedBuilder>::parse_bytes(
954                buf,
955                bytes,
956                ignore_errors,
957                needs_escaping,
958                missing_is_null,
959                None,
960            ),
961            #[cfg(feature = "dtype-i128")]
962            Int128(buf) => <PrimitiveChunkedBuilder<Int128Type> as ParsedBuilder>::parse_bytes(
963                buf,
964                bytes,
965                ignore_errors,
966                needs_escaping,
967                missing_is_null,
968                None,
969            ),
970            #[cfg(feature = "dtype-u8")]
971            UInt8(buf) => <PrimitiveChunkedBuilder<UInt8Type> as ParsedBuilder>::parse_bytes(
972                buf,
973                bytes,
974                ignore_errors,
975                needs_escaping,
976                missing_is_null,
977                None,
978            ),
979            #[cfg(feature = "dtype-u16")]
980            UInt16(buf) => <PrimitiveChunkedBuilder<UInt16Type> as ParsedBuilder>::parse_bytes(
981                buf,
982                bytes,
983                ignore_errors,
984                needs_escaping,
985                missing_is_null,
986                None,
987            ),
988            UInt32(buf) => <PrimitiveChunkedBuilder<UInt32Type> as ParsedBuilder>::parse_bytes(
989                buf,
990                bytes,
991                ignore_errors,
992                needs_escaping,
993                missing_is_null,
994                None,
995            ),
996            UInt64(buf) => <PrimitiveChunkedBuilder<UInt64Type> as ParsedBuilder>::parse_bytes(
997                buf,
998                bytes,
999                ignore_errors,
1000                needs_escaping,
1001                missing_is_null,
1002                None,
1003            ),
1004            #[cfg(feature = "dtype-u128")]
1005            UInt128(buf) => <PrimitiveChunkedBuilder<UInt128Type> as ParsedBuilder>::parse_bytes(
1006                buf,
1007                bytes,
1008                ignore_errors,
1009                needs_escaping,
1010                missing_is_null,
1011                None,
1012            ),
1013            #[cfg(feature = "dtype-f16")]
1014            Float16(buf) => <PrimitiveChunkedBuilder<Float16Type> as ParsedBuilder>::parse_bytes(
1015                buf,
1016                bytes,
1017                ignore_errors,
1018                needs_escaping,
1019                missing_is_null,
1020                None,
1021            ),
1022            Float32(buf) => <PrimitiveChunkedBuilder<Float32Type> as ParsedBuilder>::parse_bytes(
1023                buf,
1024                bytes,
1025                ignore_errors,
1026                needs_escaping,
1027                missing_is_null,
1028                None,
1029            ),
1030            Float64(buf) => <PrimitiveChunkedBuilder<Float64Type> as ParsedBuilder>::parse_bytes(
1031                buf,
1032                bytes,
1033                ignore_errors,
1034                needs_escaping,
1035                missing_is_null,
1036                None,
1037            ),
1038            #[cfg(feature = "dtype-f16")]
1039            DecimalFloat16(buf, scratch) => {
1040                prepare_decimal_comma(bytes, scratch);
1041                <PrimitiveChunkedBuilder<Float16Type> as ParsedBuilder>::parse_bytes(
1042                    buf,
1043                    scratch,
1044                    ignore_errors,
1045                    needs_escaping,
1046                    missing_is_null,
1047                    None,
1048                )
1049            },
1050            DecimalFloat32(buf, scratch) => {
1051                prepare_decimal_comma(bytes, scratch);
1052                <PrimitiveChunkedBuilder<Float32Type> as ParsedBuilder>::parse_bytes(
1053                    buf,
1054                    scratch,
1055                    ignore_errors,
1056                    needs_escaping,
1057                    missing_is_null,
1058                    None,
1059                )
1060            },
1061            DecimalFloat64(buf, scratch) => {
1062                prepare_decimal_comma(bytes, scratch);
1063                <PrimitiveChunkedBuilder<Float64Type> as ParsedBuilder>::parse_bytes(
1064                    buf,
1065                    scratch,
1066                    ignore_errors,
1067                    needs_escaping,
1068                    missing_is_null,
1069                    None,
1070                )
1071            },
1072            #[cfg(feature = "dtype-decimal")]
1073            Decimal(buf) => <DecimalField as ParsedBuilder>::parse_bytes(
1074                buf,
1075                bytes,
1076                ignore_errors,
1077                needs_escaping,
1078                missing_is_null,
1079                None,
1080            ),
1081            Utf8(buf) => <Utf8Field as ParsedBuilder>::parse_bytes(
1082                buf,
1083                bytes,
1084                ignore_errors,
1085                needs_escaping,
1086                missing_is_null,
1087                None,
1088            ),
1089            #[cfg(feature = "dtype-datetime")]
1090            Datetime { buf, time_unit, .. } => {
1091                <DatetimeField<Int64Type> as ParsedBuilder>::parse_bytes(
1092                    buf,
1093                    bytes,
1094                    ignore_errors,
1095                    needs_escaping,
1096                    missing_is_null,
1097                    Some(*time_unit),
1098                )
1099            },
1100            #[cfg(feature = "dtype-date")]
1101            Date(buf) => <DatetimeField<Int32Type> as ParsedBuilder>::parse_bytes(
1102                buf,
1103                bytes,
1104                ignore_errors,
1105                needs_escaping,
1106                missing_is_null,
1107                None,
1108            ),
1109            #[cfg(feature = "dtype-categorical")]
1110            Categorical8(buf) => {
1111                buf.parse_bytes(bytes, ignore_errors, needs_escaping, missing_is_null, None)
1112            },
1113            #[cfg(feature = "dtype-categorical")]
1114            Categorical16(buf) => {
1115                buf.parse_bytes(bytes, ignore_errors, needs_escaping, missing_is_null, None)
1116            },
1117            #[cfg(feature = "dtype-categorical")]
1118            Categorical32(buf) => {
1119                buf.parse_bytes(bytes, ignore_errors, needs_escaping, missing_is_null, None)
1120            },
1121        }
1122    }
1123}
1124
1125/// Adds the fields of one column, `None` being a field that is not in its line. Returns the row and
1126/// error of the first field that fails.
1127#[allow(clippy::too_many_arguments)]
1128#[inline(always)]
1129fn add_fields<'a, B: ?Sized>(
1130    buf: &mut B,
1131    fields: impl Iterator<Item = Option<(&'a [u8], bool)>>,
1132    column_idx: usize,
1133    null_values: Option<&NullValuesCompiled>,
1134    missing_is_null: bool,
1135    mut add: impl FnMut(&mut B, &[u8], bool) -> PolarsResult<()>,
1136    mut add_null: impl FnMut(&mut B, bool),
1137) -> Result<(), (usize, PolarsError)> {
1138    for (row, field) in fields.enumerate() {
1139        let Some((field, needs_escaping)) = field else {
1140            add_null(buf, !missing_is_null);
1141            continue;
1142        };
1143        if let Some(null_values) = null_values {
1144            let unquoted = if needs_escaping && field.len() >= 2 {
1145                &field[1..field.len() - 1]
1146            } else {
1147                field
1148            };
1149            // SAFETY: the caller ensures `column_idx` is in bounds.
1150            if unsafe { null_values.is_null(unquoted, column_idx) } {
1151                add_null(buf, !missing_is_null && field.is_empty());
1152                continue;
1153            }
1154        }
1155        add(buf, field, needs_escaping).map_err(|e| (row, e))?;
1156    }
1157    Ok(())
1158}
1159
1160impl Builder {
1161    /// Adds the fields of one column, `None` being a field that is not in its line. Returns the
1162    /// row and error of the first field that fails.
1163    ///
1164    /// # Safety
1165    /// `column_idx` must be in bounds of the per column `null_values`.
1166    pub(super) unsafe fn add_column<'a>(
1167        &mut self,
1168        fields: impl Iterator<Item = Option<(&'a [u8], bool)>>,
1169        column_idx: usize,
1170        null_values: Option<&NullValuesCompiled>,
1171        ignore_errors: bool,
1172        missing_is_null: bool,
1173    ) -> Result<(), (usize, PolarsError)> {
1174        macro_rules! add_parsed {
1175            ($buf:expr, $time_unit:expr, $add_null:expr) => {
1176                add_fields(
1177                    $buf,
1178                    fields,
1179                    column_idx,
1180                    null_values,
1181                    missing_is_null,
1182                    |b, field, needs_escaping| {
1183                        ParsedBuilder::parse_bytes(
1184                            b,
1185                            field,
1186                            ignore_errors,
1187                            needs_escaping,
1188                            missing_is_null,
1189                            $time_unit,
1190                        )
1191                    },
1192                    $add_null,
1193                )
1194            };
1195        }
1196
1197        use Builder::*;
1198        match self {
1199            Boolean(buf) => add_parsed!(buf, None, |b, _| b.append_null()),
1200            Int32(buf) => add_parsed!(buf, None, |b, _| b.append_null()),
1201            Int64(buf) => add_parsed!(buf, None, |b, _| b.append_null()),
1202            UInt32(buf) => add_parsed!(buf, None, |b, _| b.append_null()),
1203            UInt64(buf) => add_parsed!(buf, None, |b, _| b.append_null()),
1204            Float32(buf) => add_parsed!(buf, None, |b, _| b.append_null()),
1205            Float64(buf) => add_parsed!(buf, None, |b, _| b.append_null()),
1206            Utf8(buf) => add_parsed!(buf, None, |b, valid| if valid {
1207                b.mutable.push_value("")
1208            } else {
1209                b.mutable.push_null()
1210            }),
1211            #[cfg(feature = "dtype-datetime")]
1212            Datetime { buf, time_unit, .. } => {
1213                let time_unit = *time_unit;
1214                add_parsed!(buf, Some(time_unit), |b, _| b.builder.append_null())
1215            },
1216            #[cfg(feature = "dtype-date")]
1217            Date(buf) => add_parsed!(buf, None, |b, _| b.builder.append_null()),
1218            _ => add_fields(
1219                self,
1220                fields,
1221                column_idx,
1222                null_values,
1223                missing_is_null,
1224                |b, field, needs_escaping| {
1225                    b.add(field, ignore_errors, needs_escaping, missing_is_null)
1226                },
1227                |b, valid| b.add_null(valid),
1228            ),
1229        }
1230    }
1231
1232    pub(super) fn is_categorical(&self) -> bool {
1233        #[cfg(feature = "dtype-categorical")]
1234        return matches!(
1235            self,
1236            Builder::Categorical8(_) | Builder::Categorical16(_) | Builder::Categorical32(_)
1237        );
1238        #[cfg(not(feature = "dtype-categorical"))]
1239        false
1240    }
1241}
1242
1243#[inline]
1244fn prepare_decimal_comma(bytes: &[u8], scratch: &mut Vec<u8>) {
1245    scratch.clear();
1246    scratch.reserve(bytes.len());
1247
1248    // SAFETY: we pre-allocated.
1249    for &byte in bytes {
1250        if byte == b',' {
1251            unsafe { scratch.push_unchecked(b'.') }
1252        } else {
1253            unsafe { scratch.push_unchecked(byte) }
1254        }
1255    }
1256}