6 releases

0.2.1 May 19, 2022
0.2.0 Sep 15, 2021
0.1.2 May 26, 2021
0.1.1 Sep 1, 2020
0.0.0 May 12, 2020

#1114 in Encoding

Download history 14509/week @ 2024-07-23 12356/week @ 2024-07-30 11500/week @ 2024-08-06 15058/week @ 2024-08-13 14584/week @ 2024-08-20 13043/week @ 2024-08-27 15323/week @ 2024-09-03 17039/week @ 2024-09-10 14108/week @ 2024-09-17 16505/week @ 2024-09-24 18898/week @ 2024-10-01 18602/week @ 2024-10-08 18888/week @ 2024-10-15 18066/week @ 2024-10-22 16217/week @ 2024-10-29 10344/week @ 2024-11-05

65,546 downloads per month
Used in 129 crates (6 directly)

MIT/Apache

20KB
388 lines

serde-name

serde-name on crates.io Documentation (latest release) License License

This crate provides fast and reliable ways to extract and to override the Serde name of a Rust container.

Extracting Serde names

Name extraction relies on the Deserialize trait of Serde:

#[derive(Deserialize)]
struct Foo {
  bar: Bar,
}

#[derive(Deserialize)]
#[serde(rename = "ABC")]
enum Bar { A, B, C }

assert_eq!(trace_name::<Foo>(), Some("Foo"));
assert_eq!(trace_name::<Bar>(), Some("ABC"));
assert_eq!(trace_name::<Option<Bar>>(), None);

Overriding Serde names

SerializeNameAdapter and DeserializeNameAdapter may be used to override the name of a container in the cases where #[serde(rename = "..")] is not flexible enough.

#[derive(Serialize, Deserialize)]
#[serde(remote = "Foo")] // Generates Foo::(de)serialize instead of implementing Serde traits.
struct Foo<T> {
    data: T,
}

impl<'de, T> Deserialize<'de> for Foo<T>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        Foo::deserialize(DeserializeNameAdapter::new(
            deserializer,
            std::any::type_name::<Self>(),
        ))
    }
}

impl<T> Serialize for Foo<T>
where
    T: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        Foo::serialize(
            self,
            SerializeNameAdapter::new(serializer, std::any::type_name::<Self>()),
        )
    }
}

// Testing the Deserialize implementation
assert!(trace_name::<Foo<u64>>().unwrap().ends_with("Foo<u64>"));

// Testing the Serialize implementation
use serde_reflection::*;
let mut tracer = Tracer::new(TracerConfig::default());
let mut samples = Samples::new();
let (mut ident, _) = tracer.trace_value(&mut samples, &Foo { data: 1u64 }).unwrap();
ident.normalize().unwrap();
assert!(matches!(ident, Format::TypeName(s) if s.ends_with("Foo<u64>")));

Contributing

See the CONTRIBUTING file for how to help out.

License

This project is available under the terms of either the Apache 2.0 license or the MIT license.

Dependencies

~0.3–1MB
~22K SLoC