serde_json_file_io/
lib.rs

1#![deny(elided_lifetimes_in_paths)]
2
3use std::{
4    io::{Read, Write},
5};
6
7/*
8 * Writes Instance of PathManager to json file already handles all serialization*/
9pub fn write_to_file<T: serde::Serialize>(object: T, path: &std::path::Path) -> Result<i32, String> {
10    /*
11     * God forgive me for my sins of being too much of a nester*/
12    match path.parent() {
13            Some(p) => {
14                match std::fs::create_dir_all(p) {
15                    Ok(_) => {
16                        match std::fs::File::create(path) {
17                            Ok(mut f) => {
18                                match serde_json::to_string(&object) {
19                                    Ok(data_string) => {
20                                        match f.write_all(data_string.as_bytes()) {
21                                            Ok(_) => Ok(0),
22                                            Err(e) => Err("Error at writing data to file: "
23                                                .to_owned()
24                                                + &e.to_string()),
25                                        } //Match 5 End
26                                    }
27                                    Err(e) => Err("Error at serialization of PathManager: "
28                                        .to_owned()
29                                        + &e.to_string()),
30                                } //Match 4 End
31                            }
32                            Err(e) => Err("Error at file creation: ".to_owned() + &e.to_string()),
33                        } //Match 3 End
34                    }
35                    Err(e) => Err("Error at recurive directory creation after getting the parent directory: ".to_owned() + &e.to_string()),
36                } //Match 2 End
37            }
38            None => Err("Error at parent directory creation: There is no parent directory specified in given path".to_owned()),
39        } //Match 1 End
40}
41
42pub fn read_from_file<'a, T: serde::Deserialize<'a>>(path: &std::path::Path, strbuf: &'a mut String) -> Result<T, String> {
43        /*
44         * These match statements are horrible*/
45        match std::fs::File::open(path) {
46            Ok(mut f) => {
47                match f.read_to_string(strbuf) {
48                    Ok(_) => match serde_json::from_str(strbuf) {
49                        Ok(pm) => pm,
50                        Err(e) => Err("Error deserializing json: ".to_owned() + &e.to_string()),
51                    }, // Match 3 End
52                    Err(e) => Err("Error reading string from file: ".to_owned() + &e.to_string()),
53                } //Match 2 End
54            }
55            Err(e) => Err("Error opening file: ".to_owned() + &e.to_string()),
56        } //Match 1 End
57    }