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
13pub 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 #[inline(always)]
38 pub fn len(&self) -> usize {
39 self.seps.len() + 1
42 }
43
44 #[inline(always)]
46 pub fn is_empty(&self) -> bool {
47 false
48 }
49
50 #[inline(always)]
52 pub fn as_slice(&self) -> &[u8] {
53 self.slice
54 }
55
56 #[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 #[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 #[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 #[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 #[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 #[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 #[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#[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 pub fn new() -> Self {
300 Self::default()
301 }
302
303 pub fn with_capacity(buffer: usize, fields: usize) -> Self {
305 Self {
306 data: Vec::with_capacity(buffer),
307 bounds: Vec::with_capacity(fields),
308 }
309 }
310
311 #[inline]
313 pub fn len(&self) -> usize {
314 self.bounds.len()
315 }
316
317 #[inline]
319 pub fn is_empty(&self) -> bool {
320 self.len() == 0
321 }
322
323 #[inline]
325 pub fn clear(&mut self) {
326 self.data.clear();
327 self.bounds.clear();
328 }
329
330 #[inline]
333 pub fn truncate(&mut self, len: usize) {
334 self.bounds.truncate(len);
335
336 if let Some((_, end)) = self.bounds.last() {
337 self.data.truncate(*end);
338 } else {
339 self.data.clear();
340 }
341 }
342
343 #[inline]
350 pub fn as_slice(&self) -> &[u8] {
351 &self.data
352 }
353
354 #[inline]
355 #[cfg(feature = "binary")]
356 pub(crate) fn as_parts(&self) -> (&[(usize, usize)], &[u8]) {
357 (&self.bounds, &self.data)
358 }
359
360 #[inline]
362 pub fn iter(&self) -> ByteRecordIter<'_> {
363 ByteRecordIter {
364 record: self,
365 current_forward: 0,
366 current_backward: self.len(),
367 }
368 }
369
370 #[inline(always)]
372 pub fn push_field(&mut self, bytes: &[u8]) {
373 self.data.extend_from_slice(bytes.as_ref());
374
375 let bounds_len = self.bounds.len();
376
377 let start = if bounds_len == 0 {
378 0
379 } else {
380 self.bounds[bounds_len - 1].1
381 };
382
383 self.bounds.push((start, self.data.len()));
384 }
385
386 #[inline]
389 pub fn fmt_field<F: fmt::Display>(&mut self, target: &F) {
390 write!(&mut self.data, "{}", target).unwrap();
391
392 let bounds_len = self.bounds.len();
393
394 let start = if bounds_len == 0 {
395 0
396 } else {
397 self.bounds[bounds_len - 1].1
398 };
399
400 self.bounds.push((start, self.data.len()));
401 }
402
403 #[inline]
406 pub fn write_field<F>(&mut self, callback: F)
407 where
408 F: FnOnce(AppendOnlyView<u8>),
409 {
410 callback(AppendOnlyView::new(&mut self.data));
411
412 let bounds_len = self.bounds.len();
413
414 let start = if bounds_len == 0 {
415 0
416 } else {
417 self.bounds[bounds_len - 1].1
418 };
419
420 self.bounds.push((start, self.data.len()));
421 }
422
423 #[inline]
424 fn push_field_in_reverse(&mut self, bytes: &[u8]) {
425 self.data.extend_from_slice(bytes);
426
427 let bounds_len = self.bounds.len();
428
429 let start = if bounds_len == 0 {
430 0
431 } else {
432 self.bounds[bounds_len - 1].1
433 };
434
435 let bounds = (start, self.data.len());
436 self.data[bounds.0..bounds.1].reverse();
437
438 self.bounds.push(bounds);
439 }
440
441 #[inline]
443 pub fn get(&self, index: usize) -> Option<&[u8]> {
444 self.bounds
445 .get(index)
446 .copied()
447 .map(|(start, end)| &self.data[start..end])
448 }
449
450 #[cfg(feature = "str")]
452 pub fn into_string_record(self) -> error::Result<StringRecord> {
453 let mut new_record = StringRecord { inner: self };
454
455 if !new_record.validate_utf8() {
456 Err(Error::new(ErrorKind::Utf8Error))
457 } else {
458 Ok(new_record)
459 }
460 }
461
462 pub(crate) fn reverse(&mut self) {
463 self.data.reverse();
464 self.bounds.reverse();
465
466 let len = self.data.len();
467
468 for (start, end) in self.bounds.iter_mut() {
469 let new_end = len - *start;
470 let new_start = len - *end;
471
472 *start = new_start;
473 *end = new_end;
474 }
475 }
476}
477
478impl PartialEq for ByteRecord {
479 fn eq(&self, other: &Self) -> bool {
480 if self.bounds.len() != other.bounds.len() {
481 return false;
482 }
483
484 self.iter()
485 .zip(other.iter())
486 .all(|(self_cell, other_cell)| self_cell == other_cell)
487 }
488}
489
490impl Hash for ByteRecord {
491 #[inline]
492 fn hash<H: Hasher>(&self, state: &mut H) {
493 state.write_usize(self.len());
494
495 for cell in self.iter() {
496 state.write(cell);
497 }
498 }
499}
500
501impl Index<usize> for ByteRecord {
502 type Output = [u8];
503
504 #[inline]
505 fn index(&self, i: usize) -> &[u8] {
506 self.get(i).unwrap()
507 }
508}
509
510impl<T: AsRef<[u8]>> Extend<T> for ByteRecord {
511 #[inline]
512 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
513 let iter = iter.into_iter();
514 let size_hint = iter.size_hint();
515
516 self.bounds.reserve(size_hint.1.unwrap_or(size_hint.0));
517
518 for x in iter {
519 self.push_field(x.as_ref());
520 }
521 }
522}
523
524impl<T: AsRef<[u8]>> FromIterator<T> for ByteRecord {
525 #[inline]
526 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
527 let mut record = Self::new();
528 record.extend(iter);
529 record
530 }
531}
532
533impl<I, T> From<I> for ByteRecord
534where
535 I: IntoIterator<Item = T>,
536 T: AsRef<[u8]>,
537{
538 fn from(value: I) -> Self {
539 let mut record = Self::new();
540
541 for cell in value.into_iter() {
542 record.push_field(cell.as_ref());
543 }
544
545 record
546 }
547}
548
549impl<'r> IntoIterator for &'r ByteRecord {
550 type IntoIter = ByteRecordIter<'r>;
551 type Item = &'r [u8];
552
553 #[inline]
554 fn into_iter(self) -> ByteRecordIter<'r> {
555 self.iter()
556 }
557}
558
559impl fmt::Debug for ByteRecord {
560 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
561 write!(f, "ByteRecord(")?;
562 f.debug_list()
563 .entries(self.iter().map(debug::Bytes))
564 .finish()?;
565 write!(f, ")")?;
566 Ok(())
567 }
568}
569
570pub struct ByteRecordIter<'a> {
571 record: &'a ByteRecord,
572 current_forward: usize,
573 current_backward: usize,
574}
575
576impl ExactSizeIterator for ByteRecordIter<'_> {}
577
578impl<'a> Iterator for ByteRecordIter<'a> {
579 type Item = &'a [u8];
580
581 #[inline]
582 fn next(&mut self) -> Option<Self::Item> {
583 if self.current_forward == self.current_backward {
584 None
585 } else {
586 let (start, end) = self.record.bounds[self.current_forward];
587
588 self.current_forward += 1;
589
590 Some(&self.record.data[start..end])
591 }
592 }
593
594 #[inline]
595 fn size_hint(&self) -> (usize, Option<usize>) {
596 let size = self.current_backward - self.current_forward;
597
598 (size, Some(size))
599 }
600
601 #[inline]
602 fn count(self) -> usize
603 where
604 Self: Sized,
605 {
606 self.len()
607 }
608}
609
610impl DoubleEndedIterator for ByteRecordIter<'_> {
611 #[inline]
612 fn next_back(&mut self) -> Option<Self::Item> {
613 if self.current_forward == self.current_backward {
614 None
615 } else {
616 self.current_backward -= 1;
617
618 let (start, end) = self.record.bounds[self.current_backward];
619
620 Some(&self.record.data[start..end])
621 }
622 }
623}
624
625pub(crate) struct ByteRecordBuilder<'r> {
626 record: &'r mut ByteRecord,
627 start: usize,
628}
629
630impl<'r> ByteRecordBuilder<'r> {
631 #[inline(always)]
632 pub(crate) fn wrap(record: &'r mut ByteRecord) -> Self {
633 Self { record, start: 0 }
634 }
635
636 #[inline(always)]
637 pub(crate) fn extend_from_slice(&mut self, slice: &[u8]) {
638 self.record.data.extend_from_slice(slice);
639 }
640
641 #[inline(always)]
642 pub(crate) fn push_byte(&mut self, byte: u8) {
643 self.record.data.push(byte);
644 }
645
646 #[inline]
647 pub(crate) fn finalize_field(&mut self) {
648 let start = self.start;
649 self.start = self.record.data.len();
650
651 self.record.bounds.push((start, self.start));
652 }
653
654 #[inline]
655 pub(crate) fn finalize_record(&mut self) {
656 self.finalize_field();
657
658 if let Some((start, end)) = self.record.bounds.last_mut() {
659 if let Some(b'\r') = self.record.data[*start..*end].last() {
660 *end -= 1;
661 self.record.data.pop();
662 }
663 }
664 }
665
666 #[inline]
667 pub(crate) fn finalize_field_preemptively(&mut self, offset: usize) {
668 let start = self.start;
669 self.start = self.record.data.len() + offset;
670
671 self.record.bounds.push((start, self.start));
672
673 self.start += 1;
674 }
675
676 #[inline(always)]
677 pub(crate) fn bump(&mut self) {
678 self.start +=
679 (self.record.bounds.last().map(|(s, _)| *s).unwrap_or(0) != self.start) as usize;
680 }
681}
682
683#[cfg(feature = "str")]
684mod string_record {
685 use super::*;
686
687 #[derive(Default, Clone, Eq)]
700 pub struct StringRecord {
701 pub(super) inner: ByteRecord,
702 }
703
704 impl StringRecord {
705 pub fn new() -> Self {
707 Self {
708 inner: ByteRecord::new(),
709 }
710 }
711
712 pub fn with_capacity(buffer: usize, fields: usize) -> Self {
714 Self {
715 inner: ByteRecord::with_capacity(buffer, fields),
716 }
717 }
718
719 #[inline(always)]
721 pub fn as_byte_record(&self) -> &ByteRecord {
722 &self.inner
723 }
724
725 #[inline(always)]
727 pub fn len(&self) -> usize {
728 self.inner.len()
729 }
730
731 #[inline(always)]
733 pub fn is_empty(&self) -> bool {
734 self.inner.is_empty()
735 }
736
737 #[inline(always)]
739 pub fn clear(&mut self) {
740 self.inner.clear();
741 }
742
743 #[inline(always)]
744 pub(crate) fn as_inner_mut(&mut self) -> &mut ByteRecord {
745 &mut self.inner
746 }
747
748 #[inline]
749 pub(crate) fn validate_utf8(&mut self) -> bool {
750 let bytes = self.inner.as_slice();
751
752 if bytes.is_ascii() {
754 true
755 } else if simdutf8::basic::from_utf8(bytes).is_err() {
756 self.inner.clear();
758 false
759 } else {
760 true
761 }
762 }
763
764 #[inline]
766 pub fn get(&self, index: usize) -> Option<&str> {
767 self.inner.get(index).map(|slice| {
768 debug_assert!(std::str::from_utf8(slice).is_ok());
769 unsafe { std::str::from_utf8_unchecked(slice) }
770 })
771 }
772
773 #[inline]
775 pub fn iter(&self) -> StringRecordIter<'_> {
776 StringRecordIter {
777 record: &self.inner,
778 current_forward: 0,
779 current_backward: self.len(),
780 }
781 }
782
783 #[inline(always)]
785 pub fn push_field(&mut self, field: &str) {
786 self.as_inner_mut().push_field(field.as_bytes());
787 }
788 }
789
790 impl PartialEq for StringRecord {
791 #[inline(always)]
792 fn eq(&self, other: &Self) -> bool {
793 self.inner.eq(&other.inner)
794 }
795 }
796
797 impl Hash for StringRecord {
798 #[inline(always)]
799 fn hash<H: Hasher>(&self, state: &mut H) {
800 self.inner.hash(state);
801 }
802 }
803
804 impl Index<usize> for StringRecord {
805 type Output = str;
806
807 #[inline]
808 fn index(&self, i: usize) -> &str {
809 self.get(i).unwrap()
810 }
811 }
812
813 impl<T: AsRef<str>> Extend<T> for StringRecord {
814 #[inline]
815 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
816 let iter = iter.into_iter();
817 let size_hint = iter.size_hint();
818
819 self.inner
820 .bounds
821 .reserve(size_hint.1.unwrap_or(size_hint.0));
822
823 for x in iter {
824 self.push_field(x.as_ref());
825 }
826 }
827 }
828
829 impl<T: AsRef<str>> FromIterator<T> for StringRecord {
830 #[inline]
831 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
832 let mut record = Self::new();
833 record.extend(iter);
834 record
835 }
836 }
837
838 impl<'r> IntoIterator for &'r StringRecord {
839 type IntoIter = StringRecordIter<'r>;
840 type Item = &'r str;
841
842 #[inline]
843 fn into_iter(self) -> StringRecordIter<'r> {
844 self.iter()
845 }
846 }
847
848 impl fmt::Debug for StringRecord {
849 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
850 write!(f, "StringRecord(")?;
851 f.debug_list().entries(self.iter()).finish()?;
852 write!(f, ")")?;
853 Ok(())
854 }
855 }
856
857 pub struct StringRecordIter<'a> {
858 record: &'a ByteRecord,
859 current_forward: usize,
860 current_backward: usize,
861 }
862
863 impl ExactSizeIterator for StringRecordIter<'_> {}
864
865 impl<'a> Iterator for StringRecordIter<'a> {
866 type Item = &'a str;
867
868 #[inline]
869 fn next(&mut self) -> Option<Self::Item> {
870 if self.current_forward == self.current_backward {
871 None
872 } else {
873 let (start, end) = self.record.bounds[self.current_forward];
874
875 self.current_forward += 1;
876
877 Some(unsafe { std::str::from_utf8_unchecked(&self.record.data[start..end]) })
878 }
879 }
880
881 #[inline]
882 fn size_hint(&self) -> (usize, Option<usize>) {
883 let size = self.current_backward - self.current_forward;
884
885 (size, Some(size))
886 }
887
888 #[inline]
889 fn count(self) -> usize
890 where
891 Self: Sized,
892 {
893 self.len()
894 }
895 }
896
897 impl DoubleEndedIterator for StringRecordIter<'_> {
898 #[inline]
899 fn next_back(&mut self) -> Option<Self::Item> {
900 if self.current_forward == self.current_backward {
901 None
902 } else {
903 self.current_backward -= 1;
904
905 let (start, end) = self.record.bounds[self.current_backward];
906
907 Some(unsafe { std::str::from_utf8_unchecked(&self.record.data[start..end]) })
908 }
909 }
910 }
911}
912
913#[cfg(feature = "str")]
914pub use string_record::*;
915
916#[cfg(test)]
917mod tests {
918 use super::*;
919
920 #[test]
921 fn test_zero_copy_byte_record() {
922 let record = ZeroCopyByteRecord::new(b"name,surname,age", &[4, 12], b'"');
923
924 assert_eq!(record.len(), 3);
925
926 let expected: Vec<&[u8]> = vec![b"name", b"surname", b"age"];
927 assert_eq!(record.iter().collect::<Vec<_>>(), expected);
928
929 for i in 0..expected.len() {
930 assert_eq!(record.get(i), Some(expected[i]));
931 }
932
933 assert_eq!(record.get(4), None);
934 }
935
936 #[test]
937 fn test_byte_record() {
938 let mut record = ByteRecord::new();
939
940 assert_eq!(record.len(), 0);
941 assert_eq!(record.is_empty(), true);
942 assert_eq!(record.get(0), None);
943
944 record.push_field(b"name");
945 record.push_field(b"surname");
946 record.push_field(b"age");
947
948 let expected: Vec<&[u8]> = vec![b"name", b"surname", b"age"];
949 assert_eq!(record.iter().collect::<Vec<_>>(), expected);
950
951 assert_eq!(record.get(0), Some::<&[u8]>(b"name"));
952 assert_eq!(record.get(1), Some::<&[u8]>(b"surname"));
953 assert_eq!(record.get(2), Some::<&[u8]>(b"age"));
954 assert_eq!(record.get(3), None);
955 }
956
957 #[test]
958 fn test_fmt_field() {
959 let mut record = ByteRecord::new();
960
961 record.fmt_field(&45);
962 record.fmt_field(&5.6);
963 record.fmt_field(&"test");
964
965 assert_eq!(record, brec!["45", "5.6", "test"]);
966 }
967
968 #[test]
969 fn test_write_field() {
970 let mut record = ByteRecord::new();
971
972 record.write_field(|bytes| serde_json::to_writer(bytes, &vec!["hello", "world"]).unwrap());
973
974 record.push_field(b"test");
975
976 assert_eq!(record, brec!["[\"hello\",\"world\"]", "test"]);
977 }
978
979 #[test]
980 fn test_mutate_record_after_read() {
981 let mut record = ByteRecord::new();
982 let mut builder = ByteRecordBuilder::wrap(&mut record);
983 builder.extend_from_slice(b"test\r");
984 builder.finalize_record();
985
986 assert_eq!(record.iter().collect::<Vec<_>>(), vec![b"test"]);
987
988 record.push_field(b"next");
989
990 assert_eq!(record.iter().collect::<Vec<_>>(), vec![b"test", b"next"]);
991 }
992
993 #[test]
994 fn test_reverse_byte_record() {
995 let record = brec!["name", "surname", "age"];
996 let mut reversed = record.clone();
997 reversed.reverse();
998
999 assert_eq!(reversed, brec!["ega", "emanrus", "eman"]);
1000 reversed.reverse();
1001 assert_eq!(record, reversed);
1002 }
1003}