polars_io/csv/read/
splitfields.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
#[cfg(not(feature = "simd"))]
mod inner {
    /// An adapted version of std::iter::Split.
    /// This exists solely because we cannot split the lines naively as
    pub(crate) struct SplitFields<'a> {
        v: &'a [u8],
        separator: u8,
        finished: bool,
        quote_char: u8,
        quoting: bool,
        eol_char: u8,
    }

    impl<'a> SplitFields<'a> {
        pub(crate) fn new(
            slice: &'a [u8],
            separator: u8,
            quote_char: Option<u8>,
            eol_char: u8,
        ) -> Self {
            Self {
                v: slice,
                separator,
                finished: false,
                quote_char: quote_char.unwrap_or(b'"'),
                quoting: quote_char.is_some(),
                eol_char,
            }
        }

        unsafe fn finish_eol(
            &mut self,
            need_escaping: bool,
            idx: usize,
        ) -> Option<(&'a [u8], bool)> {
            self.finished = true;
            debug_assert!(idx <= self.v.len());
            Some((self.v.get_unchecked(..idx), need_escaping))
        }

        fn finish(&mut self, need_escaping: bool) -> Option<(&'a [u8], bool)> {
            self.finished = true;
            Some((self.v, need_escaping))
        }

        fn eof_oel(&self, current_ch: u8) -> bool {
            current_ch == self.separator || current_ch == self.eol_char
        }
    }

    impl<'a> Iterator for SplitFields<'a> {
        // the bool is used to indicate that it requires escaping
        type Item = (&'a [u8], bool);

        #[inline]
        fn next(&mut self) -> Option<(&'a [u8], bool)> {
            if self.finished {
                return None;
            } else if self.v.is_empty() {
                return self.finish(false);
            }

            let mut needs_escaping = false;
            // There can be strings with separators:
            // "Street, City",

            // SAFETY:
            // we have checked bounds
            let pos = if self.quoting && unsafe { *self.v.get_unchecked(0) } == self.quote_char {
                needs_escaping = true;
                // There can be pair of double-quotes within string.
                // Each of the embedded double-quote characters must be represented
                // by a pair of double-quote characters:
                // e.g. 1997,Ford,E350,"Super, ""luxurious"" truck",20020

                // denotes if we are in a string field, started with a quote
                let mut in_field = false;

                let mut idx = 0u32;
                let mut current_idx = 0u32;
                // micro optimizations
                #[allow(clippy::explicit_counter_loop)]
                for &c in self.v.iter() {
                    if c == self.quote_char {
                        // toggle between string field enclosure
                        //      if we encounter a starting '"' -> in_field = true;
                        //      if we encounter a closing '"' -> in_field = false;
                        in_field = !in_field;
                    }

                    if !in_field && self.eof_oel(c) {
                        if c == self.eol_char {
                            // SAFETY:
                            // we are in bounds
                            return unsafe {
                                self.finish_eol(needs_escaping, current_idx as usize)
                            };
                        }
                        idx = current_idx;
                        break;
                    }
                    current_idx += 1;
                }

                if idx == 0 {
                    return self.finish(needs_escaping);
                }

                idx as usize
            } else {
                match self.v.iter().position(|&c| self.eof_oel(c)) {
                    None => return self.finish(needs_escaping),
                    Some(idx) => unsafe {
                        // SAFETY:
                        // idx was just found
                        if *self.v.get_unchecked(idx) == self.eol_char {
                            return self.finish_eol(needs_escaping, idx);
                        } else {
                            idx
                        }
                    },
                }
            };

            unsafe {
                debug_assert!(pos <= self.v.len());
                // SAFETY:
                // we are in bounds
                let ret = Some((self.v.get_unchecked(..pos), needs_escaping));
                self.v = self.v.get_unchecked(pos + 1..);
                ret
            }
        }
    }
}

#[cfg(feature = "simd")]
mod inner {
    use std::simd::prelude::*;

    use polars_utils::clmul::prefix_xorsum_inclusive;

    const SIMD_SIZE: usize = 64;
    type SimdVec = u8x64;

    /// An adapted version of std::iter::Split.
    /// This exists solely because we cannot split the lines naively as
    pub(crate) struct SplitFields<'a> {
        pub v: &'a [u8],
        separator: u8,
        pub finished: bool,
        quote_char: u8,
        quoting: bool,
        eol_char: u8,
        simd_separator: SimdVec,
        simd_eol_char: SimdVec,
        simd_quote_char: SimdVec,
        previous_valid_ends: u64,
    }

    impl<'a> SplitFields<'a> {
        pub(crate) fn new(
            slice: &'a [u8],
            separator: u8,
            quote_char: Option<u8>,
            eol_char: u8,
        ) -> Self {
            let simd_separator = SimdVec::splat(separator);
            let simd_eol_char = SimdVec::splat(eol_char);
            let quoting = quote_char.is_some();
            let quote_char = quote_char.unwrap_or(b'"');
            let simd_quote_char = SimdVec::splat(quote_char);

            Self {
                v: slice,
                separator,
                finished: false,
                quote_char,
                quoting,
                eol_char,
                simd_separator,
                simd_eol_char,
                simd_quote_char,
                previous_valid_ends: 0,
            }
        }

        unsafe fn finish_eol(
            &mut self,
            need_escaping: bool,
            pos: usize,
        ) -> Option<(&'a [u8], bool)> {
            self.finished = true;
            debug_assert!(pos <= self.v.len());
            Some((self.v.get_unchecked(..pos), need_escaping))
        }

        #[inline]
        fn finish(&mut self, need_escaping: bool) -> Option<(&'a [u8], bool)> {
            self.finished = true;
            Some((self.v, need_escaping))
        }

        fn eof_oel(&self, current_ch: u8) -> bool {
            current_ch == self.separator || current_ch == self.eol_char
        }
    }

    impl<'a> Iterator for SplitFields<'a> {
        // the bool is used to indicate that it requires escaping
        type Item = (&'a [u8], bool);

        #[inline]
        fn next(&mut self) -> Option<(&'a [u8], bool)> {
            // This must be before we check the cached value
            if self.finished {
                return None;
            }
            // Then check cached value as this is hot.
            if self.previous_valid_ends != 0 {
                let pos = self.previous_valid_ends.trailing_zeros() as usize;
                self.previous_valid_ends >>= (pos + 1) as u64;

                unsafe {
                    debug_assert!(pos < self.v.len());
                    // SAFETY:
                    // we are in bounds
                    let needs_escaping = self
                        .v
                        .first()
                        .map(|c| *c == self.quote_char && self.quoting)
                        .unwrap_or(false);

                    if *self.v.get_unchecked(pos) == self.eol_char {
                        return self.finish_eol(needs_escaping, pos);
                    }

                    let bytes = self.v.get_unchecked(..pos);

                    self.v = self.v.get_unchecked(pos + 1..);
                    let ret = Some((bytes, needs_escaping));

                    return ret;
                }
            }
            if self.v.is_empty() {
                return self.finish(false);
            }

            let mut needs_escaping = false;
            // There can be strings with separators:
            // "Street, City",

            // SAFETY:
            // we have checked bounds
            let pos = if self.quoting && unsafe { *self.v.get_unchecked(0) } == self.quote_char {
                let mut total_idx = 0;
                needs_escaping = true;
                let mut not_in_field_previous_iter = true;

                loop {
                    let bytes = unsafe { self.v.get_unchecked(total_idx..) };

                    if bytes.len() > SIMD_SIZE {
                        let lane: [u8; SIMD_SIZE] = unsafe {
                            bytes
                                .get_unchecked(0..SIMD_SIZE)
                                .try_into()
                                .unwrap_unchecked()
                        };
                        let simd_bytes = SimdVec::from(lane);
                        let has_eol = simd_bytes.simd_eq(self.simd_eol_char);
                        let has_sep = simd_bytes.simd_eq(self.simd_separator);
                        let quote_mask = simd_bytes.simd_eq(self.simd_quote_char).to_bitmask();
                        let mut end_mask = (has_sep | has_eol).to_bitmask();

                        let mut not_in_quote_field = prefix_xorsum_inclusive(quote_mask);

                        if not_in_field_previous_iter {
                            not_in_quote_field = !not_in_quote_field;
                        }
                        not_in_field_previous_iter =
                            (not_in_quote_field & (1 << (SIMD_SIZE - 1))) > 0;
                        end_mask &= not_in_quote_field;

                        if end_mask != 0 {
                            let pos = end_mask.trailing_zeros() as usize;
                            total_idx += pos;
                            debug_assert!(
                                self.v[total_idx] == self.eol_char
                                    || self.v[total_idx] == self.separator
                            );

                            if pos == SIMD_SIZE - 1 {
                                self.previous_valid_ends = 0;
                            } else {
                                self.previous_valid_ends = end_mask >> (pos + 1) as u64;
                            }

                            break;
                        } else {
                            total_idx += SIMD_SIZE;
                        }
                    } else {
                        // There can be a pair of double-quotes within a string.
                        // Each of the embedded double-quote characters must be represented
                        // by a pair of double-quote characters:
                        // e.g. 1997,Ford,E350,"Super, ""luxurious"" truck",20020

                        // denotes if we are in a string field, started with a quote
                        let mut in_field = !not_in_field_previous_iter;

                        // usize::MAX is unset.
                        let mut idx = usize::MAX;
                        let mut current_idx = 0;
                        // micro optimizations
                        #[allow(clippy::explicit_counter_loop)]
                        for &c in bytes.iter() {
                            if c == self.quote_char {
                                // toggle between string field enclosure
                                //      if we encounter a starting '"' -> in_field = true;
                                //      if we encounter a closing '"' -> in_field = false;
                                in_field = !in_field;
                            }

                            if !in_field && self.eof_oel(c) {
                                if c == self.eol_char {
                                    // SAFETY:
                                    // we are in bounds
                                    return unsafe {
                                        self.finish_eol(needs_escaping, current_idx + total_idx)
                                    };
                                }
                                idx = current_idx;
                                break;
                            }
                            current_idx += 1;
                        }

                        if idx == usize::MAX {
                            return self.finish(needs_escaping);
                        }

                        total_idx += idx;
                        debug_assert!(
                            self.v[total_idx] == self.eol_char
                                || self.v[total_idx] == self.separator
                        );
                        break;
                    }
                }
                total_idx
            } else {
                let mut total_idx = 0;

                loop {
                    let bytes = unsafe { self.v.get_unchecked(total_idx..) };

                    if bytes.len() > SIMD_SIZE {
                        let lane: [u8; SIMD_SIZE] = unsafe {
                            bytes
                                .get_unchecked(0..SIMD_SIZE)
                                .try_into()
                                .unwrap_unchecked()
                        };
                        let simd_bytes = SimdVec::from(lane);
                        let has_eol_char = simd_bytes.simd_eq(self.simd_eol_char);
                        let has_separator = simd_bytes.simd_eq(self.simd_separator);
                        let has_any_mask = (has_separator | has_eol_char).to_bitmask();

                        if has_any_mask != 0 {
                            total_idx += has_any_mask.trailing_zeros() as usize;
                            break;
                        } else {
                            total_idx += SIMD_SIZE;
                        }
                    } else {
                        match bytes.iter().position(|&c| self.eof_oel(c)) {
                            None => return self.finish(needs_escaping),
                            Some(idx) => {
                                total_idx += idx;
                                break;
                            },
                        }
                    }
                }
                unsafe {
                    if *self.v.get_unchecked(total_idx) == self.eol_char {
                        return self.finish_eol(needs_escaping, total_idx);
                    } else {
                        total_idx
                    }
                }
            };

            unsafe {
                debug_assert!(pos < self.v.len());
                // SAFETY:
                // we are in bounds
                let ret = Some((self.v.get_unchecked(..pos), needs_escaping));
                self.v = self.v.get_unchecked(pos + 1..);
                ret
            }
        }
    }
}

pub(crate) use inner::SplitFields;

#[cfg(test)]
mod test {
    use super::SplitFields;

    #[test]
    fn test_splitfields() {
        let input = "\"foo\",\"bar\"";
        let mut fields = SplitFields::new(input.as_bytes(), b',', Some(b'"'), b'\n');

        assert_eq!(fields.next(), Some(("\"foo\"".as_bytes(), true)));
        assert_eq!(fields.next(), Some(("\"bar\"".as_bytes(), true)));
        assert_eq!(fields.next(), None);

        let input2 = "\"foo\n bar\";\"baz\";12345";
        let mut fields2 = SplitFields::new(input2.as_bytes(), b';', Some(b'"'), b'\n');

        assert_eq!(fields2.next(), Some(("\"foo\n bar\"".as_bytes(), true)));
        assert_eq!(fields2.next(), Some(("\"baz\"".as_bytes(), true)));
        assert_eq!(fields2.next(), Some(("12345".as_bytes(), false)));
        assert_eq!(fields2.next(), None);
    }
}