From 02f9030511aefe1431b39724a9caa4858316b73d Mon Sep 17 00:00:00 2001 From: PTFOPlayer Date: Wed, 5 Jun 2024 11:04:08 +0200 Subject: [PATCH] add serde feature --- Cargo.toml | 4 ++++ examples/README.md | 5 +++++ examples/serde.rs | 17 +++++++++++++++++ src/utils/noise_map.rs | 4 ++++ 4 files changed, 30 insertions(+) create mode 100644 examples/serde.rs diff --git a/Cargo.toml b/Cargo.toml index 6da6d5e7..22f5fa43 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,16 +20,20 @@ rand = { version = "0.8", default-features = false } rand_xorshift = "0.3" image = { version = "0.25.0", optional = true } num-traits = "0.2" +serde = { version = "1.0.203", features = ["derive"], optional = true } + [features] default = [] images = ["image", "std"] std = [] +serde = ["dep:serde"] [dev-dependencies] criterion = { version = "0.5.1", features = ["html_reports"] } rand = { version = "0.8", default-features = true } rand_pcg = "0.3" +serde_json = "1.0.117" [[bench]] name = "open_simplex" diff --git a/examples/README.md b/examples/README.md index bb8b9eff..0a51d668 100644 --- a/examples/README.md +++ b/examples/README.md @@ -382,6 +382,11 @@ cargo run --example "select" --features="images" *select2.png* +## [serde](/examples/serde.rs) + +``` +cargo run --example "serde" --features="serde" +``` ## [simplex](/examples/simplex.rs) diff --git a/examples/serde.rs b/examples/serde.rs new file mode 100644 index 00000000..fdb2bedb --- /dev/null +++ b/examples/serde.rs @@ -0,0 +1,17 @@ +use std::{fs::File, io::Write}; + +use noise::{utils::*, Perlin}; +use serde::{self, Serialize}; +mod utils; + +fn main() { + let perlin = Perlin::default(); + + let map = &PlaneMapBuilder::new(perlin).build(); + + let serialized = serde_json::ser::to_string(map).expect("error serializing"); + + let mut file = File::create("examples/file.json").expect("error opening file"); + + let _ = file.write(serialized.as_bytes()); +} diff --git a/src/utils/noise_map.rs b/src/utils/noise_map.rs index 44430b45..ba27e47e 100644 --- a/src/utils/noise_map.rs +++ b/src/utils/noise_map.rs @@ -2,13 +2,17 @@ use alloc::{ slice::{Iter, IterMut}, vec::{IntoIter, Vec}, }; + use core::ops::{Index, IndexMut}; #[cfg(feature = "images")] use std::path::Path; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; const RASTER_MAX_WIDTH: u16 = 32_767; const RASTER_MAX_HEIGHT: u16 = 32_767; +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct NoiseMap { size: (usize, usize), border_value: f64,