use core::marker;
#[cfg(feature = "alloc")]
use rust_alloc::string::String;
#[cfg(feature = "alloc")]
use rust_alloc::vec::Vec;
#[cfg(feature = "alloc")]
use crate::alloc::Global;
use crate::mode::Text;
use crate::{Context, Decode, Encode, IntoWriter};
use super::de::JsonDecoder;
use super::en::JsonEncoder;
#[cfg(feature = "alloc")]
use super::error::Error;
use super::parser::IntoParser;
#[allow(unused)]
const DEFAULT: Encoding = Encoding::new();
crate::macros::bare_encoding!(Text, DEFAULT, json, IntoParser, IntoWriter);
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[inline]
pub fn to_string<T>(value: &T) -> Result<String, Error>
where
T: ?Sized + Encode<Text>,
{
DEFAULT.to_string(value)
}
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[inline]
pub fn from_str<'de, T>(string: &'de str) -> Result<T, Error>
where
T: Decode<'de, Text, Global>,
{
DEFAULT.from_str(string)
}
pub struct Encoding<M = Text>
where
M: 'static,
{
_marker: marker::PhantomData<M>,
}
impl Default for Encoding<Text> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl Encoding<Text> {
#[inline]
pub const fn new() -> Self {
Encoding {
_marker: marker::PhantomData,
}
}
}
impl<M> Encoding<M>
where
M: 'static,
{
pub const fn with_mode<T>(self) -> Encoding<T>
where
T: 'static,
{
Encoding {
_marker: marker::PhantomData,
}
}
crate::macros::encoding_impls!(
M,
json,
JsonEncoder::<_, _, M>::new,
JsonDecoder::<_, _, M>::new,
IntoParser::into_parser,
IntoWriter::into_writer,
);
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[inline]
pub fn to_string<T>(self, value: &T) -> Result<String, Error>
where
T: ?Sized + Encode<M>,
{
let cx = crate::context::new().with_error();
self.to_string_with(&cx, value)
}
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[inline]
pub fn to_string_with<T, C>(self, cx: C, value: &T) -> Result<String, C::Error>
where
C: Context,
T: ?Sized + Encode<M>,
{
cx.clear();
let mut data = Vec::with_capacity(128);
T::encode(value, JsonEncoder::<_, _, M>::new(cx, &mut data))?;
Ok(unsafe { String::from_utf8_unchecked(data) })
}
}
impl<M> Clone for Encoding<M> {
#[inline]
fn clone(&self) -> Self {
*self
}
}
impl<M> Copy for Encoding<M> {}