use std::fs::{read_to_string, write};
use std::io::{BufWriter, Write};
use std::path::Path;
use serde::{Deserialize, Serialize};
#[allow(clippy::module_name_repetitions)]
pub trait FromJson: for<'de> Deserialize<'de> {
fn from_json_file(filename: impl AsRef<Path>) -> anyhow::Result<Self> {
<Self as FromJson>::from_json_string(&read_to_string(filename)?)
}
fn from_json_string(text: &str) -> anyhow::Result<Self> {
Ok(serde_json::from_str(text)?)
}
}
#[allow(clippy::module_name_repetitions)]
pub trait ToJson: Serialize {
fn write_json<W>(&self, writer: W) -> anyhow::Result<()>
where
W: Write,
{
Ok(serde_json::to_writer(writer, self)?)
}
fn write_json_pretty<W>(&self, writer: W) -> anyhow::Result<()>
where
W: Write,
{
Ok(serde_json::to_writer_pretty(writer, self)?)
}
fn to_json(&self) -> anyhow::Result<String> {
Ok(serde_json::to_string(self)?)
}
fn to_json_pretty(&self) -> anyhow::Result<String> {
let mut writer = BufWriter::new(Vec::new());
<Self as ToJson>::write_json_pretty(self, &mut writer)?;
Ok(String::from_utf8(writer.into_inner()?)?)
}
fn write_to_json_file(&self, filename: impl AsRef<Path>) -> anyhow::Result<()> {
Ok(write(filename, <Self as ToJson>::to_json(self)?)?)
}
fn write_to_json_file_pretty(&self, filename: impl AsRef<Path>) -> anyhow::Result<()> {
Ok(write(filename, <Self as ToJson>::to_json_pretty(self)?)?)
}
}