# Input Output Operations This module defines the input and output operations for [`CSVBinaryMatrix`]. [`CSVBinaryMatrix`]: crate::matrix::CSVBinaryMatrix For the following we consider this matrix: ```rust use csvbinmatrix::prelude::CSVBinaryMatrix; CSVBinaryMatrix::try_from(&[ [0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1], ]).unwrap(); ``` ## Write to a file without consuming the matrix ```rust # use csvbinmatrix::prelude::CSVBinaryMatrix; # # let matrix = CSVBinaryMatrix::try_from(&[ # [0, 0, 0], # [0, 0, 1], # [0, 1, 1], # [1, 1, 1], # ]).unwrap(); # match matrix.to_file("mymatrix.csvbm") { Ok(_) => println!("[INFO] File created"), Err(e) => println!("[ERROR] creating file fails: {e}"), } # std::fs::remove_file("mymatrix.csvbm").unwrap_or(()); // You can still use `matrix` assert_eq!(matrix.number_of_ones(), 6); ``` ## Efficiently write and read a file with consuming the matrix ```rust use csvbinmatrix::prelude::CSVBinaryMatrix; # # let matrix = CSVBinaryMatrix::try_from(&[ # [0, 0, 0], # [0, 0, 1], # [0, 1, 1], # [1, 1, 1], # ]).unwrap(); # let expected_matrix_from_file = matrix.clone(); match matrix.into_file("mymatrix.csvbm") { Ok(_) => println!("[INFO] File created"), Err(e) => println!("[ERROR] creating file fails: {e}"), } // `matrix` is consumed so you cannot use it anymore. let matrix_from_file = match CSVBinaryMatrix::try_from_file("mymatrix.csvbm") { Ok(m) => m, Err(e) => panic!("[ERROR] reading file fails: {e}"), }; assert_eq!(matrix_from_file, expected_matrix_from_file); # std::fs::remove_file("mymatrix.csvbm").unwrap_or(()); ``` ## The CSVBM file format for CSV binary matrices A conventional CSVBM file has the `.csvbm` extension. The CSVBM format is as follows: ```text number_of_rows number_of_columns number_of_ones is_reversed distance_1 distance_2 ... distance_number_of_ones ``` Where: * `number_of_rows` is the number of rows of the matrix. * `number_of_columns` is the number of columns of the matrix. * `number_of_ones` is the number of ones in the matrix. * `is_reversed` is a 0-1 boolean value indicating whether the matrix is reversed or not. Depending on the method you use to store the matrix into a file, the meaning of the distances differs. * If `is_reversed` is `0`: * `distance_i` is the distance between the i-th and the (i+1)-th ones. * `distance_1` is the distance between the first cell and the first one. * Otherwise, `is_reversed` is `1`: * `distance_i` is the distance between the (i+1)-th and the i-th one. * `distance_1` is the distance between the last cell and the last one. ### Example For the matrix: ```text 1 1 1 1 0 0 0 1 0 ``` The CSVBM file can either be: ```text 3 3 5 0 0 1 1 1 4 ``` or (note the `is_reversed` bool set to `1`): ```text 3 3 5 1 1 4 1 1 1 ```