serde_json_file_io/
lib.rs1#![deny(elided_lifetimes_in_paths)]
2
3use std::{
4 io::{Read, Write},
5};
6
7pub fn write_to_file<T: serde::Serialize>(object: T, path: &std::path::Path) -> Result<i32, String> {
10 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 } }
27 Err(e) => Err("Error at serialization of PathManager: "
28 .to_owned()
29 + &e.to_string()),
30 } }
32 Err(e) => Err("Error at file creation: ".to_owned() + &e.to_string()),
33 } }
35 Err(e) => Err("Error at recurive directory creation after getting the parent directory: ".to_owned() + &e.to_string()),
36 } }
38 None => Err("Error at parent directory creation: There is no parent directory specified in given path".to_owned()),
39 } }
41
42pub fn read_from_file<'a, T: serde::Deserialize<'a>>(path: &std::path::Path, strbuf: &'a mut String) -> Result<T, String> {
43 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 }, Err(e) => Err("Error reading string from file: ".to_owned() + &e.to_string()),
53 } }
55 Err(e) => Err("Error opening file: ".to_owned() + &e.to_string()),
56 } }