use std::{
clone::Clone,
fmt::{self, Debug, Formatter},
marker::PhantomData,
};
use serde::{
de::{Deserialize, Deserializer, IgnoredAny, MapAccess, Visitor},
ser::{Serialize, Serializer},
};
use serde_json::value::RawValue;
use crate::cow::MyCowStr;
pub struct Raw<T> {
json: Box<RawValue>,
_ev: PhantomData<T>,
}
impl<T> Raw<T> {
fn new(json: Box<RawValue>) -> Self {
Self { json, _ev: PhantomData }
}
pub fn from_json(raw: Box<RawValue>) -> Self {
Self::new(raw)
}
pub fn json(&self) -> &RawValue {
&self.json
}
pub fn into_json(self) -> Box<RawValue> {
self.json
}
pub fn get_field<'a, U>(&'a self, field_name: &str) -> serde_json::Result<Option<U>>
where
U: Deserialize<'a>,
{
struct SingleFieldVisitor<'b, T> {
field_name: &'b str,
_phantom: PhantomData<T>,
}
impl<'b, T> SingleFieldVisitor<'b, T> {
fn new(field_name: &'b str) -> Self {
Self { field_name, _phantom: PhantomData }
}
}
impl<'b, 'de, T> Visitor<'de> for SingleFieldVisitor<'b, T>
where
T: Deserialize<'de>,
{
type Value = Option<T>;
fn expecting(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a string")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut res = None;
while let Some(key) = map.next_key::<MyCowStr<'_>>()? {
if key.get() == self.field_name {
res = Some(map.next_value()?);
} else {
map.next_value::<IgnoredAny>()?;
}
}
Ok(res)
}
}
let mut deserializer = serde_json::Deserializer::from_str(self.json().get());
deserializer.deserialize_map(SingleFieldVisitor::new(field_name))
}
pub fn deserialize<'a>(&'a self) -> serde_json::Result<T>
where
T: Deserialize<'a>,
{
serde_json::from_str(self.json.get())
}
pub fn deserialize_as<'a, U>(&'a self) -> serde_json::Result<U>
where
U: Deserialize<'a>,
{
serde_json::from_str(self.json.get())
}
}
impl<T: Serialize> From<&T> for Raw<T> {
fn from(val: &T) -> Self {
Self::new(serde_json::value::to_raw_value(val).unwrap())
}
}
impl<T: Serialize> From<T> for Raw<T> {
fn from(val: T) -> Self {
Self::from(&val)
}
}
impl<T> Clone for Raw<T> {
fn clone(&self) -> Self {
Self::new(self.json.clone())
}
}
impl<T> Debug for Raw<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
use std::any::type_name;
f.debug_struct(&format!("Raw::<{}>", type_name::<T>())).field("json", &self.json).finish()
}
}
impl<'de, T> Deserialize<'de> for Raw<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Box::<RawValue>::deserialize(deserializer).map(Self::new)
}
}
impl<T> Serialize for Raw<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.json.serialize(serializer)
}
}