Closed dtolnay closed 7 years ago
Thanks for the heads-up! I think we're good feature-wise, but there is something I'm not sure how to do properly:
This is a library, so I want to provide Serde to people that want it, but not force it on anyone. So the trait implementations are behind a feature flag.
I have to end up implementing the Serialize and Deserialize traits manually decause I can't put just the derive section behind cfg(serde)
. Is there a way to still use the codegen features but in a module separate from the struct definition?
Hm, I've just realised I could duplicate the new struct inside the optional module, derive the serde traits on it and then just convert it to the original struct I actually want. This seems to work fine, so unless there's a more elegant way to do it, I'm happy with this.
#![cfg(feature = "serde")]
use super::Color as UpstreamColor;
use serde::ser::{Serialize, Serializer};
use serde::de::{Deserialize, Deserializer};
#[derive(Serialize, Deserialize)]
struct Color {
r: u8,
g: u8,
b: u8,
}
impl Serialize for UpstreamColor {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
let color = Color {r: self.r, g: self.g, b: self.b};
color.serialize(serializer)
}
}
impl Deserialize for UpstreamColor {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer
{
let color = Color::deserialize(deserializer)?;
Ok(UpstreamColor {r: color.r, g: color.g, b: color.b})
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
struct Color { /* ... */ }
Wow, I completely forgot about cfg_attr
. Thanks!
According to Rust release milestone predictions, rustc-serialize is scheduled to be deprecated in next month's beta release of Rust.
This would be a good time to let us know if there is any functionality you require from Serde before that happens.