anvil_zksync_common/utils/
io.rs1use anyhow::Context;
2use serde::de::DeserializeOwned;
3use serde::Serialize;
4use std::{
5 fs::File,
6 io::{BufWriter, Write},
7 path::Path,
8};
9
10pub fn write_json_file<T: Serialize>(path: &Path, obj: &T) -> anyhow::Result<()> {
13 let file = File::create(path)
14 .with_context(|| format!("Failed to create file '{}'", path.display()))?;
15 let mut writer = BufWriter::new(file);
16 serde_json::to_writer_pretty(&mut writer, obj)
18 .with_context(|| format!("Failed to write JSON to '{}'", path.display()))?;
19 writer
20 .flush()
21 .with_context(|| format!("Failed to flush writer for '{}'", path.display()))?;
22
23 Ok(())
24}
25
26pub fn read_json_file<T: DeserializeOwned>(path: &Path) -> anyhow::Result<T> {
29 let file_content = std::fs::read_to_string(path)
30 .with_context(|| format!("Failed to read file '{}'", path.display()))?;
31
32 serde_json::from_str(&file_content)
33 .with_context(|| format!("Failed to deserialize JSON from '{}'", path.display()))
34}