Skip to content

Instantly share code, notes, and snippets.

@lambda-fairy
Last active March 11, 2017 07:21
Show Gist options
  • Save lambda-fairy/0ea468324d9040ecb63b4234ebcb8aaf to your computer and use it in GitHub Desktop.
Save lambda-fairy/0ea468324d9040ecb63b4234ebcb8aaf to your computer and use it in GitHub Desktop.
Versioned serialization a la safecopy
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate safecopy;
#[safecopy(CrusadersV0 = "0", CrusadersV1 = "1", Crusaders = "2")]
pub struct Crusaders {
apple_bloom: String,
sweetie_belle: String,
scootaloo: String,
babs_seed: Option<String>,
gabby: Option<String>,
}
impl From<CrusadersV1> for Crusaders {
fn from(CrusadersV1 { apple_bloom, sweetie_belle, scootaloo, babs_seed }: CrusadersV1) -> Crusaders {
Crusaders {
apple_bloom, sweetie_belle, scootaloo, babs_seed,
gabby: None,
}
}
}
#[derive(Deserialize)]
pub struct CrusadersV1 {
apple_bloom: String,
sweetie_belle: String,
scootaloo: String,
babs_seed: Option<String>,
}
impl From<CrusadersV0> for CrusadersV1 {
fn from(CrusadersV0 { apple_bloom, sweetie_belle, scootaloo }: CrusadersV0) -> CrusadersV1 {
CrusadersV1 {
apple_bloom, sweetie_belle, scootaloo,
babs_seed: None,
}
}
}
#[derive(Deserialize)]
pub struct CrusadersV0 {
apple_bloom: String,
sweetie_belle: String,
scootaloo: String,
}
//////////////////////////////////////////////////////////////////////////////////////////////
#[allow(non_camel_case_types, non_upper_case_globals)]
const __SAFECOPY__Crusaders: () = {
#[derive(Deserialize)]
enum __Crusaders__Deserialize {
#[serde(rename = "0")]
CrusadersV0(CrusadersV0),
#[serde(rename = "1")]
CrusadersV1(CrusadersV1),
#[serde(rename = "2")]
Crusaders(__Crusaders),
}
#[derive(Serialize)]
enum __Crusaders__Serialize<'__serialize> {
#[serde(rename = "0")]
CrusadersV0(()),
#[serde(rename = "1")]
CrusadersV1(()),
#[serde(rename = "2")]
Crusaders(&'__serialize __Crusaders),
}
#[derive(Serialize, Deserialize)]
struct __Crusaders {
apple_bloom: String,
sweetie_belle: String,
scootaloo: String,
babs_seed: Option<String>,
gabby: Option<String>,
}
impl ::serde::Deserialize for Crusaders {
fn deserialize<D: ::serde::Deserializer>(deserializer: D) -> Result<Self, D::Error> {
::serde::Deserialize::deserialize(deserializer).map(|value| match value {
__Crusaders__Deserialize::CrusadersV0(x) => Crusaders::from(CrusadersV1::from(x)),
__Crusaders__Deserialize::CrusadersV1(x) => Crusaders::from(x),
__Crusaders__Deserialize::Crusaders(x) => unsafe { ::std::mem::transmute(x) },
})
}
}
impl ::serde::Serialize for Crusaders {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
::serde::Serialize::serialize(
&__Crusaders__Serialize::Crusaders(unsafe { ::std::mem::transmute(self) }),
serializer)
}
}
()
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment