1use std::io::Write;
6
7use serde_json::{Map, Value};
8
9use crate::error::Result;
10
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
16pub enum Format {
17 #[default]
19 Tsv,
20 Csv,
22 Json,
24}
25
26impl Format {
27 pub fn accept(self) -> &'static str {
29 match self {
30 Format::Tsv => "text/tab-separated-values",
31 Format::Csv => "text/csv",
32 Format::Json => "application/json",
33 }
34 }
35}
36
37#[derive(Debug, Clone, Default, PartialEq)]
39pub struct Table {
40 pub header: Vec<String>,
42 pub rows: Vec<Vec<Value>>,
44}
45
46impl Table {
47 pub fn new(header: &[&str]) -> Self {
49 Self {
50 header: header.iter().map(|h| h.to_string()).collect(),
51 rows: Vec::new(),
52 }
53 }
54
55 pub fn push(&mut self, row: Vec<Value>) {
58 assert_eq!(row.len(), self.header.len(), "row length must match header");
59 self.rows.push(row);
60 }
61
62 pub fn write(&self, format: Format, out: &mut impl Write) -> Result<()> {
64 match format {
65 Format::Tsv | Format::Csv => {
66 let line = |cells: Vec<String>| -> String {
67 match format {
68 Format::Csv => cells.iter().map(|c| csv_escape(c)).collect::<Vec<_>>().join(","),
69 _ => cells.iter().map(|c| tsv_escape(c)).collect::<Vec<_>>().join("\t"),
70 }
71 };
72 writeln!(out, "{}", line(self.header.clone()))?;
73 for row in &self.rows {
74 writeln!(out, "{}", line(row.iter().map(cell_text).collect()))?;
75 }
76 }
77 Format::Json => {
78 let objects = self
79 .rows
80 .iter()
81 .map(|row| {
82 Value::Object(
83 self.header.iter().cloned().zip(row.iter().cloned()).collect::<Map<_, _>>(),
84 )
85 })
86 .collect::<Vec<_>>();
87 writeln!(out, "{}", serde_json::to_string_pretty(&Value::Array(objects))?)?;
88 }
89 }
90 Ok(())
91 }
92
93 pub fn print(&self, format: Format) -> Result<()> {
95 let mut out = std::io::BufWriter::new(std::io::stdout().lock());
96 self.write(format, &mut out)?;
97 out.flush()?;
98 Ok(())
99 }
100}
101
102pub fn cell_text(value: &Value) -> String {
105 match value {
106 Value::Null => String::new(),
107 Value::String(s) => s.clone(),
108 Value::Array(values) => values.iter().map(cell_text).collect::<Vec<_>>().join(";"),
109 other => other.to_string(),
110 }
111}
112
113fn tsv_escape(text: &str) -> String {
115 text.replace(['\t', '\n', '\r'], " ")
116}
117
118fn csv_escape(text: &str) -> String {
120 if text.contains([',', '"', '\n', '\r']) {
121 format!("\"{}\"", text.replace('"', "\"\""))
122 } else {
123 text.to_string()
124 }
125}
126
127pub fn epoch_millis_to_date(millis: i64) -> String {
130 let z = millis.div_euclid(86_400_000) + 719_468;
132 let era = z.div_euclid(146_097);
133 let doe = z - era * 146_097;
134 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
135 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
136 let mp = (5 * doy + 2) / 153;
137 let day = doy - (153 * mp + 2) / 5 + 1;
138 let month = if mp < 10 { mp + 3 } else { mp - 9 };
139 let year = yoe + era * 400 + i64::from(month <= 2);
140 format!("{:04}-{:02}-{:02}", year, month, day)
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146 use serde_json::json;
147
148 fn sample() -> Table {
149 let mut table = Table::new(&["name", "count", "tags"]);
150 table.push(vec![json!("Homo sapiens"), json!(3), json!(["a", "b"])]);
151 table.push(vec![json!("comma, \"quote\""), Value::Null, json!([])]);
152 table
153 }
154
155 fn render(table: &Table, format: Format) -> String {
156 let mut out = Vec::new();
157 table.write(format, &mut out).unwrap();
158 String::from_utf8(out).unwrap()
159 }
160
161 #[test]
162 fn test_tsv() {
163 assert_eq!(
164 render(&sample(), Format::Tsv),
165 "name\tcount\ttags\nHomo sapiens\t3\ta;b\ncomma, \"quote\"\t\t\n"
166 );
167 }
168
169 #[test]
170 fn test_csv_quotes_when_needed() {
171 assert_eq!(
172 render(&sample(), Format::Csv),
173 "name,count,tags\nHomo sapiens,3,a;b\n\"comma, \"\"quote\"\"\",,\n"
174 );
175 }
176
177 #[test]
178 fn test_json_objects_keep_types() {
179 let parsed: Value = serde_json::from_str(&render(&sample(), Format::Json)).unwrap();
180 assert_eq!(parsed[0], json!({"name": "Homo sapiens", "count": 3, "tags": ["a", "b"]}));
181 assert_eq!(parsed[1]["count"], Value::Null);
182 }
183
184 #[test]
185 fn test_tsv_replaces_tabs_and_newlines() {
186 let mut table = Table::new(&["x"]);
187 table.push(vec![json!("a\tb\nc")]);
188 assert_eq!(render(&table, Format::Tsv), "x\na b c\n");
189 }
190
191 #[test]
192 fn test_epoch_millis_to_date() {
193 assert_eq!(epoch_millis_to_date(0), "1970-01-01");
194 assert_eq!(epoch_millis_to_date(1_293_840_000_000), "2011-01-01");
195 assert_eq!(epoch_millis_to_date(951_782_400_000), "2000-02-29");
196 assert_eq!(epoch_millis_to_date(-86_400_000), "1969-12-31");
197 }
198}