kvds/
encode_to_file.rs

1use std::fs::File;
2use std::io::prelude::*;
3
4#[derive(Debug)]
5pub enum EncodeToFileError {
6    EncodeError(crate::EncodeError),
7    IOError(std::io::Error),
8}
9
10use EncodeToFileError::*;
11
12/// Encodes a key-value list to a file.
13///
14/// # Example
15///
16/// ```rust
17/// # use kvds::EncodeToFileError;
18/// #
19/// # fn main() -> Result<(), Box<EncodeToFileError>> {
20/// #
21/// let data = vec![
22///     (1, "Hello".as_bytes().to_vec()),
23///     (2, ", ".as_bytes().to_vec()),
24///     (4, "world".as_bytes().to_vec()),
25///     (1, "!".as_bytes().to_vec()),
26/// ];
27///
28/// kvds::encode_to_file("data", data)?;
29/// #
30/// # Ok(())
31/// # }
32/// ```
33///
34/// # Errors
35///
36/// This function returns an error if something goes wrong with creating or writing
37/// to a file, or an error occurs in encoding the data.
38pub fn encode_to_file(name: &str, data: Vec<(u8, Vec<u8>)>) -> Result<(), EncodeToFileError> {
39    let mut file = match File::create(name) {
40        Ok(f) => f,
41        Err(e) => return Err(IOError(e)),
42    };
43
44    let encoded_data = match crate::encode(data) {
45        Ok(d) => d,
46        Err(e) => return Err(EncodeError(e)),
47    };
48
49    if let Err(e) = file.write_all(&encoded_data) {
50        return Err(IOError(e));
51    }
52
53    Ok(())
54}