From d924d474f8d6114665d647bf4f691a23fc6b3f71 Mon Sep 17 00:00:00 2001 From: Travis Veazey Date: Fri, 7 May 2021 09:54:31 -0800 Subject: [PATCH] Add optional support for Serde --- Cargo.toml | 6 ++++++ src/lib.rs | 4 ++++ tests/serde.rs | 16 ++++++++++++++++ 3 files changed, 26 insertions(+) create mode 100644 tests/serde.rs diff --git a/Cargo.toml b/Cargo.toml index 3d3a280..0797eba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,8 +16,14 @@ exclude = ["/.github/*"] rand = "0.8.3" rand_xoshiro = "0.6.0" rand_distr = "0.4.0" +serde = { version = "1.0", package = "serde", features = ["derive"], optional = true } +serde_arrays = { version = "0.1.0", optional = true } [features] default = [] # Provide an "empty" default feature for CI single_precision = [] small_rng = [] +derive_serde = ["serde", "serde_arrays"] + +[dev-dependencies] +serde_json = "1.0" \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 0a1c75d..edf2daa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -150,6 +150,8 @@ //! [const generics]: https://blog.rust-lang.org/2021/03/25/Rust-1.51.0.html#const-generics-mvp //! [small_rng]: https://docs.rs/rand/0.8.3/rand/rngs/struct.SmallRng.html +#[cfg(feature = "derive_serde")] +use serde::{Deserialize, Serialize}; #[cfg(test)] mod tests; @@ -181,8 +183,10 @@ type Float = f32; /// whether or not they were built with the same parameters, but rather on whether or not they will /// produce the same results once the distribution is generated. #[derive(Debug, Clone)] +#[cfg_attr(feature = "derive_serde", derive(Serialize, Deserialize))] pub struct Poisson { /// Dimensions of the box + #[cfg_attr(feature = "derive_serde", serde(with = "serde_arrays"))] dimensions: [Float; N], /// Radius around each point that must remain empty radius: Float, diff --git a/tests/serde.rs b/tests/serde.rs new file mode 100644 index 0000000..4b3cb7c --- /dev/null +++ b/tests/serde.rs @@ -0,0 +1,16 @@ +#![cfg(feature = "derive_serde")] + +use fast_poisson::Poisson2D; +use serde_json; + +#[test] +fn serialize_and_deserialize() { + // Be sure to set a seed so we can assert equality + let mut poisson = Poisson2D::new(); + poisson.with_seed(1337); + + let json = serde_json::to_string(&poisson).unwrap(); + let decoded = serde_json::from_str(&json).unwrap(); + + assert_eq!(poisson, decoded); +}