From 68e94e98b1928378f38549d786e7797d4c67e13f Mon Sep 17 00:00:00 2001 From: Tim Anderson Date: Fri, 27 Aug 2021 13:46:34 +1000 Subject: [PATCH] Add support for rust_decimal and bigdecimal --- schemars/Cargo.toml | 2 ++ schemars/src/json_schema_impls/decimal.rs | 31 +++++++++++++++++++++++ schemars/src/json_schema_impls/mod.rs | 2 ++ 3 files changed, 35 insertions(+) create mode 100644 schemars/src/json_schema_impls/decimal.rs diff --git a/schemars/Cargo.toml b/schemars/Cargo.toml index 6fe31219..d5c13851 100644 --- a/schemars/Cargo.toml +++ b/schemars/Cargo.toml @@ -26,6 +26,8 @@ smallvec = { version = "1.0", optional = true } arrayvec = { version = "0.5", default-features = false, optional = true } url = { version = "2.0", default-features = false, optional = true } bytes = { version = "1.0", optional = true } +rust_decimal = { version = "1", default-features = false, optional = true } +bigdecimal = { version = "0.3", default-features = false, optional = true } [dev-dependencies] pretty_assertions = "0.6.1" diff --git a/schemars/src/json_schema_impls/decimal.rs b/schemars/src/json_schema_impls/decimal.rs new file mode 100644 index 00000000..6058a7fd --- /dev/null +++ b/schemars/src/json_schema_impls/decimal.rs @@ -0,0 +1,31 @@ +use crate::gen::SchemaGenerator; +use crate::schema::*; +use crate::JsonSchema; + +macro_rules! decimal_impl { + ($type:ty) => { + decimal_impl!($type => Number, "Number"); + }; + ($type:ty => $instance_type:ident, $name:expr) => { + impl JsonSchema for $type { + no_ref_schema!(); + + fn schema_name() -> String { + $name.to_owned() + } + + fn json_schema(_: &mut SchemaGenerator) -> Schema { + SchemaObject { + instance_type: Some(InstanceType::$instance_type.into()), + ..Default::default() + } + .into() + } + } + }; +} + +#[cfg(feature="rust_decimal")] +decimal_impl!(rust_decimal::Decimal); +#[cfg(feature="bigdecimal")] +decimal_impl!(bigdecimal::BigDecimal); diff --git a/schemars/src/json_schema_impls/mod.rs b/schemars/src/json_schema_impls/mod.rs index ff2e1e71..81b698f8 100644 --- a/schemars/src/json_schema_impls/mod.rs +++ b/schemars/src/json_schema_impls/mod.rs @@ -45,6 +45,8 @@ mod bytes; #[cfg(feature = "chrono")] mod chrono; mod core; +#[cfg(any(feature = "rust_decimal", feature="bigdecimal"))] +mod decimal; #[cfg(feature = "either")] mod either; mod ffi;