use crate::io::error::IoResult;
use serde::{Deserialize, Serialize};
use std::io::{Read, Write};
pub fn read_json<T, R>(reader: &mut R) -> IoResult<T>
where
T: for<'de> Deserialize<'de>,
R: Read,
{
let mut buffer = Vec::new();
reader.read_to_end(&mut buffer)?;
let value = serde_json::from_slice(&buffer)?;
Ok(value)
}
pub fn write_json<T, W>(data: &T, writer: &mut W) -> IoResult<()>
where
T: Serialize,
W: Write,
{
let json_string = serde_json::to_string_pretty(data)?;
writer.write_all(json_string.as_bytes())?;
Ok(())
}
#[allow(dead_code)]
pub fn read_json_with_options<T, R>(reader: &mut R, pretty: bool) -> IoResult<T>
where
T: for<'de> Deserialize<'de>,
R: Read,
{
let mut buffer = Vec::new();
reader.read_to_end(&mut buffer)?;
if pretty {
let value = serde_json::from_slice(&buffer)?;
Ok(value)
} else {
let value = serde_json::from_slice(&buffer)?;
Ok(value)
}
}
#[allow(dead_code)]
pub fn write_json_with_options<T, W>(data: &T, writer: &mut W, pretty: bool) -> IoResult<()>
where
T: Serialize,
W: Write,
{
let json_string = if pretty {
serde_json::to_string_pretty(data)?
} else {
serde_json::to_string(data)?
};
writer.write_all(json_string.as_bytes())?;
Ok(())
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct JsonConfig {
pub pretty: bool,
pub include_null: bool,
}
impl JsonConfig {
pub fn new() -> Self {
Self {
pretty: true,
include_null: false,
}
}
pub fn compact() -> Self {
Self {
pretty: false,
include_null: false,
}
}
pub fn pretty() -> Self {
Self {
pretty: true,
include_null: false,
}
}
}
impl Default for JsonConfig {
fn default() -> Self {
Self::new()
}
}
#[allow(dead_code)]
pub struct JsonReader {
config: JsonConfig,
}
impl JsonReader {
pub fn new() -> Self {
Self {
config: JsonConfig::new(),
}
}
pub fn with_config(config: JsonConfig) -> Self {
Self { config }
}
pub fn read<T, R>(&self, reader: &mut R) -> IoResult<T>
where
T: for<'de> Deserialize<'de>,
R: Read,
{
read_json(reader)
}
}
impl Default for JsonReader {
fn default() -> Self {
Self::new()
}
}
#[allow(dead_code)]
pub struct JsonWriter {
config: JsonConfig,
}
impl JsonWriter {
pub fn new() -> Self {
Self {
config: JsonConfig::new(),
}
}
pub fn with_config(config: JsonConfig) -> Self {
Self { config }
}
pub fn write<T, W>(&self, data: &T, writer: &mut W) -> IoResult<()>
where
T: Serialize,
W: Write,
{
write_json_with_options(data, writer, self.config.pretty)
}
}
impl Default for JsonWriter {
fn default() -> Self {
Self::new()
}
}