causal_hub/io/
csv.rs

1/// A trait for reading and writing CSV files.
2pub trait CsvIO: Sized {
3    /// Create an instance of the type from a CSV string.
4    ///
5    /// # Arguments
6    ///
7    /// * `csv` - The CSV string to parse.
8    ///
9    /// # Returns
10    ///
11    /// A new instance of the type.
12    ///
13    fn from_csv(csv: &str) -> Self;
14
15    /// Convert the instance to a CSV string.
16    ///
17    /// # Returns
18    ///
19    /// A CSV string representation of the instance.
20    ///
21    fn to_csv(&self) -> String;
22
23    /// Create an instance of the type from a CSV file.
24    ///
25    /// # Arguments
26    ///
27    /// * `path` - The path to the CSV file to read.
28    ///
29    /// # Returns
30    ///
31    /// A new instance of the type.
32    ///
33    fn read_csv(path: &str) -> Self {
34        // TODO: Reading the entire file to a string is not efficient.
35        Self::from_csv(&std::fs::read_to_string(path).expect("Failed to read CSV file."))
36    }
37
38    /// Write the instance to a CSV file.
39    ///
40    /// # Arguments
41    ///
42    /// * `path` - The path to the CSV file to write.
43    ///
44    fn write_csv(&self, path: &str) {
45        std::fs::write(path, self.to_csv()).expect("Failed to write CSV file.");
46    }
47}