Last active
June 1, 2021 18:12
-
-
Save irevoire/d67ca8bf280d8e6e5f9ae09ec39ae4df to your computer and use it in GitHub Desktop.
A fsm you can serialize with serde only on some state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::marker::PhantomData; | |
use serde::{Deserialize, Serialize}; | |
#[derive(Debug, Deserialize)] | |
struct A; | |
#[derive(Debug, Serialize)] | |
struct B; | |
#[derive(Debug, Clone, Default, Serialize, Deserialize)] | |
#[serde(deny_unknown_fields, rename_all = "camelCase", bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'static>"))] | |
pub struct Fsm<T> { | |
pub field: String, | |
#[serde(skip)] | |
pub _kind: PhantomData<T>, | |
} | |
impl Fsm<A> { | |
pub fn into_b(self) -> Fsm<B> { | |
Fsm { | |
field: self.field, | |
_kind: PhantomData::default(), | |
} | |
} | |
} | |
fn main() { | |
let data = r#"{ "field": "hello" }"#; | |
let fsm: Fsm<A> = serde_json::from_str(data).unwrap(); | |
// does not compile | |
// let fsm: Fsm<B> = serde_json::from_str(data).unwrap(); | |
// does not compile | |
// let res = serde_json::to_string_pretty(&fsm); | |
let res = serde_json::to_string_pretty(&fsm.into_b()).unwrap(); | |
println!("{}", &res); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment