use crate::decode::decode;
use crate::encode::encode;
use crate::error::Error;
use crate::options::{DecodeOptions, EncodeOptions};
use serde::{de::DeserializeOwned, Serialize};
use std::io::{Read, Write};
pub fn to_string<T: Serialize>(value: &T) -> Result<String, Error> {
let json_value =
serde_json::to_value(value).map_err(|e| Error::Serialization(e.to_string()))?;
encode(&json_value, None)
}
pub fn to_string_with_options<T: Serialize>(
value: &T,
options: &EncodeOptions,
) -> Result<String, Error> {
let json_value =
serde_json::to_value(value).map_err(|e| Error::Serialization(e.to_string()))?;
encode(&json_value, Some(options))
}
pub fn to_writer<T: Serialize, W: Write>(value: &T, writer: &mut W) -> Result<(), Error> {
let toon = to_string(value)?;
writer
.write_all(toon.as_bytes())
.map_err(|e| Error::Io(e.to_string()))?;
Ok(())
}
pub fn to_writer_with_options<T: Serialize, W: Write>(
value: &T,
writer: &mut W,
options: &EncodeOptions,
) -> Result<(), Error> {
let toon = to_string_with_options(value, options)?;
writer
.write_all(toon.as_bytes())
.map_err(|e| Error::Io(e.to_string()))?;
Ok(())
}
pub fn from_str<T: DeserializeOwned>(s: &str) -> Result<T, Error> {
from_str_with_options(s, None)
}
pub fn from_str_with_options<T: DeserializeOwned>(
s: &str,
options: Option<&DecodeOptions>,
) -> Result<T, Error> {
let json_value = decode(s, options)?;
serde_json::from_value(json_value).map_err(|e| Error::Deserialization(e.to_string()))
}
pub fn from_reader<T: DeserializeOwned, R: Read>(reader: &mut R) -> Result<T, Error> {
let mut s = String::new();
reader
.read_to_string(&mut s)
.map_err(|e| Error::Io(e.to_string()))?;
from_str(&s)
}
pub fn from_reader_with_options<T: DeserializeOwned, R: Read>(
reader: &mut R,
options: &DecodeOptions,
) -> Result<T, Error> {
let mut s = String::new();
reader
.read_to_string(&mut s)
.map_err(|e| Error::Io(e.to_string()))?;
from_str_with_options(&s, Some(options))
}