~icefox/oorandom#2
Serde support?

Could be optional, and basically all it needs is the following code from #1:

#[derive(Serialize, Deserialize)]
pub struct Game {
     // a bunch of other fields

    #[serde(with = "Rand32Serde")]
    rng: Rand32,
}

fn rand32_get_state(r: &Rand32) -> u64 {
    r.state().0
}

fn rand32_get_inc(r: &Rand32) -> u64 {
    r.state().1
}

#[derive(Serialize, Deserialize)]
#[serde(remote = "Rand32")]
struct Rand32Serde {
    #[serde(getter = "rand32_get_state")]
    state: u64,
    #[serde(getter = "rand32_get_inc")]
    inc: u64,
}

impl From<Rand32Serde> for Rand32 {
    fn from(r: Rand32Serde) -> Rand32 {
        Rand32::from_state((r.state, r.inc))
    }
}
Status
REPORTED
Submitter
~icefox
Assigned to
No-one
Submitted
4 months ago
Updated
4 months ago
Labels
Feature

~tomassedovic 4 months ago

Doing it in oorandom is simpler than that even. You would put this in Cargo.toml:

[dependencies]
serde = { version = "1.0", optional = true, features = ["derive"] }

[features]
serialization = ["serde"]

And then in lib.rs:

#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
struct Rand32 {
    ...
}

And then anyone using the lib can would add this to their Cargo.toml

oorandom = { version = "11.2", features = ["serialization"] }

And this in their code:

#[derive(Serialize, Deserialize)]
struct MyStruct {
    rng: oorandom::Rand32
}

The code from #1 is only necessary because Rand32 does not implement the Serde traits (so you have to tell Serde in the usage code how to do the serialisation/deserialisation explicitly).

Register here or Log in to comment, or comment via email.