csv_perusal/
open.rs

1use std::{fs::File, path::Path, io::BufReader};
2
3use crate::errors::CSVPerusalError;
4
5/// Opens a csv file and extract the contents as a vector of [`csv::ByteRecord`].
6pub fn csv_read(path: &str) -> Result<Vec<csv::ByteRecord>, CSVPerusalError> {
7    match File::open(Path::new(&path)) {
8        Ok(file_handle) => {
9            let reader = BufReader::new(file_handle);
10            let mut data: Vec<csv::ByteRecord> = Vec::new();
11            // Build the CSV reader and iterate over each record.
12            let mut rdr = csv::ReaderBuilder::new()
13                .has_headers(false)
14                .from_reader(reader);
15            for result in rdr.byte_records() {
16                match result {
17                    Ok(record) => data.push(record),
18                    Err(e) => return Err(CSVPerusalError::FileError(e)),
19                };
20            }
21            return Ok(data)
22        },
23        Err(e) => return Err(CSVPerusalError::IOError(e)),
24    };
25}