1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#![warn(clippy::all, missing_docs, nonstandard_style, future_incompatible)]
#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use csv::StringRecord;
use serde::de::DeserializeOwned;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("quick_csv")]
QuickCsv(#[from] quick_csv::error::Error),
#[error("csv")]
Csv(#[from] csv::Error),
}
pub type Result<T> = core::result::Result<T, Error>;
pub struct CSVLine {
delimiter: u8,
}
impl CSVLine {
pub fn new() -> Self {
Default::default()
}
pub fn delimiter(mut self, delimiter: u8) -> Self {
self.delimiter = delimiter;
self
}
pub fn decode_str<T: DeserializeOwned>(&self, s: &str) -> Result<T> {
let record = if let Some(row) = quick_csv::Csv::from_string(s)
.delimiter(self.delimiter)
.into_iter()
.next()
{
StringRecord::from_iter(row?.columns()?)
} else {
StringRecord::from(vec![""])
};
Ok(record.deserialize(None)?)
}
}
impl Default for CSVLine {
fn default() -> Self {
Self { delimiter: b',' }
}
}
pub fn from_str<T: DeserializeOwned>(s: &str) -> Result<T> {
CSVLine::new().decode_str(s)
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[test]
fn basic() {
#[derive(Debug, PartialEq, Deserialize)]
struct Foo(String);
assert_eq!(from_str::<Foo>("foo").unwrap(), Foo("foo".into()));
}
#[test]
fn empty() {
#[derive(Debug, PartialEq, Deserialize)]
struct Foo(Option<String>);
assert_eq!(from_str::<Foo>("").unwrap(), Foo(None));
}
#[test]
fn types() {
#[derive(Debug, PartialEq, Deserialize)]
struct Foo {
text: String,
maybe_text: Option<String>,
num: i32,
flag: bool,
}
assert_eq!(
from_str::<Foo>(r#""foo,bar",,1,true"#).unwrap(),
Foo {
text: "foo,bar".into(),
maybe_text: None,
num: 1,
flag: true
}
);
}
#[test]
fn tsv() {
#[derive(Debug, PartialEq, Deserialize)]
struct Foo(String, String);
assert_eq!(
CSVLine::new()
.delimiter(b'\t')
.decode_str::<Foo>("foo\tbar")
.unwrap(),
Foo("foo".into(), "bar".into())
);
}
}