serde-name

serde-name on crates.io Documentation (latest release) Documentation (master) 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:

```rust

[derive(Deserialize)]

struct Foo { bar: Bar, }

[derive(Deserialize)]

[serde(rename = "ABC")]

enum Bar { A, B, C }

asserteq!(tracename::(), Some("Foo")); asserteq!(tracename::(), Some("ABC")); asserteq!(tracename::>(), 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.

```rust

[derive(Serialize, Deserialize)]

[serde(remote = "Foo")] // Generates Foo::(de)serialize instead of implementing Serde traits.

struct Foo { data: T, }

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

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

// Testing the Deserialize implementation assert!(tracename::>().unwrap().endswith("Foo"));

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

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.