Skip to main content

php_std/
csv.rs

1//! CSV parsing: `str_getcsv()` and `fgetcsv()`.
2//!
3//! A port of `php_fgetcsv()` (`ext/standard/file.c`, PHP 8.5): fields are
4//! split at the delimiter; a field starting (after leading whitespace) with
5//! the enclosure runs to the closing enclosure, a doubled enclosure is one
6//! enclosure character, an escape character protects the next byte (and is
7//! kept), and text after the closing enclosure up to the delimiter is
8//! appended raw. Unenclosed fields lose trailing whitespace; the line's
9//! trailing `\r\n`, `\n` or `\r` is dropped. An enclosure left open takes the
10//! following lines (`fgetcsv()`) or runs to the end of the input
11//! (`str_getcsv()`). A blank line is one `null` field.
12//!
13//! Bytes are characters: the dev image's C library counts one byte per
14//! character in the default locale, so no multibyte sequence is special.
15
16use std::io::{self, BufRead};
17
18/// One parsed line: its fields, or `[null]` (`None`) for a blank line.
19pub 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
25/// `php_fgetcsv_lookup_trailing_spaces()`: the end of `buf` without its
26/// final line ending.
27fn 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
40/// Unenclosed fields keep everything up to the line end; `php_fgetcsv`
41/// trims trailing spaces only from the end of the field data it copied
42/// with `php_fgetcsv_lookup_trailing_spaces`, which strips one line ending.
43fn 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    /// `php_fgetcsv()`. `buf` gets a NUL appended, as the C buffer has one:
56    /// the parser reads up to one byte past the line's end.
57    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                // 2A. The enclosed part.
90                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                // Up to the delimiter.
163                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                // 2B. An unenclosed field.
172                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
193/// PHP `str_getcsv($string, $separator, $enclosure, $escape)`: the fields of
194/// `input` (an enclosure left open runs to the end); `escape` `None` is
195/// `""` (no escape character).
196pub 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
201/// Reads one line, up to and including `\n` (`php_stream_get_line()`).
202fn 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
208/// PHP `fgetcsv($stream, 0, $separator, $enclosure, $escape)`: the fields of
209/// the next record (an open enclosure takes the following lines), or `None`
210/// at the end of the stream (PHP's `false`).
211pub 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}