#serde #derive #derive-deserialize #serialization

macro serde_piecewise_default_derive

Uses serde's Option<T> handling to let you easily specify defaults for all fields at once by implementing Default

2 unstable releases

0.2.0 Jun 12, 2019
0.1.0 Jun 12, 2019

#63 in #derive-deserialize

Download history 186/week @ 2024-04-03 486/week @ 2024-04-10 273/week @ 2024-04-17 168/week @ 2024-04-24 67/week @ 2024-05-01 59/week @ 2024-05-08 36/week @ 2024-05-15 53/week @ 2024-05-22 95/week @ 2024-05-29 59/week @ 2024-06-05 109/week @ 2024-06-12 82/week @ 2024-06-19 39/week @ 2024-06-26 86/week @ 2024-07-03 93/week @ 2024-07-10 70/week @ 2024-07-17

335 downloads per month
Used in serde_piecewise_default

MIT license

9KB
109 lines

serde-piecewise-default

Travis Build Status Crates.io docs.rs

Uses serde's Option<T> handling to let you easily specify defaults for all fields at once by implementing Default.

Examples

use serde::Deserialize;
use serde_piecewise_default::DeserializePiecewiseDefault;

#[derive(DeserializePiecewiseDefault, PartialEq, Eq, Debug)]
struct Example {
    value: u8,
    enabled: bool,
}

impl Default for Example {
    fn default() -> Self {
        Example {
            value: 20,
            enabled: true,
        }
    }
}

let data: Example = serde_json::from_str(r#"{"value": 8}"#).unwrap();
assert_eq!(data, Example { value: 8, enabled: true });
let data: Example = serde_json::from_str(r#"{"enabled": false}"#).unwrap();
assert_eq!(data, Example { value: 20, enabled: false });
let data: Example = serde_json::from_str("{}").unwrap();
assert_eq!(data, Example { value: 20, enabled: true });

Implementation Details

#[derive(DeserializePiecewiseDefault)]
struct Example {
    item1: i8,
    item2: String,
}

will expand to

struct Example {
    item1: i8,
    item2: String,
}

#[derive(Deserialize)]
struct OptionExample {
    item1: Option<i8>,
    item2: Option<String>,
}

impl<'de> Deserialize<'de> for Example {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
        <OptionExample as Deserialize>::deserialize(deserializer)
            .map(|raw_result| {
                let OptionExample { item1, item2 } = raw_result;
                let default = <Example as Default>::default();
                let item1 = item1.unwrap_or(default.item1);
                let item2 = item2.unwrap_or(default.item2);
                Example { item1, item2 }
            })
    }
}

lib.rs:

See the parent crate documentation for more information.

Dependencies

~0.5–1MB
~25K SLoC