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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use std::path::{PathBuf, Path};
use std::fs::{File, canonicalize, OpenOptions, metadata};
use std::io::{self, Write};
pub trait AsCsv {
fn as_csv(&self) -> String;
fn filename(&self) -> String;
fn header(&self) -> &'static str;
}
#[derive(Debug)]
pub struct ResultsFile {
pub path: PathBuf,
handle: File
}
impl ResultsFile {
pub fn new<P: AsRef<Path>>(path: P, header: &str) -> Result<ResultsFile, io::Error> {
let handle = OpenOptions::new().append(true).create(true).open(&path)?;
let full_path = canonicalize(path)?;
let mut rf = ResultsFile {
path: full_path,
handle
};
if rf.length() == 0 {
if let Err(e) = rf.append(header) {
return Err(io::Error::from(e));
}
}
Ok(rf)
}
pub fn for_item<I: AsCsv>(item: &I) -> Result<ResultsFile, io::Error> {
ResultsFile::new(item.filename(), item.header())
}
pub fn length(&self) -> u64 {
let m = metadata(&self.path).expect("File does not exist or this process does not have permission to access it");
m.len()
}
pub fn append(&mut self, record: &str) -> io::Result<usize> {
self.handle.write(record.as_bytes())
}
pub fn write_csv<R: AsCsv>(&mut self, record: &R) -> io::Result<usize> {
self.append(&format!("{}\n", record.as_csv()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::{canonicalize, remove_file, create_dir};
pub struct Point {
x: i32,
y: i32
}
impl AsCsv for Point {
fn as_csv(&self) -> String {
format!("{},{}", self.x, self.y)
}
fn filename(&self) -> String {
String::from("points.csv")
}
fn header(&self) -> &'static str {
"x,y\n"
}
}
fn header() -> &'static str {
"x,y"
}
fn test_dir() -> PathBuf {
let path = canonicalize(".").expect("test_data dir missing. Are you in the right directory?");
let mut dir = PathBuf::from(path);
dir.push("test_data/");
match create_dir(&dir) {
Ok(_) => return dir,
Err(_) => return dir
};
}
fn delete<P: AsRef<Path>>(file: P) {
match remove_file(file) {
Ok(_) => {},
Err(_) => {}
}
}
#[test]
fn test_new_results_file_creates_file() {
let mut file = test_dir();
file.push("results_file.csv");
let rf = ResultsFile::new(&file, header()).unwrap();
assert!(rf.path.to_str().unwrap().contains("results_file.csv"));
delete(file);
}
#[test]
fn test_works_with_abs_or_rel_path() {
let rel = PathBuf::from("./test_data/rel.csv");
assert!(!rel.exists());
assert!(rel.is_relative());
let _ = ResultsFile::new(&rel, header()).expect("Couldn't create results file");
assert!(rel.exists());
delete(&rel);
let mut abs = PathBuf::from(canonicalize("./test_data/").unwrap());
abs.push("abs.csv");
assert!(!abs.exists());
assert!(!abs.is_relative());
let _ = ResultsFile::new(&abs, header()).expect("Couldn't create results file");
assert!(abs.exists());
delete(&abs);
let slice = "./test_data/str.csv";
let _ = ResultsFile::new(&slice, header());
let slice_buf = PathBuf::from(&slice);
assert!(slice_buf.exists());
delete(slice_buf);
}
#[test]
fn test_get_length() {
let mut file = test_dir();
file.push("length.csv");
let rf = ResultsFile::new(&file, header()).unwrap();
assert!(rf.length() == 3);
delete(&file);
}
#[test]
fn test_append() {
let content = "here's some content to write";
let mut file = test_dir();
file.push("append.csv");
let mut rf = ResultsFile::new(&file, header()).unwrap();
assert!(rf.length() == 3);
rf.append(&content).expect("Couldn't write to results file");
rf.append(&content).expect("Couldn't write to results file");
rf.append(&content).expect("Couldn't write to results file");
assert!(rf.length() > 3);
delete(&file);
}
#[test]
fn test_write_csv() {
let mut file = test_dir();
file.push("write_csv.csv");
let point = Point { x: 5, y: 7 };
let mut rf = ResultsFile::new(&file, header()).unwrap();
assert!(rf.length() == 3);
let result = rf.write_csv(&point);
assert!(result.is_ok());
assert!(rf.length() > 3);
delete(&file);
}
#[test]
fn test_results_file_for_csv_item() {
let point = Point { x: 32, y: 37 };
let rf = ResultsFile::for_item(&point).expect("Couldn't make file");
assert!(format!("{}", rf.path.display()).contains(&point.filename()));
delete(point.filename());
}
}