Skip to main content

teaql_tool_extra/
csv.rs

1use csv::{Reader, Writer};
2use teaql_tool_core::{Result, TeaQLToolError};
3
4pub struct CsvTool;
5
6impl CsvTool {
7    pub fn new() -> Self {
8        Self
9    }
10
11    pub fn parse(&self, data: &str) -> Result<Vec<Vec<String>>> {
12        let mut rdr = Reader::from_reader(data.as_bytes());
13        let mut records = Vec::new();
14        for result in rdr.records() {
15            let record = result.map_err(|e| TeaQLToolError::ParseError(e.to_string()))?;
16            records.push(record.iter().map(|s| s.to_string()).collect());
17        }
18        Ok(records)
19    }
20
21    pub fn generate(&self, records: &[Vec<String>]) -> Result<String> {
22        let mut wtr = Writer::from_writer(vec![]);
23        for record in records {
24            wtr.write_record(record).map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
25        }
26        let data = wtr.into_inner().map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
27        String::from_utf8(data).map_err(|e| TeaQLToolError::ParseError(e.to_string()))
28    }
29}
30
31impl Default for CsvTool {
32    fn default() -> Self {
33        Self::new()
34    }
35}