1use crate::*;
4
5pub fn from_csv(input: &str, group_name: &str) -> Vec<u8> {
8 let rows = parse_csv(input);
9 if rows.is_empty() {
10 return Vec::new();
11 }
12 let headers: Vec<&str> = rows[0].iter().map(String::as_str).collect();
13 Builder::build(|b| {
14 b.group(group_name, Some(&headers));
15 for row in &rows[1..] {
16 b.record(row);
17 }
18 })
19}
20
21pub fn to_csv(buf: &[u8]) -> Result<String> {
25 to_csv_group(buf, None)
26}
27
28pub fn to_csv_group(buf: &[u8], group_name: Option<&str>) -> Result<String> {
30 let doc = Document::new(buf)?;
31 let g = match group_name {
32 Some(name) => doc
33 .groups()
34 .find(|g| g.name() == name.as_bytes())
35 .ok_or_else(|| Error::Key(format!("no group named '{name}'")))?,
36 None => doc
37 .groups()
38 .next()
39 .ok_or_else(|| Error::other("no group in buffer"))?,
40 };
41 let mut out = String::new();
42 if g.has_header() {
43 let row: Vec<String> = g
44 .headers()
45 .iter()
46 .map(|h| csv_quote(&String::from_utf8_lossy(h)))
47 .collect();
48 out.push_str(&row.join(","));
49 out.push('\n');
50 }
51 for rec in g.records() {
52 let mut row = Vec::new();
53 for (i, f) in rec.fields().into_iter().enumerate() {
54 if is_level(f) {
55 return Err(Error::other(format!(
56 "CSV cannot carry a nested level (group '{}', field {})",
57 String::from_utf8_lossy(g.name()),
58 i + 1
59 )));
60 } else if is_reference(f) {
61 let r = Reference::parse(f)?;
62 let segs: Vec<String> = r
63 .path()
64 .iter()
65 .map(|s| String::from_utf8_lossy(s).into_owned())
66 .collect();
67 row.push(csv_quote(&segs.join("/")));
68 } else {
69 row.push(csv_quote(&String::from_utf8_lossy(&value(f)?)));
70 }
71 }
72 out.push_str(&row.join(","));
73 out.push('\n');
74 }
75 Ok(out)
76}
77
78fn parse_csv(input: &str) -> Vec<Vec<String>> {
81 let mut rows: Vec<Vec<String>> = Vec::new();
82 let mut row: Vec<String> = Vec::new();
83 let mut field = String::new();
84 let mut in_quotes = false;
85 let mut started = false;
86 let mut chars = input.chars().peekable();
87
88 while let Some(ch) = chars.next() {
89 started = true;
90 if in_quotes {
91 if ch == '"' {
92 if chars.peek() == Some(&'"') {
93 field.push('"');
94 chars.next();
95 } else {
96 in_quotes = false;
97 }
98 } else {
99 field.push(ch);
100 }
101 } else {
102 match ch {
103 '"' => in_quotes = true,
104 ',' => row.push(std::mem::take(&mut field)),
105 '\n' => {
106 row.push(std::mem::take(&mut field));
107 rows.push(std::mem::take(&mut row));
108 started = false;
109 }
110 '\r' => {}
111 _ => field.push(ch),
112 }
113 }
114 }
115 if started || !field.is_empty() || !row.is_empty() {
116 row.push(field);
117 rows.push(row);
118 }
119 rows
120}
121
122fn csv_quote(field: &str) -> String {
124 if field.contains([',', '"', '\n', '\r']) {
125 let mut s = String::with_capacity(field.len() + 2);
126 s.push('"');
127 for ch in field.chars() {
128 if ch == '"' {
129 s.push('"');
130 }
131 s.push(ch);
132 }
133 s.push('"');
134 s
135 } else {
136 field.to_string()
137 }
138}