Skip to main content

simd_csv/
records.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::hash::{Hash, Hasher};
4use std::io::Write;
5use std::ops::Index;
6
7use crate::debug;
8use crate::utils::{trim_trailing_crlf, unescape, unescape_to, unquoted, AppendOnlyView};
9
10#[cfg(feature = "str")]
11use crate::error::{self, Error, ErrorKind};
12
13/// A view of a CSV record into a [`ZeroCopyReader`](crate::ZeroCopyReader) buffer.
14pub struct ZeroCopyByteRecord<'a> {
15    slice: &'a [u8],
16    seps: &'a [usize],
17    pub(crate) quote: u8,
18}
19
20impl<'a> ZeroCopyByteRecord<'a> {
21    #[inline]
22    pub(crate) fn new(slice: &'a [u8], seps: &'a [usize], quote: u8) -> Self {
23        Self {
24            slice: trim_trailing_crlf(slice),
25            seps,
26            quote,
27        }
28    }
29
30    #[inline]
31    pub(crate) fn to_parts(&self) -> (Vec<usize>, Vec<u8>) {
32        (self.seps.to_vec(), self.slice.to_vec())
33    }
34
35    /// Number of fields of the record. Cannot be less than 1 since a CSV with no
36    /// columns does not make sense.
37    #[inline(always)]
38    pub fn len(&self) -> usize {
39        // NOTE: an empty zero copy record cannot be constructed,
40        // by definition.
41        self.seps.len() + 1
42    }
43
44    /// Returns whether the record has no fields.
45    #[inline(always)]
46    pub fn is_empty(&self) -> bool {
47        false
48    }
49
50    /// Returns the underlying byte slice, delimiters and all.
51    #[inline(always)]
52    pub fn as_slice(&self) -> &[u8] {
53        self.slice
54    }
55
56    /// Returns an iterator over the record's fields, as-is.
57    ///
58    /// This means fields might or might not be quoted and
59    /// field bytes have not been unescaped at all.
60    #[inline]
61    pub fn iter(&self) -> ZeroCopyByteRecordIter<'_> {
62        ZeroCopyByteRecordIter {
63            record: self,
64            current_forward: 0,
65            current_backward: self.len(),
66        }
67    }
68
69    /// Returns an iterator over the record's fields, unquoted.
70    ///
71    /// See [`Self::unquote`] for more detail.
72    #[inline]
73    pub fn unquoted_iter(&self) -> ZeroCopyByteRecordUnquotedIter<'_> {
74        ZeroCopyByteRecordUnquotedIter {
75            record: self,
76            current_forward: 0,
77            current_backward: self.len(),
78        }
79    }
80
81    /// Returns an iterator over the record's fields, unescaped.
82    ///
83    /// See [`Self::unescape`] for more detail.
84    #[inline]
85    pub fn unescaped_iter(&self) -> ZeroCopyByteRecordUnescapedIter<'_> {
86        ZeroCopyByteRecordUnescapedIter {
87            record: self,
88            current_forward: 0,
89            current_backward: self.len(),
90        }
91    }
92
93    /// Returns the nth field of the zero copy byte record, if it is not
94    /// out-of-bounds.
95    ///
96    /// The field's bytes will be given as-is, quoted or unquoted, and won't be
97    /// unescaped at all.
98    #[inline]
99    pub fn get(&self, index: usize) -> Option<&[u8]> {
100        let len = self.seps.len();
101
102        if index > len {
103            return None;
104        }
105
106        let start = if index == 0 {
107            0
108        } else {
109            self.seps[index - 1] + 1
110        };
111
112        let end = if index == len {
113            self.slice.len()
114        } else {
115            self.seps[index]
116        };
117
118        Some(&self.slice[start..end])
119    }
120
121    /// Returns the nth field of the zero copy byte record, if it is not
122    /// out-of-bounds.
123    ///
124    /// The field's bytes will be given unquoted (i.e. without surrounding
125    /// quotes), but not unescaped (i.e. doubled double quotes will still be
126    /// there).
127    ///
128    /// The overhead vs. [`Self::get`] is only constant (we trim a leading and
129    /// trailing quote if required).
130    #[inline]
131    pub fn unquote(&self, index: usize) -> Option<&[u8]> {
132        self.get(index)
133            .map(|cell| unquoted(cell, self.quote).unwrap_or(cell))
134    }
135
136    /// Returns the nth field of the zero copy byte record, if it is not
137    /// out-of-bounds.
138    ///
139    /// The field's bytes will be completely unescaped.
140    ///
141    /// The overhead vs. [`Self::get`] is linear in the field's number of bytes.
142    ///
143    /// A [`Cow::Owned`] will be returned if the field actually needed
144    /// unescaping, else a [`Cow::Borrowed`] will be returned.
145    #[inline]
146    pub fn unescape(&self, index: usize) -> Option<Cow<'_, [u8]>> {
147        self.get(index).map(|cell| {
148            if let Some(trimmed) = unquoted(cell, self.quote) {
149                unescape(trimmed, self.quote)
150            } else {
151                Cow::Borrowed(cell)
152            }
153        })
154    }
155
156    fn read_byte_record(&self, record: &mut ByteRecord) {
157        record.clear();
158
159        for cell in self.iter() {
160            if let Some(trimmed) = unquoted(cell, self.quote) {
161                unescape_to(trimmed, self.quote, &mut record.data);
162
163                let bounds_len = record.bounds.len();
164
165                let start = if bounds_len == 0 {
166                    0
167                } else {
168                    record.bounds[bounds_len - 1].1
169                };
170
171                record.bounds.push((start, record.data.len()));
172            } else {
173                record.push_field(cell);
174            }
175        }
176    }
177
178    /// Converts the zero copy byte record into a proper, owned [`ByteRecord`].
179    #[inline]
180    pub fn to_byte_record(&self) -> ByteRecord {
181        let mut record = ByteRecord::new();
182        self.read_byte_record(&mut record);
183        record
184    }
185
186    #[inline]
187    pub(crate) fn to_byte_record_in_reverse(&self) -> ByteRecord {
188        let mut record = ByteRecord::new();
189
190        for cell in self.unescaped_iter().rev() {
191            record.push_field_in_reverse(&cell);
192        }
193
194        record
195    }
196}
197
198impl fmt::Debug for ZeroCopyByteRecord<'_> {
199    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
200        write!(f, "ZeroCopyByteRecord(")?;
201        f.debug_list()
202            .entries(self.iter().map(debug::Bytes))
203            .finish()?;
204        write!(f, ")")?;
205        Ok(())
206    }
207}
208
209macro_rules! make_zero_copy_iterator {
210    ($name:ident, $method: ident, $out_type: ty) => {
211        pub struct $name<'a> {
212            record: &'a ZeroCopyByteRecord<'a>,
213            current_forward: usize,
214            current_backward: usize,
215        }
216
217        impl ExactSizeIterator for $name<'_> {}
218
219        impl<'a> Iterator for $name<'a> {
220            type Item = $out_type;
221
222            #[inline]
223            fn next(&mut self) -> Option<Self::Item> {
224                if self.current_forward == self.current_backward {
225                    None
226                } else {
227                    let cell = self.record.$method(self.current_forward);
228
229                    self.current_forward += 1;
230
231                    cell
232                }
233            }
234
235            #[inline]
236            fn size_hint(&self) -> (usize, Option<usize>) {
237                let size = self.current_backward - self.current_forward;
238
239                (size, Some(size))
240            }
241
242            #[inline]
243            fn count(self) -> usize
244            where
245                Self: Sized,
246            {
247                self.len()
248            }
249        }
250
251        impl DoubleEndedIterator for $name<'_> {
252            #[inline]
253            fn next_back(&mut self) -> Option<Self::Item> {
254                if self.current_forward == self.current_backward {
255                    None
256                } else {
257                    self.current_backward -= 1;
258
259                    self.record.$method(self.current_backward)
260                }
261            }
262        }
263    };
264}
265
266make_zero_copy_iterator!(ZeroCopyByteRecordIter, get, &'a [u8]);
267make_zero_copy_iterator!(ZeroCopyByteRecordUnquotedIter, unquote, &'a [u8]);
268make_zero_copy_iterator!(ZeroCopyByteRecordUnescapedIter, unescape, Cow<'a, [u8]>);
269
270impl Index<usize> for ZeroCopyByteRecord<'_> {
271    type Output = [u8];
272
273    #[inline]
274    fn index(&self, i: usize) -> &[u8] {
275        self.get(i).unwrap()
276    }
277}
278
279/// An owned, unquoted/unescaped representation of a CSV record.
280///
281/// [`ByteRecord`] are typically used with a [`Reader`](crate::Reader).
282///
283/// *Creating a [`ByteRecord`]*:
284/// ```
285/// use simd_csv::ByteRecord;
286///
287/// let mut record = ByteRecord::new();
288/// record.push_field(b"john");
289/// record.push_field(b"landis");
290/// ```
291#[derive(Default, Clone, Eq)]
292pub struct ByteRecord {
293    pub(crate) data: Vec<u8>,
294    pub(crate) bounds: Vec<(usize, usize)>,
295}
296
297impl ByteRecord {
298    /// Create a empty record.
299    pub fn new() -> Self {
300        Self::default()
301    }
302
303    /// Create a single field record from given bytes vector
304    pub fn from_field(data: Vec<u8>) -> Self {
305        Self {
306            bounds: vec![(0, data.len())],
307            data,
308        }
309    }
310
311    /// Create a new record with given capacity.
312    pub fn with_capacity(buffer: usize, fields: usize) -> Self {
313        Self {
314            data: Vec::with_capacity(buffer),
315            bounds: Vec::with_capacity(fields),
316        }
317    }
318
319    /// Return the number of fields of the record.
320    #[inline]
321    pub fn len(&self) -> usize {
322        self.bounds.len()
323    }
324
325    /// Return whether the record is empty.
326    #[inline]
327    pub fn is_empty(&self) -> bool {
328        self.len() == 0
329    }
330
331    /// Clear the record completely.
332    #[inline]
333    pub fn clear(&mut self) {
334        self.data.clear();
335        self.bounds.clear();
336    }
337
338    /// Shortens the record, keeping the first `len` elements and dropping the
339    /// rest.
340    #[inline]
341    pub fn truncate(&mut self, len: usize) {
342        self.bounds.truncate(len);
343
344        if let Some((_, end)) = self.bounds.last() {
345            self.data.truncate(*end);
346        } else {
347            self.data.clear();
348        }
349    }
350
351    /// Return the underlying byte slice.
352    ///
353    /// **BEWARE**: the [`Reader`](crate::Reader) amortizes copies by sometimes
354    /// including spurious data such as quotes and delimiters. You will never
355    /// see those bytes while accessing fields because the field boundaries
356    /// remain correct, but you will see them in the underlying slice.
357    #[inline]
358    pub fn as_slice(&self) -> &[u8] {
359        &self.data
360    }
361
362    #[inline]
363    #[cfg(feature = "binary")]
364    pub(crate) fn as_parts(&self) -> (&[(usize, usize)], &[u8]) {
365        (&self.bounds, &self.data)
366    }
367
368    /// Return an iterator over the record's fields.
369    #[inline]
370    pub fn iter(&self) -> ByteRecordIter<'_> {
371        ByteRecordIter {
372            record: self,
373            current_forward: 0,
374            current_backward: self.len(),
375        }
376    }
377
378    /// Push a new field to the back of the record.
379    #[inline(always)]
380    pub fn push_field(&mut self, bytes: &[u8]) {
381        self.data.extend_from_slice(bytes.as_ref());
382
383        let bounds_len = self.bounds.len();
384
385        let start = if bounds_len == 0 {
386            0
387        } else {
388            self.bounds[bounds_len - 1].1
389        };
390
391        self.bounds.push((start, self.data.len()));
392    }
393
394    /// Push a new field to the back of the record by formatting given [`fmt::Display`]
395    /// target into this record's bytes directly.
396    #[inline]
397    pub fn fmt_field<F: fmt::Display>(&mut self, target: &F) {
398        write!(&mut self.data, "{}", target).unwrap();
399
400        let bounds_len = self.bounds.len();
401
402        let start = if bounds_len == 0 {
403            0
404        } else {
405            self.bounds[bounds_len - 1].1
406        };
407
408        self.bounds.push((start, self.data.len()));
409    }
410
411    /// Push a new field to the back of the record by writing to this record's back
412    /// directly using a callback.
413    #[inline]
414    pub fn write_field<F>(&mut self, callback: F)
415    where
416        F: FnOnce(AppendOnlyView<u8>),
417    {
418        callback(AppendOnlyView::new(&mut self.data));
419
420        let bounds_len = self.bounds.len();
421
422        let start = if bounds_len == 0 {
423            0
424        } else {
425            self.bounds[bounds_len - 1].1
426        };
427
428        self.bounds.push((start, self.data.len()));
429    }
430
431    #[inline]
432    fn push_field_in_reverse(&mut self, bytes: &[u8]) {
433        self.data.extend_from_slice(bytes);
434
435        let bounds_len = self.bounds.len();
436
437        let start = if bounds_len == 0 {
438            0
439        } else {
440            self.bounds[bounds_len - 1].1
441        };
442
443        let bounds = (start, self.data.len());
444        self.data[bounds.0..bounds.1].reverse();
445
446        self.bounds.push(bounds);
447    }
448
449    /// Return field at `index`. Will return `None` if `index` is out of bounds.
450    #[inline]
451    pub fn get(&self, index: usize) -> Option<&[u8]> {
452        self.bounds
453            .get(index)
454            .copied()
455            .map(|(start, end)| &self.data[start..end])
456    }
457
458    /// Attempt to decode given byte record.
459    #[cfg(feature = "str")]
460    pub fn into_string_record(self) -> error::Result<StringRecord> {
461        let mut new_record = StringRecord { inner: self };
462
463        if !new_record.validate_utf8() {
464            Err(Error::new(ErrorKind::Utf8Error))
465        } else {
466            Ok(new_record)
467        }
468    }
469
470    pub(crate) fn reverse(&mut self) {
471        self.data.reverse();
472        self.bounds.reverse();
473
474        let len = self.data.len();
475
476        for (start, end) in self.bounds.iter_mut() {
477            let new_end = len - *start;
478            let new_start = len - *end;
479
480            *start = new_start;
481            *end = new_end;
482        }
483    }
484}
485
486impl PartialEq for ByteRecord {
487    fn eq(&self, other: &Self) -> bool {
488        if self.bounds.len() != other.bounds.len() {
489            return false;
490        }
491
492        self.iter()
493            .zip(other.iter())
494            .all(|(self_cell, other_cell)| self_cell == other_cell)
495    }
496}
497
498impl Hash for ByteRecord {
499    #[inline]
500    fn hash<H: Hasher>(&self, state: &mut H) {
501        state.write_usize(self.len());
502
503        for cell in self.iter() {
504            state.write(cell);
505        }
506    }
507}
508
509impl Index<usize> for ByteRecord {
510    type Output = [u8];
511
512    #[inline]
513    fn index(&self, i: usize) -> &[u8] {
514        self.get(i).unwrap()
515    }
516}
517
518impl<T: AsRef<[u8]>> Extend<T> for ByteRecord {
519    #[inline]
520    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
521        let iter = iter.into_iter();
522        let size_hint = iter.size_hint();
523
524        self.bounds.reserve(size_hint.1.unwrap_or(size_hint.0));
525
526        for x in iter {
527            self.push_field(x.as_ref());
528        }
529    }
530}
531
532impl<T: AsRef<[u8]>> FromIterator<T> for ByteRecord {
533    #[inline]
534    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
535        let mut record = Self::new();
536        record.extend(iter);
537        record
538    }
539}
540
541impl<I, T> From<I> for ByteRecord
542where
543    I: IntoIterator<Item = T>,
544    T: AsRef<[u8]>,
545{
546    fn from(value: I) -> Self {
547        let mut record = Self::new();
548
549        for cell in value.into_iter() {
550            record.push_field(cell.as_ref());
551        }
552
553        record
554    }
555}
556
557impl<'r> IntoIterator for &'r ByteRecord {
558    type IntoIter = ByteRecordIter<'r>;
559    type Item = &'r [u8];
560
561    #[inline]
562    fn into_iter(self) -> ByteRecordIter<'r> {
563        self.iter()
564    }
565}
566
567impl fmt::Debug for ByteRecord {
568    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
569        write!(f, "ByteRecord(")?;
570        f.debug_list()
571            .entries(self.iter().map(debug::Bytes))
572            .finish()?;
573        write!(f, ")")?;
574        Ok(())
575    }
576}
577
578pub struct ByteRecordIter<'a> {
579    record: &'a ByteRecord,
580    current_forward: usize,
581    current_backward: usize,
582}
583
584impl ExactSizeIterator for ByteRecordIter<'_> {}
585
586impl<'a> Iterator for ByteRecordIter<'a> {
587    type Item = &'a [u8];
588
589    #[inline]
590    fn next(&mut self) -> Option<Self::Item> {
591        if self.current_forward == self.current_backward {
592            None
593        } else {
594            let (start, end) = self.record.bounds[self.current_forward];
595
596            self.current_forward += 1;
597
598            Some(&self.record.data[start..end])
599        }
600    }
601
602    #[inline]
603    fn size_hint(&self) -> (usize, Option<usize>) {
604        let size = self.current_backward - self.current_forward;
605
606        (size, Some(size))
607    }
608
609    #[inline]
610    fn count(self) -> usize
611    where
612        Self: Sized,
613    {
614        self.len()
615    }
616}
617
618impl DoubleEndedIterator for ByteRecordIter<'_> {
619    #[inline]
620    fn next_back(&mut self) -> Option<Self::Item> {
621        if self.current_forward == self.current_backward {
622            None
623        } else {
624            self.current_backward -= 1;
625
626            let (start, end) = self.record.bounds[self.current_backward];
627
628            Some(&self.record.data[start..end])
629        }
630    }
631}
632
633pub(crate) struct ByteRecordBuilder<'r> {
634    record: &'r mut ByteRecord,
635    start: usize,
636}
637
638impl<'r> ByteRecordBuilder<'r> {
639    #[inline(always)]
640    pub(crate) fn wrap(record: &'r mut ByteRecord) -> Self {
641        Self { record, start: 0 }
642    }
643
644    #[inline(always)]
645    pub(crate) fn extend_from_slice(&mut self, slice: &[u8]) {
646        self.record.data.extend_from_slice(slice);
647    }
648
649    #[inline(always)]
650    pub(crate) fn push_byte(&mut self, byte: u8) {
651        self.record.data.push(byte);
652    }
653
654    #[inline]
655    pub(crate) fn finalize_field(&mut self) {
656        let start = self.start;
657        self.start = self.record.data.len();
658
659        self.record.bounds.push((start, self.start));
660    }
661
662    #[inline]
663    pub(crate) fn finalize_record(&mut self) {
664        self.finalize_field();
665
666        if let Some((start, end)) = self.record.bounds.last_mut() {
667            if let Some(b'\r') = self.record.data[*start..*end].last() {
668                *end -= 1;
669                self.record.data.pop();
670            }
671        }
672    }
673
674    #[inline]
675    pub(crate) fn finalize_field_preemptively(&mut self, offset: usize) {
676        let start = self.start;
677        self.start = self.record.data.len() + offset;
678
679        self.record.bounds.push((start, self.start));
680
681        self.start += 1;
682    }
683
684    #[inline(always)]
685    pub(crate) fn bump(&mut self) {
686        self.start +=
687            (self.record.bounds.last().map(|(s, _)| *s).unwrap_or(0) != self.start) as usize;
688    }
689}
690
691#[cfg(feature = "str")]
692mod string_record {
693    use super::*;
694
695    /// An owned, decoded & unquoted/unescaped representation of a CSV record.
696    ///
697    /// [`StringRecord`] are typically used with a [`Reader`](crate::Reader).
698    ///
699    /// *Creating a [`StringRecord`]*:
700    /// ```
701    /// use simd_csv::StringRecord;
702    ///
703    /// let mut record = StringRecord::new();
704    /// record.push_field("john");
705    /// record.push_field("landis");
706    /// ```
707    #[derive(Default, Clone, Eq)]
708    pub struct StringRecord {
709        pub(super) inner: ByteRecord,
710    }
711
712    impl StringRecord {
713        /// Create an empty record
714        pub fn new() -> Self {
715            Self {
716                inner: ByteRecord::new(),
717            }
718        }
719
720        /// Create a new record with given capacity.
721        pub fn with_capacity(buffer: usize, fields: usize) -> Self {
722            Self {
723                inner: ByteRecord::with_capacity(buffer, fields),
724            }
725        }
726
727        /// Return a reference to the underlying [`ByteRecord`] backing this record.
728        #[inline(always)]
729        pub fn as_byte_record(&self) -> &ByteRecord {
730            &self.inner
731        }
732
733        /// Return the number of fields of the record.
734        #[inline(always)]
735        pub fn len(&self) -> usize {
736            self.inner.len()
737        }
738
739        /// Return whether the record is empty.
740        #[inline(always)]
741        pub fn is_empty(&self) -> bool {
742            self.inner.is_empty()
743        }
744
745        /// Clear the record completely.
746        #[inline(always)]
747        pub fn clear(&mut self) {
748            self.inner.clear();
749        }
750
751        #[inline(always)]
752        pub(crate) fn as_inner_mut(&mut self) -> &mut ByteRecord {
753            &mut self.inner
754        }
755
756        #[inline]
757        pub(crate) fn validate_utf8(&mut self) -> bool {
758            let bytes = self.inner.as_slice();
759
760            // NOTE: we need to bench this more rigorously
761            if bytes.is_ascii() {
762                true
763            } else if simdutf8::basic::from_utf8(bytes).is_err() {
764                // NOTE: we clear so we don't leave the record in an invalid state!
765                self.inner.clear();
766                false
767            } else {
768                true
769            }
770        }
771
772        /// Return field at `index`. Will return `None` if `index` is out of bounds.
773        #[inline]
774        pub fn get(&self, index: usize) -> Option<&str> {
775            self.inner.get(index).map(|slice| {
776                debug_assert!(std::str::from_utf8(slice).is_ok());
777                unsafe { std::str::from_utf8_unchecked(slice) }
778            })
779        }
780
781        /// Return an iterator over the record's fields.
782        #[inline]
783        pub fn iter(&self) -> StringRecordIter<'_> {
784            StringRecordIter {
785                record: &self.inner,
786                current_forward: 0,
787                current_backward: self.len(),
788            }
789        }
790
791        /// Append a new field to the back of the record.
792        #[inline(always)]
793        pub fn push_field(&mut self, field: &str) {
794            self.as_inner_mut().push_field(field.as_bytes());
795        }
796    }
797
798    impl PartialEq for StringRecord {
799        #[inline(always)]
800        fn eq(&self, other: &Self) -> bool {
801            self.inner.eq(&other.inner)
802        }
803    }
804
805    impl Hash for StringRecord {
806        #[inline(always)]
807        fn hash<H: Hasher>(&self, state: &mut H) {
808            self.inner.hash(state);
809        }
810    }
811
812    impl Index<usize> for StringRecord {
813        type Output = str;
814
815        #[inline]
816        fn index(&self, i: usize) -> &str {
817            self.get(i).unwrap()
818        }
819    }
820
821    impl<T: AsRef<str>> Extend<T> for StringRecord {
822        #[inline]
823        fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
824            let iter = iter.into_iter();
825            let size_hint = iter.size_hint();
826
827            self.inner
828                .bounds
829                .reserve(size_hint.1.unwrap_or(size_hint.0));
830
831            for x in iter {
832                self.push_field(x.as_ref());
833            }
834        }
835    }
836
837    impl<T: AsRef<str>> FromIterator<T> for StringRecord {
838        #[inline]
839        fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
840            let mut record = Self::new();
841            record.extend(iter);
842            record
843        }
844    }
845
846    impl<'r> IntoIterator for &'r StringRecord {
847        type IntoIter = StringRecordIter<'r>;
848        type Item = &'r str;
849
850        #[inline]
851        fn into_iter(self) -> StringRecordIter<'r> {
852            self.iter()
853        }
854    }
855
856    impl fmt::Debug for StringRecord {
857        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
858            write!(f, "StringRecord(")?;
859            f.debug_list().entries(self.iter()).finish()?;
860            write!(f, ")")?;
861            Ok(())
862        }
863    }
864
865    pub struct StringRecordIter<'a> {
866        record: &'a ByteRecord,
867        current_forward: usize,
868        current_backward: usize,
869    }
870
871    impl ExactSizeIterator for StringRecordIter<'_> {}
872
873    impl<'a> Iterator for StringRecordIter<'a> {
874        type Item = &'a str;
875
876        #[inline]
877        fn next(&mut self) -> Option<Self::Item> {
878            if self.current_forward == self.current_backward {
879                None
880            } else {
881                let (start, end) = self.record.bounds[self.current_forward];
882
883                self.current_forward += 1;
884
885                Some(unsafe { std::str::from_utf8_unchecked(&self.record.data[start..end]) })
886            }
887        }
888
889        #[inline]
890        fn size_hint(&self) -> (usize, Option<usize>) {
891            let size = self.current_backward - self.current_forward;
892
893            (size, Some(size))
894        }
895
896        #[inline]
897        fn count(self) -> usize
898        where
899            Self: Sized,
900        {
901            self.len()
902        }
903    }
904
905    impl DoubleEndedIterator for StringRecordIter<'_> {
906        #[inline]
907        fn next_back(&mut self) -> Option<Self::Item> {
908            if self.current_forward == self.current_backward {
909                None
910            } else {
911                self.current_backward -= 1;
912
913                let (start, end) = self.record.bounds[self.current_backward];
914
915                Some(unsafe { std::str::from_utf8_unchecked(&self.record.data[start..end]) })
916            }
917        }
918    }
919}
920
921#[cfg(feature = "str")]
922pub use string_record::*;
923
924#[cfg(test)]
925mod tests {
926    use super::*;
927
928    #[test]
929    fn test_zero_copy_byte_record() {
930        let record = ZeroCopyByteRecord::new(b"name,surname,age", &[4, 12], b'"');
931
932        assert_eq!(record.len(), 3);
933
934        let expected: Vec<&[u8]> = vec![b"name", b"surname", b"age"];
935        assert_eq!(record.iter().collect::<Vec<_>>(), expected);
936
937        for i in 0..expected.len() {
938            assert_eq!(record.get(i), Some(expected[i]));
939        }
940
941        assert_eq!(record.get(4), None);
942    }
943
944    #[test]
945    fn test_byte_record() {
946        let mut record = ByteRecord::new();
947
948        assert_eq!(record.len(), 0);
949        assert_eq!(record.is_empty(), true);
950        assert_eq!(record.get(0), None);
951
952        record.push_field(b"name");
953        record.push_field(b"surname");
954        record.push_field(b"age");
955
956        let expected: Vec<&[u8]> = vec![b"name", b"surname", b"age"];
957        assert_eq!(record.iter().collect::<Vec<_>>(), expected);
958
959        assert_eq!(record.get(0), Some::<&[u8]>(b"name"));
960        assert_eq!(record.get(1), Some::<&[u8]>(b"surname"));
961        assert_eq!(record.get(2), Some::<&[u8]>(b"age"));
962        assert_eq!(record.get(3), None);
963    }
964
965    #[test]
966    fn test_fmt_field() {
967        let mut record = ByteRecord::new();
968
969        record.fmt_field(&45);
970        record.fmt_field(&5.6);
971        record.fmt_field(&"test");
972
973        assert_eq!(record, brec!["45", "5.6", "test"]);
974    }
975
976    #[test]
977    fn test_write_field() {
978        let mut record = ByteRecord::new();
979
980        record.write_field(|bytes| serde_json::to_writer(bytes, &vec!["hello", "world"]).unwrap());
981
982        record.push_field(b"test");
983
984        assert_eq!(record, brec!["[\"hello\",\"world\"]", "test"]);
985    }
986
987    #[test]
988    fn test_mutate_record_after_read() {
989        let mut record = ByteRecord::new();
990        let mut builder = ByteRecordBuilder::wrap(&mut record);
991        builder.extend_from_slice(b"test\r");
992        builder.finalize_record();
993
994        assert_eq!(record.iter().collect::<Vec<_>>(), vec![b"test"]);
995
996        record.push_field(b"next");
997
998        assert_eq!(record.iter().collect::<Vec<_>>(), vec![b"test", b"next"]);
999    }
1000
1001    #[test]
1002    fn test_reverse_byte_record() {
1003        let record = brec!["name", "surname", "age"];
1004        let mut reversed = record.clone();
1005        reversed.reverse();
1006
1007        assert_eq!(reversed, brec!["ega", "emanrus", "eman"]);
1008        reversed.reverse();
1009        assert_eq!(record, reversed);
1010    }
1011
1012    #[test]
1013    fn test_from_field() {
1014        let field = b"john".to_vec();
1015        let mut record = ByteRecord::from_field(field);
1016
1017        assert_eq!(record, brec!["john"]);
1018
1019        record.push_field(b"landis");
1020
1021        assert_eq!(record, brec!["john", "landis"]);
1022    }
1023}