darkfi/util/
file.rs

1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2026 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use std::{
20    fs::File,
21    io::{BufReader, Read, Write},
22    path::Path,
23};
24
25use tinyjson::JsonValue;
26
27use crate::Result;
28
29pub fn load_file(path: &Path) -> Result<String> {
30    let file = File::open(path)?;
31    let mut reader = BufReader::new(file);
32    let mut st = String::new();
33    reader.read_to_string(&mut st)?;
34    Ok(st)
35}
36
37pub fn save_file(path: &Path, st: &str) -> Result<()> {
38    let mut file = File::create(path)?;
39    file.write_all(st.as_bytes())?;
40    Ok(())
41}
42
43pub fn load_json_file(path: &Path) -> Result<JsonValue> {
44    let st = load_file(path)?;
45    Ok(st.parse()?)
46}
47
48pub fn save_json_file(path: &Path, value: &JsonValue, pretty: bool) -> Result<()> {
49    let mut file = File::create(path)?;
50
51    if pretty {
52        value.format_to(&mut file)?;
53    } else {
54        value.write_to(&mut file)?;
55    }
56
57    Ok(())
58}