#serde #derive #serialization #derive-deserialize

serde_piecewise_default

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

#1667 in Encoding

Download history 55/week @ 2024-07-26 83/week @ 2024-08-02 49/week @ 2024-08-09 38/week @ 2024-08-16 71/week @ 2024-08-23 84/week @ 2024-08-30 55/week @ 2024-09-06 90/week @ 2024-09-13 206/week @ 2024-09-20 129/week @ 2024-09-27 174/week @ 2024-10-04 88/week @ 2024-10-11 56/week @ 2024-10-18 105/week @ 2024-10-25 101/week @ 2024-11-01 78/week @ 2024-11-08

359 downloads per month

MIT license

7KB

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 }
            })
    }
}

Dependencies

~2MB
~53K SLoC