anvil_zksync_common/utils/
io.rs

1use anyhow::Context;
2use serde::de::DeserializeOwned;
3use serde::Serialize;
4use std::{
5    fs::File,
6    io::{BufWriter, Write},
7    path::Path,
8};
9
10/// Writes the given serializable object as JSON to the specified file path using pretty printing.
11/// Returns an error if the file cannot be created or if serialization/writing fails.
12pub 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    // Note: intentionally using pretty printing for better readability.
17    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
26/// Reads the JSON file at the specified path and deserializes it into the provided type.
27/// Returns an error if the file cannot be read or deserialization fails.
28pub 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}