I need a function that returns a type's name, I have this function which works using serde, but now I need an alternative version that doesn't require the type to be Deserialize
so that I can use it on structs that have borrowing members.
How can I rewrite this function so that it works when the type is Serialize
, but not Deserialize
?
#[macro_use]
extern crate serde;
#[macro_use]
extern crate serde_derive;
use serde::de::{self, Deserialize, Deserializer, Visitor};
use std::fmt::{self, Display};
fn type_name<'de, D: Deserialize<'de>>() -> &'static str {
#[derive(Debug)]
struct NoError;
impl std::error::Error for NoError {
fn description(&self) -> &str {
"no error"
}
}
impl Display for NoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "NoError")
}
}
impl de::Error for NoError {
fn custom<T: Display>(_msg: T) -> Self {
NoError
}
}
struct NameDeserializer(Option<&'static str>);
impl<'a, 'de> Deserializer<'de> for &'a mut NameDeserializer {
type Error = NoError;
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
Err(NoError)
}
fn deserialize_unit_struct<V>(self, name: &'static str, _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
self.0 = Some(name);
Err(NoError)
}
fn deserialize_newtype_struct<V>(self, name: &'static str, _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
self.0 = Some(name);
Err(NoError)
}
fn deserialize_tuple_struct<V>(self, name: &'static str, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
self.0 = Some(name);
Err(NoError)
}
fn deserialize_struct<V>(self, name: &'static str, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
self.0 = Some(name);
Err(NoError)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
byte_buf option unit seq tuple map enum identifier ignored_any
}
}
let mut deserializer = NameDeserializer(None);
let _ = D::deserialize(&mut deserializer);
deserializer.0.unwrap()
}
#[derive(Serialize, Deserialize)]
struct Vec2(f32, f32);
fn main() {
println!("{}", type_name::<Vec2>());
}