1use std::io::{self, BufRead};
17
18pub type Fields = Vec<Option<Vec<u8>>>;
20
21fn is_space(b: u8) -> bool {
22 matches!(b, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
23}
24
25fn trailing(buf: &[u8], len: usize) -> usize {
28 let mut last = [0u8; 2];
29 for &b in &buf[..len] {
30 last[0] = last[1];
31 last[1] = b;
32 }
33 match last[1] {
34 b'\n' if last[0] == b'\r' => len - 2,
35 b'\n' | b'\r' => len - 1,
36 _ => len,
37 }
38}
39
40fn field_end(temp: &[u8]) -> usize {
44 trailing(temp, temp.len())
45}
46
47struct Parser<'a> {
48 delimiter: u8,
49 enclosure: u8,
50 escape: Option<u8>,
51 next_line: Option<&'a mut dyn FnMut() -> io::Result<Option<Vec<u8>>>>,
52}
53
54impl Parser<'_> {
55 fn parse(&mut self, line: Vec<u8>) -> io::Result<Option<Fields>> {
58 let mut values: Vec<Option<Vec<u8>>> = Vec::new();
59 let mut len = line.len();
60 let mut buf = line;
61 buf.push(0);
62 let at = |buf: &Vec<u8>, i: usize| buf.get(i).copied().unwrap_or(0);
63 let mut bptr = 0usize;
64 let mut limit = trailing(&buf, len);
65 let mut line_end = limit;
66 let mut line_end_len = len - limit;
67 let mut first_field = true;
68 loop {
69 let mut temp: Vec<u8> = Vec::new();
70 let mut inc = usize::from(bptr < limit);
71 if inc == 1 {
72 let mut t = bptr;
73 while at(&buf, t) != self.delimiter && is_space(at(&buf, t)) {
74 t += 1;
75 }
76 if at(&buf, t) == self.enclosure && t < limit {
77 bptr = t;
78 }
79 }
80 if first_field && bptr == line_end {
81 return Ok(None);
82 }
83 first_field = false;
84 let comp_end;
85 if inc != 0 && at(&buf, bptr) == self.enclosure {
86 let mut state = 0;
87 bptr += 1;
88 let mut hunk = bptr;
89 loop {
91 if inc == 0 {
92 if state == 2 {
93 temp.extend_from_slice(&buf[hunk..bptr - 1]);
94 hunk = bptr;
95 break;
96 }
97 if state == 1 {
98 temp.extend_from_slice(&buf[hunk..bptr]);
99 hunk = bptr;
100 }
101 if hunk != line_end {
102 temp.extend_from_slice(&buf[hunk..bptr]);
103 hunk = bptr;
104 }
105 temp.extend_from_slice(&buf[line_end..line_end + line_end_len]);
106 let next = match self.next_line.as_mut() {
107 Some(next) => next()?,
108 None => None,
109 };
110 match next {
111 None => {
112 if bptr > limit {
113 if hunk == bptr {
114 hunk -= 1;
115 }
116 bptr -= 1;
117 }
118 break;
119 }
120 Some(next) => {
121 len = next.len();
122 buf = next;
123 buf.push(0);
124 bptr = 0;
125 hunk = 0;
126 limit = trailing(&buf, len);
127 line_end = limit;
128 line_end_len = len - limit;
129 state = 0;
130 }
131 }
132 } else {
133 match state {
134 1 => {
135 bptr += 1;
136 state = 0;
137 }
138 2 => {
139 if at(&buf, bptr) != self.enclosure {
140 temp.extend_from_slice(&buf[hunk..bptr - 1]);
141 hunk = bptr;
142 break;
143 }
144 temp.extend_from_slice(&buf[hunk..bptr]);
145 bptr += 1;
146 hunk = bptr;
147 state = 0;
148 }
149 _ => {
150 let b = at(&buf, bptr);
151 if b == self.enclosure {
152 state = 2;
153 } else if self.escape == Some(b) {
154 state = 1;
155 }
156 bptr += 1;
157 }
158 }
159 }
160 inc = usize::from(bptr < limit);
161 }
162 while inc != 0 && at(&buf, bptr) != self.delimiter {
164 bptr += 1;
165 inc = usize::from(bptr < limit);
166 }
167 temp.extend_from_slice(&buf[hunk..bptr]);
168 bptr += inc;
169 comp_end = temp.len();
170 } else {
171 let hunk = bptr;
173 while inc != 0 && at(&buf, bptr) != self.delimiter {
174 bptr += 1;
175 inc = usize::from(bptr < limit);
176 }
177 temp.extend_from_slice(&buf[hunk..bptr]);
178 comp_end = field_end(&temp);
179 if at(&buf, bptr) == self.delimiter {
180 bptr += 1;
181 }
182 }
183 temp.truncate(comp_end);
184 values.push(Some(temp));
185 if inc == 0 {
186 break;
187 }
188 }
189 Ok(Some(values))
190 }
191}
192
193pub fn str_getcsv(input: &[u8], delimiter: u8, enclosure: u8, escape: Option<u8>) -> Fields {
197 let mut p = Parser { delimiter, enclosure, escape, next_line: None };
198 p.parse(input.to_vec()).ok().flatten().unwrap_or_else(|| vec![None])
199}
200
201fn read_line<R: BufRead>(reader: &mut R) -> io::Result<Option<Vec<u8>>> {
203 let mut line = Vec::new();
204 let n = reader.read_until(b'\n', &mut line)?;
205 Ok(if n == 0 { None } else { Some(line) })
206}
207
208pub fn fgetcsv<R: BufRead>(
212 reader: &mut R,
213 delimiter: u8,
214 enclosure: u8,
215 escape: Option<u8>,
216) -> io::Result<Option<Fields>> {
217 let Some(first) = read_line(reader)? else {
218 return Ok(None);
219 };
220 let mut next = || read_line(reader);
221 let mut p = Parser { delimiter, enclosure, escape, next_line: Some(&mut next) };
222 Ok(Some(p.parse(first)?.unwrap_or_else(|| vec![None])))
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 fn f(s: &str) -> Vec<Option<String>> {
230 str_getcsv(s.as_bytes(), b',', b'"', Some(b'"'))
231 .into_iter()
232 .map(|v| v.map(|b| String::from_utf8(b).unwrap()))
233 .collect()
234 }
235
236 #[test]
237 fn fields() {
238 assert_eq!(f("a,b,c"), [Some("a".into()), Some("b".into()), Some("c".into())]);
239 assert_eq!(f(""), [None]);
240 assert_eq!(f("\"a,b\",c"), [Some("a,b".into()), Some("c".into())]);
241 assert_eq!(f("\"a\"\"b\""), [Some("a\"b".into())]);
242 assert_eq!(f("a ,b"), [Some("a ".into()), Some("b".into())]);
243 assert_eq!(f("a,"), [Some("a".into()), Some("".into())]);
244 }
245
246 #[test]
247 fn multi_line() {
248 let mut r = io::Cursor::new(b"\"a\nb\",c\nd\n".to_vec());
249 let row = fgetcsv(&mut r, b',', b'"', Some(b'"')).unwrap().unwrap();
250 assert_eq!(row, vec![Some(b"a\nb".to_vec()), Some(b"c".to_vec())]);
251 let row = fgetcsv(&mut r, b',', b'"', Some(b'"')).unwrap().unwrap();
252 assert_eq!(row, vec![Some(b"d".to_vec())]);
253 assert!(fgetcsv(&mut r, b',', b'"', Some(b'"')).unwrap().is_none());
254 }
255}