file.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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. use std::{
  19. fs::File,
  20. io::{BufReader, Read, Write},
  21. path::Path,
  22. };
  23. use tinyjson::JsonValue;
  24. use crate::Result;
  25. pub fn load_file(path: &Path) -> Result<String> {
  26. let file = File::open(path)?;
  27. let mut reader = BufReader::new(file);
  28. let mut st = String::new();
  29. reader.read_to_string(&mut st)?;
  30. Ok(st)
  31. }
  32. pub fn save_file(path: &Path, st: &str) -> Result<()> {
  33. let mut file = File::create(path)?;
  34. file.write_all(st.as_bytes())?;
  35. Ok(())
  36. }
  37. pub fn load_json_file(path: &Path) -> Result<JsonValue> {
  38. let st = load_file(path)?;
  39. Ok(st.parse()?)
  40. }
  41. pub fn save_json_file(path: &Path, value: &JsonValue, pretty: bool) -> Result<()> {
  42. let mut file = File::create(path)?;
  43. if pretty {
  44. value.format_to(&mut file)?;
  45. } else {
  46. value.write_to(&mut file)?;
  47. }
  48. Ok(())
  49. }