diff options
| author | Benedict Börger <benedict@0xb8000.de> | 2018-12-17 21:34:36 +0100 |
|---|---|---|
| committer | Benedict Börger <benedict@0xb8000.de> | 2018-12-17 21:34:36 +0100 |
| commit | 7fcdc3ecc0f077ff7ff4ec57c912beae4f974fdb (patch) | |
| tree | b0ecd5e6f008c2326b8dc96ca12c54632e2a8bff /src/Csv/mod.rs | |
[finz] inital commit
Diffstat (limited to 'src/Csv/mod.rs')
| -rw-r--r-- | src/Csv/mod.rs | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/Csv/mod.rs b/src/Csv/mod.rs new file mode 100644 index 0000000..29e1aca --- /dev/null +++ b/src/Csv/mod.rs @@ -0,0 +1,62 @@ +use std::fs::File; +use std::io; +use std::io::BufRead; + +/** + Represents a CSV file + **/ + +pub struct CsvFile { + path : String, + delim : String, + pub header : Vec<String>, + pub content : Vec<Vec<String>>, + has_header : bool +} + +impl CsvFile { + pub fn new(path: &str, delim: &str, header: bool) -> CsvFile { + CsvFile { + path : String::from(path), + delim: String::from(delim), + header : Vec::new(), + content : Vec::new(), + has_header : header + } + + } + + // TODO nicht gleich viele spalten + fn parse_line(line : String, delim: &str) -> Vec<String> { + let mut columns : Vec<String> = Vec::new(); + for column in line.split(delim).collect::<Vec<&str>>() { + columns.push(column.to_string()); + } + columns + } + + + pub fn read_file(path: &str, delim: &str, header: bool) -> Result<CsvFile, io::Error> { + let fd = File::open(path)?; + let reader = io::BufReader::new(fd); + let mut column_names : Vec<String> = Vec::new(); + let mut lines : Vec<Vec<String>> = Vec::new(); + let mut first = true; + + for line in reader.lines() { + let line = line?; + if header && first { + column_names.append(&mut CsvFile::parse_line(line, delim)); + first = false; + } else { + lines.push(CsvFile::parse_line(line, delim)); + } + } + + Ok(CsvFile { path: String::from(path), + delim : String::from(delim), + header : column_names, + content : lines, + has_header: header } ) + } +} |
