-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_processing.rs
264 lines (246 loc) · 5.89 KB
/
csv_processing.rs
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
use csv::{Error, ReaderBuilder};
use serde::{de, Deserialize, Deserializer, Serialize};
use std::str::FromStr;
/// Read CSV records from a string.
///
/// # Arguments
///
/// * `csv_data` - A string slice that holds the CSV data.
///
/// # Returns
///
/// A vector of strings, where each string is a record from the CSV data.
///
/// # Example
///
/// ```
/// use encoding::read_csv_records;
///
/// let csv_data = "name,age\nAlice,30\nBob,25\n";
///
/// let records = read_csv_records(csv_data).unwrap();
///
/// assert_eq!(records, vec!["Alice30", "Bob25"]);
/// ```
pub fn read_csv_records(csv_data: &str) -> Result<Vec<String>, Error> {
let mut reader = csv::Reader::from_reader(csv_data.as_bytes());
let mut records = Vec::new();
for result in reader.records() {
let record = result?;
records.push(
record
.iter()
.map(|field| field.to_string())
.collect::<String>(),
);
}
Ok(records)
}
/// A token struct that represents a record in a CSV file.
///
/// # Example
///
/// ```
/// use encoding::Token;
///
/// let token = Token {
/// chain: "Ethereum".to_string(),
/// name: "ETH".to_string(),
/// ticker: "Ether".to_string(),
/// price: 3000.0,
/// };
///
/// assert_eq!(token.chain, "Ethereum");
/// ```
#[derive(Debug, Deserialize)]
pub struct Token {
pub chain: String,
pub name: String,
pub ticker: String,
pub price: f64,
}
/// Read CSV records from a string and deserialize them into a strong type.
///
/// # Arguments
///
/// * `csv_data` - A string slice that holds the CSV data.
/// * `delimiter` - A u8 that represents the delimiter character.
///
/// # Returns
///
/// A vector of tokens, where each token is a record from the CSV data.
///
/// # Example
///
/// ```
/// use encoding::{read_csv_records_custom_delimiter, Token};
///
/// let csv_data = "name;age\nAlice;30\nBob;25\n";
/// let records = read_csv_records_custom_delimiter(csv_data, b';').unwrap();
///
/// assert_eq!(records, vec!["Alice30", "Bob25"]);
/// ```
pub fn read_csv_records_custom_delimiter(
csv_data: &str,
delimiter: u8,
) -> Result<Vec<String>, Error> {
let mut reader = ReaderBuilder::new()
.delimiter(delimiter)
.from_reader(csv_data.as_bytes());
let mut records = Vec::new();
for result in reader.records() {
let record = result?;
records.push(
record
.iter()
.map(|field| field.to_string())
.collect::<String>(),
);
}
Ok(records)
}
/// Filter CSV records that match a predicate.
///
/// # Arguments
///
/// * `csv_data` - A string slice that holds the CSV data.
/// * `query` - A string slice that holds the query to filter the records.
///
/// # Returns
///
/// A vector of strings, where each string is a record from the CSV data that matches the query.
///
/// # Example
///
/// ```
/// use encoding::filter_csv_records_matching_predicate;
///
/// let csv_data = "name,age\nAlice,30\nBob,25\n";
/// let query = "Alice";
///
/// let filtered_records = filter_csv_records_matching_predicate(csv_data, query);
///
/// assert_eq!(filtered_records, vec!["Alice30"]);
/// ```
pub fn filter_csv_records_matching_predicate(csv_data: &str, query: &str) -> Vec<String> {
let mut reader = ReaderBuilder::new().from_reader(csv_data.as_bytes());
let mut filtered_records: Vec<String> = Vec::new();
for result in reader.records() {
let record = result.unwrap();
let record_str = record
.iter()
.map(|field| field.to_string())
.collect::<String>();
if record_str.contains(query) {
filtered_records.push(record_str);
}
}
filtered_records
}
/// A struct that represents a steak record in a CSV file.
///
/// # Example
///
/// ```
/// use encoding::Steak;
///
/// let steak = Steak {
/// name: "T-bone".to_string(),
/// price: 20.0,
/// id: Some(1),
/// };
///
/// assert_eq!(steak.name, "T-bone");
/// ```
#[derive(Debug, Deserialize)]
pub struct Steak {
pub name: String,
pub price: f64,
#[serde(deserialize_with = "csv::invalid_option")]
pub id: Option<u64>,
}
/// Serializable struct that represents a meme coin.
///
/// # Example
///
/// ```
/// use encoding::MemeCoin;
///
/// let meme_coin = MemeCoin {
/// chain: "Ethereum",
/// name: "Pepe",
/// ticker: "PEPE"
/// };
///
/// assert_eq!(meme_coin.chain, "Ethereum");
/// ```
#[derive(Debug, Serialize)]
pub struct MemeCoin<'a> {
pub chain: &'a str,
pub name: &'a str,
pub ticker: &'a str,
}
/// A RGB color struct.
///
/// # Example
///
/// ```
/// use encoding::RgbColor;
///
/// let color = RgbColor {
/// red: 255,
/// green: 0,
/// blue: 0,
/// };
///
/// assert_eq!(color.red, 255);
/// ```
#[derive(Debug)]
pub struct RgbColor {
pub red: u8,
pub green: u8,
pub blue: u8,
}
/// A struct that represents a row in a CSV file.
///
/// # Example
///
/// ```
/// use encoding::{Row, RgbColor};
///
/// let row = Row {
/// color_name: "Red".to_string(),
/// color: RgbColor {
/// red: 255,
/// green: 0,
/// blue: 0,
/// }
/// };
///
/// assert_eq!(row.color_name, "Red");
/// ```
#[derive(Debug, Deserialize)]
pub struct Row {
pub color_name: String,
pub color: RgbColor,
}
impl FromStr for RgbColor {
type Err = Error;
fn from_str(color_name: &str) -> std::result::Result<Self, Self::Err> {
let color = color_name.split(',').collect::<Vec<&str>>();
Ok(RgbColor {
red: color[0].parse().unwrap(),
green: color[1].parse().unwrap(),
blue: color[2].parse().unwrap(),
})
}
}
impl<'de> Deserialize<'de> for RgbColor {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
FromStr::from_str(&s).map_err(de::Error::custom)
}
}