oxidecomputer / typify

compiler from JSON Schema into idiomatic Rust types
Apache License 2.0
401 stars 57 forks source link

default values for floats/doubles are not rendered #442

Open demosdemon opened 10 months ago

demosdemon commented 10 months ago

Example

Schema

{
  "definitions": {
    "Data": {
      "type": "object",
      "properties": {
        "frequency": {
          "type": "number",
          "default": 0.1
        },
        "amount": {
          "type": "integer",
          "default": 42
        },
        "reason": {
          "type": "string",
          "default": "I'm a teapot"
        }
      }
    }
  }
}

Invocation

$ cargo typify --no-builder example.json

Output

#![allow(clippy::redundant_closure_call)]
#![allow(clippy::needless_lifetimes)]
#![allow(clippy::match_single_binding)]
#![allow(clippy::clone_on_copy)]

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Data {
    #[serde(default = "defaults::default_u64::<i64, 42>")]
    pub amount: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frequency: Option<f64>,
    #[serde(default = "defaults::data_reason")]
    pub reason: String,
}
impl From<&Data> for Data {
    fn from(value: &Data) -> Self {
        value.clone()
    }
}
pub mod defaults {
    pub(super) fn default_u64<T, const V: u64>() -> T
    where
        T: std::convert::TryFrom<u64>,
        <T as std::convert::TryFrom<u64>>::Error: std::fmt::Debug,
    {
        T::try_from(V).unwrap()
    }
    pub(super) fn data_reason() -> String {
        "I'm a teapot".to_string()
    }
}

Expected

frequency is expected to not be optional and use a default function like reason.

Meta

$ cargo typify --version
cargo-typify 0.0.14

Real version is: c9d6453fc3cf69726d539925b838b267f886cb53 (main)

ahl commented 9 months ago

Thanks for this. Our handling of floats is pretty lousy right now since they don't come up much for our own uses. In the spirit of transparency, it's probably going to be a low priority for us to fix this.