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 #[inline(always)]
714 pub fn as_byte_record(&self) -> &ByteRecord {
715 &self.inner
716 }
717
718 #[inline(always)]
720 pub fn len(&self) -> usize {
721 self.inner.len()
722 }
723
724 #[inline(always)]
726 pub fn is_empty(&self) -> bool {
727 self.inner.is_empty()
728 }
729
730 #[inline(always)]
732 pub fn clear(&mut self) {
733 self.inner.clear();
734 }
735
736 #[inline(always)]
737 pub(crate) fn as_inner_mut(&mut self) -> &mut ByteRecord {
738 &mut self.inner
739 }
740
741 #[inline]
742 pub(crate) fn validate_utf8(&mut self) -> bool {
743 let bytes = self.inner.as_slice();
744
745 if bytes.is_ascii() {
747 true
748 } else if simdutf8::basic::from_utf8(bytes).is_err() {
749 self.inner.clear();
751 false
752 } else {
753 true
754 }
755 }
756
757 #[inline]
759 pub fn get(&self, index: usize) -> Option<&str> {
760 self.inner.get(index).map(|slice| {
761 debug_assert!(std::str::from_utf8(slice).is_ok());
762 unsafe { std::str::from_utf8_unchecked(slice) }
763 })
764 }
765
766 #[inline]
768 pub fn iter(&self) -> StringRecordIter<'_> {
769 StringRecordIter {
770 record: &self.inner,
771 current_forward: 0,
772 current_backward: self.len(),
773 }
774 }
775
776 #[inline(always)]
778 pub fn push_field(&mut self, field: &str) {
779 self.as_inner_mut().push_field(field.as_bytes());
780 }
781 }
782
783 impl PartialEq for StringRecord {
784 #[inline(always)]
785 fn eq(&self, other: &Self) -> bool {
786 self.inner.eq(&other.inner)
787 }
788 }
789
790 impl Hash for StringRecord {
791 #[inline(always)]
792 fn hash<H: Hasher>(&self, state: &mut H) {
793 self.inner.hash(state);
794 }
795 }
796
797 impl Index<usize> for StringRecord {
798 type Output = str;
799
800 #[inline]
801 fn index(&self, i: usize) -> &str {
802 self.get(i).unwrap()
803 }
804 }
805
806 impl<T: AsRef<str>> Extend<T> for StringRecord {
807 #[inline]
808 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
809 let iter = iter.into_iter();
810 let size_hint = iter.size_hint();
811
812 self.inner
813 .bounds
814 .reserve(size_hint.1.unwrap_or(size_hint.0));
815
816 for x in iter {
817 self.push_field(x.as_ref());
818 }
819 }
820 }
821
822 impl<T: AsRef<str>> FromIterator<T> for StringRecord {
823 #[inline]
824 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
825 let mut record = Self::new();
826 record.extend(iter);
827 record
828 }
829 }
830
831 impl<'r> IntoIterator for &'r StringRecord {
832 type IntoIter = StringRecordIter<'r>;
833 type Item = &'r str;
834
835 #[inline]
836 fn into_iter(self) -> StringRecordIter<'r> {
837 self.iter()
838 }
839 }
840
841 impl fmt::Debug for StringRecord {
842 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
843 write!(f, "StringRecord(")?;
844 f.debug_list().entries(self.iter()).finish()?;
845 write!(f, ")")?;
846 Ok(())
847 }
848 }
849
850 pub struct StringRecordIter<'a> {
851 record: &'a ByteRecord,
852 current_forward: usize,
853 current_backward: usize,
854 }
855
856 impl ExactSizeIterator for StringRecordIter<'_> {}
857
858 impl<'a> Iterator for StringRecordIter<'a> {
859 type Item = &'a str;
860
861 #[inline]
862 fn next(&mut self) -> Option<Self::Item> {
863 if self.current_forward == self.current_backward {
864 None
865 } else {
866 let (start, end) = self.record.bounds[self.current_forward];
867
868 self.current_forward += 1;
869
870 Some(unsafe { std::str::from_utf8_unchecked(&self.record.data[start..end]) })
871 }
872 }
873
874 #[inline]
875 fn size_hint(&self) -> (usize, Option<usize>) {
876 let size = self.current_backward - self.current_forward;
877
878 (size, Some(size))
879 }
880
881 #[inline]
882 fn count(self) -> usize
883 where
884 Self: Sized,
885 {
886 self.len()
887 }
888 }
889
890 impl DoubleEndedIterator for StringRecordIter<'_> {
891 #[inline]
892 fn next_back(&mut self) -> Option<Self::Item> {
893 if self.current_forward == self.current_backward {
894 None
895 } else {
896 self.current_backward -= 1;
897
898 let (start, end) = self.record.bounds[self.current_backward];
899
900 Some(unsafe { std::str::from_utf8_unchecked(&self.record.data[start..end]) })
901 }
902 }
903 }
904}
905
906#[cfg(feature = "str")]
907pub use string_record::*;
908
909#[cfg(test)]
910mod tests {
911 use super::*;
912
913 #[test]
914 fn test_zero_copy_byte_record() {
915 let record = ZeroCopyByteRecord::new(b"name,surname,age", &[4, 12], b'"');
916
917 assert_eq!(record.len(), 3);
918
919 let expected: Vec<&[u8]> = vec![b"name", b"surname", b"age"];
920 assert_eq!(record.iter().collect::<Vec<_>>(), expected);
921
922 for i in 0..expected.len() {
923 assert_eq!(record.get(i), Some(expected[i]));
924 }
925
926 assert_eq!(record.get(4), None);
927 }
928
929 #[test]
930 fn test_byte_record() {
931 let mut record = ByteRecord::new();
932
933 assert_eq!(record.len(), 0);
934 assert_eq!(record.is_empty(), true);
935 assert_eq!(record.get(0), None);
936
937 record.push_field(b"name");
938 record.push_field(b"surname");
939 record.push_field(b"age");
940
941 let expected: Vec<&[u8]> = vec![b"name", b"surname", b"age"];
942 assert_eq!(record.iter().collect::<Vec<_>>(), expected);
943
944 assert_eq!(record.get(0), Some::<&[u8]>(b"name"));
945 assert_eq!(record.get(1), Some::<&[u8]>(b"surname"));
946 assert_eq!(record.get(2), Some::<&[u8]>(b"age"));
947 assert_eq!(record.get(3), None);
948 }
949
950 #[test]
951 fn test_fmt_field() {
952 let mut record = ByteRecord::new();
953
954 record.fmt_field(&45);
955 record.fmt_field(&5.6);
956 record.fmt_field(&"test");
957
958 assert_eq!(record, brec!["45", "5.6", "test"]);
959 }
960
961 #[test]
962 fn test_write_field() {
963 let mut record = ByteRecord::new();
964
965 record.write_field(|bytes| serde_json::to_writer(bytes, &vec!["hello", "world"]).unwrap());
966
967 record.push_field(b"test");
968
969 assert_eq!(record, brec!["[\"hello\",\"world\"]", "test"]);
970 }
971
972 #[test]
973 fn test_mutate_record_after_read() {
974 let mut record = ByteRecord::new();
975 let mut builder = ByteRecordBuilder::wrap(&mut record);
976 builder.extend_from_slice(b"test\r");
977 builder.finalize_record();
978
979 assert_eq!(record.iter().collect::<Vec<_>>(), vec![b"test"]);
980
981 record.push_field(b"next");
982
983 assert_eq!(record.iter().collect::<Vec<_>>(), vec![b"test", b"next"]);
984 }
985
986 #[test]
987 fn test_reverse_byte_record() {
988 let record = brec!["name", "surname", "age"];
989 let mut reversed = record.clone();
990 reversed.reverse();
991
992 assert_eq!(reversed, brec!["ega", "emanrus", "eman"]);
993 reversed.reverse();
994 assert_eq!(record, reversed);
995 }
996}