This repository was archived by the owner on Apr 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvector_exporter.rs
107 lines (96 loc) · 2.87 KB
/
vector_exporter.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
use std::{fs::File, io::Write};
#[derive(Debug, Clone)]
pub enum ExportType {
Text,
Csv,
Json,
}
pub enum ExportError {
IoError(std::io::Error),
JsonError(serde_json::Error),
}
impl Default for ExportType {
fn default() -> Self {
ExportType::Text
}
}
pub trait IVectorExporter<T> {
fn new(vec: Vec<T>, export_type: ExportType, export_type: &str) -> Self;
fn export(&self) -> Result<(), ExportError>;
}
#[derive(Debug, Clone)]
pub struct VectorExporter<T> {
pub vec: Vec<T>,
pub export_type: ExportType,
pub export_path: String,
}
impl IVectorExporter<String> for VectorExporter<String> {
/// Initialize a new `VectorExporter` for type `String`
///
/// # Example
///
/// ```rust
/// let vec_exporter: VectorExporter<String> = IVectorExporter::<String>::new(vec![], ExportType::default(), "/path/to/file");
/// ```
///
/// # Returns
///
/// The `VectorExporter` struct for type `String`
fn new(vec: Vec<String>, export_type: ExportType, export_path: &str) -> VectorExporter<String> {
VectorExporter {
vec,
export_type,
export_path: String::from(export_path),
}
}
/// Export the `Vec` of type `String` to a file
///
/// # Example
///
/// ```rust
/// let res = vec_exporter.export();
/// ```
///
/// # Returns
///
/// A `Result` that can either contain an `Ok` or an `Error` struct
fn export(&self) -> Result<(), ExportError> {
let file = File::create(&self.export_path);
let mut file = match file {
Ok(file) => file,
Err(e) => return Err(ExportError::IoError(e)),
};
match self.export_type {
ExportType::Text => {
let mut data = String::new();
for l in &self.vec {
data.push_str(&format!("{}\n", l));
}
match write!(file, "{}", data) {
Ok(_) => Ok(()),
Err(e) => Err(ExportError::IoError(e)),
}
}
ExportType::Csv => {
let mut data = String::new();
for l in &self.vec {
data.push_str(&format!("\"{}\"\n", l));
}
match write!(file, "{}", data) {
Ok(_) => Ok(()),
Err(e) => Err(ExportError::IoError(e)),
}
}
ExportType::Json => {
let serialized = match serde_json::to_string(&self.vec) {
Ok(d) => d,
Err(e) => return Err(ExportError::JsonError(e)),
};
match write!(file, "{}", serialized) {
Ok(_) => Ok(()),
Err(e) => Err(ExportError::IoError(e)),
}
}
}
}
}