From e7c73b37523507d6610ab4142aaf78c1a5796b56 Mon Sep 17 00:00:00 2001 From: Thomas Ziemek Date: Tue, 24 Nov 2026 10:46:45 +0100 Subject: [PATCH] feat: add optional jiff as chrono replacement --- .github/workflows/rust.yml | 29 + CHANGELOG.adoc | 5 + Cargo.lock | 18 + Cargo.toml | 7 +- README.md | 17 + cargo-typify/Cargo.toml | 7 +- typify-impl/Cargo.toml | 8 + typify-impl/src/convert.rs | 142 +++-- typify-impl/src/lib.rs | 4 +- typify-impl/tests/test_date_fallback.rs | 31 ++ typify-impl/tests/test_date_json_schema.rs | 47 ++ typify-impl/tests/test_dependencies.rs | 9 +- typify-impl/tests/test_github.rs | 3 + typify-macro/Cargo.toml | 5 + typify/Cargo.toml | 7 +- typify/tests/jiff_runtime.rs | 37 ++ typify/tests/schemas.rs | 45 +- typify/tests/schemas/jiff/maps.rs | 176 ++++++ .../tests/schemas/jiff/types-with-defaults.rs | 515 ++++++++++++++++++ typify/tests/schemas/types-with-defaults.json | 4 +- typify/tests/schemas/types-with-defaults.rs | 67 +-- 21 files changed, 1080 insertions(+), 103 deletions(-) create mode 100644 typify-impl/tests/test_date_fallback.rs create mode 100644 typify-impl/tests/test_date_json_schema.rs create mode 100644 typify/tests/jiff_runtime.rs create mode 100644 typify/tests/schemas/jiff/maps.rs create mode 100644 typify/tests/schemas/jiff/types-with-defaults.rs diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index b5e914ab..3a844e50 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -64,6 +64,35 @@ jobs: - name: Run tests run: cargo test --locked --workspace --no-fail-fast --verbose + # Each date backend is tested on its own. The packages are run one at a time + # so that a feature enabled by one package cannot leak into another through + # feature unification. + date-backends: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - backend: jiff + impl_flags: --no-default-features --features jiff + typify_flags: --no-default-features --features macro,jiff + cli_flags: --no-default-features --features jiff + - backend: none + impl_flags: --no-default-features + typify_flags: --no-default-features --features macro + cli_flags: --no-default-features + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: date-${{ matrix.backend }} + - name: Run typify-impl + run: cargo test --locked -p typify-impl ${{ matrix.impl_flags }} --no-fail-fast + - name: Run typify + run: cargo test --locked -p typify ${{ matrix.typify_flags }} --no-fail-fast + - name: Run cargo-typify + run: cargo test --locked -p cargo-typify ${{ matrix.cli_flags }} --no-fail-fast + msrv: runs-on: ubuntu-latest env: diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index fef739a0..a5947eda 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -19,6 +19,11 @@ https://github.com/oxidecomputer/typify/compare/v0.10.1\...HEAD[Full list of com * Lower the MSRV to 1.88 * A newtype with a schema `default` gets its `Default` impl back, per 0.8 (typespace #74). +* The `date` and `date-time` string formats can map to `jiff` types + (`jiff::civil::Date` and `jiff::Timestamp`) through a new `jiff` feature. + The `chrono` feature, which is on by default, keeps the existing mapping. + When both are enabled, `jiff` takes precedence. Types from `jiff` do not + implement `JsonSchema`. == 0.10.1 (released 2026-11-16) diff --git a/Cargo.lock b/Cargo.lock index 33aa5475..56faa8ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -704,10 +704,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a3546dc96b6d42c5f24902af9e2538e82e39ad350b0c766eb3fbf2d8f3d8359" dependencies = [ "jiff-static", + "jiff-tzdb-platform", "log", "portable-atomic", "portable-atomic-util", "serde_core", + "windows-sys 0.52.0", ] [[package]] @@ -721,6 +723,21 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -1785,6 +1802,7 @@ dependencies = [ "env_logger", "expectorate", "glob", + "jiff", "quote", "regress", "rustfmt-wrapper", diff --git a/Cargo.toml b/Cargo.toml index b9eb4844..8dfee5bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,9 +15,9 @@ resolver = "2" rust-version = "1.88" [workspace.dependencies] -typify = { version = "0.10.1", path = "typify" } -typify-impl = { version = "0.10.1", path = "typify-impl" } -typify-macro = { version = "0.10.1", path = "typify-macro" } +typify = { version = "0.10.1", path = "typify", default-features = false } +typify-impl = { version = "0.10.1", path = "typify-impl", default-features = false } +typify-macro = { version = "0.10.1", path = "typify-macro", default-features = false } assert_cmd = "2.2.2" chrono = { version = "0.4.45", features = ["serde"] } @@ -28,6 +28,7 @@ expectorate = "1.2.0" glob = "0.3.3" heck = "0.5.0" ipnetwork = { version = "0.21.1", features = ["schemars"] } +jiff = { version = "0.2.23", features = ["serde"] } log = "0.4.31" newline-converter = "0.3.0" paste = "1.0.15" diff --git a/README.md b/README.md index bee64f74..09e3f0c2 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,23 @@ appropriate Rust type. For example `{ "type": "string", "format": "uuid" }` is represented as a `uuid::Uuid` (which requires the `uuid` crate be included as a dependency). +The `date` and `date-time` formats are represented by a date library, chosen +with the `chrono` (default) or `jiff` feature: + +| Format | `chrono` | `jiff` | +| ----------- | --------------------------------- | -------------------- | +| `date` | `chrono::naive::NaiveDate` | `jiff::civil::Date` | +| `date-time` | `chrono::DateTime` | `jiff::Timestamp` | + +Enable `jiff` with `default-features = false` to drop chrono. When both features +are enabled, `jiff` takes precedence. With neither, dates are plain `String`s. +The generated code needs the chosen crate as a dependency; enable its `serde` +feature so the date types deserialize. + +Types from `jiff` do not implement `schemars::JsonSchema` (schemars 0.8 has no +`jiff` impl), so a generated type that requires `JsonSchema` cannot contain a +`jiff` date. + ### Arrays JSON Schema arrays can turn into one of three Rust types `Vec`, `HashSet`, diff --git a/cargo-typify/Cargo.toml b/cargo-typify/Cargo.toml index c20050bf..9783de2e 100644 --- a/cargo-typify/Cargo.toml +++ b/cargo-typify/Cargo.toml @@ -12,9 +12,14 @@ rust-version.workspace = true default-run = "cargo-typify" +[features] +default = ["chrono"] +chrono = ["typify/chrono"] +jiff = ["typify/jiff"] + [dependencies] syn = { workspace = true } -typify = { workspace = true } +typify = { workspace = true, features = ["macro"] } clap = { workspace = true } color-eyre = { workspace = true } diff --git a/typify-impl/Cargo.toml b/typify-impl/Cargo.toml index 3679c1d0..a3e0acb9 100644 --- a/typify-impl/Cargo.toml +++ b/typify-impl/Cargo.toml @@ -8,6 +8,14 @@ repository = "https://github.com/oxidecomputer/typify" readme = "../README.md" rust-version.workspace = true +[features] +default = ["chrono"] +# Selects the date library that `date` and `date-time` strings map to. These +# are marker features: typify emits paths and never links either crate. When +# both are enabled, jiff takes precedence. +chrono = [] +jiff = [] + [dependencies] heck = { workspace = true } log = { workspace = true } diff --git a/typify-impl/src/convert.rs b/typify-impl/src/convert.rs index f830e7d9..fc04769c 100644 --- a/typify-impl/src/convert.rs +++ b/typify-impl/src/convert.rs @@ -17,6 +17,68 @@ use crate::util::get_type_name; use crate::{Error, Name, Result, TypeSpace}; +/// The date library that `date` and `date-time` strings map to, chosen by the +/// `chrono` and `jiff` features. jiff takes precedence when both are enabled. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum DateLibrary { + Chrono, + Jiff, +} + +impl DateLibrary { + fn crate_name(self) -> &'static str { + match self { + DateLibrary::Chrono => "chrono", + DateLibrary::Jiff => "jiff", + } + } +} + +fn date_library() -> Option { + if cfg!(feature = "jiff") { + Some(DateLibrary::Jiff) + } else if cfg!(feature = "chrono") { + Some(DateLibrary::Chrono) + } else { + None + } +} + +/// The Rust path a `date` or `date-time` string maps to under `library`. +fn date_path(format: &str, library: DateLibrary) -> &'static str { + match (format, library) { + ("date", DateLibrary::Chrono) => "::chrono::naive::NaiveDate", + ("date", DateLibrary::Jiff) => "::jiff::civil::Date", + (_, DateLibrary::Chrono) => "::chrono::DateTime<::chrono::offset::Utc>", + (_, DateLibrary::Jiff) => "::jiff::Timestamp", + } +} + +/// The traits a date native declares. jiff types have no schemars 0.8 impl, +/// so they omit `JsonSchema`. +fn date_traits(library: DateLibrary) -> TypespaceTraitSet { + let traits = [ + TypespaceTrait::Clone, + TypespaceTrait::Debug, + TypespaceTrait::Serialize, + TypespaceTrait::Deserialize, + TypespaceTrait::Display, + TypespaceTrait::FromStr, + TypespaceTrait::Eq, + TypespaceTrait::PartialEq, + TypespaceTrait::Ord, + TypespaceTrait::PartialOrd, + TypespaceTrait::Hash, + ]; + match library { + DateLibrary::Chrono => traits + .into_iter() + .chain([TypespaceTrait::JsonSchema]) + .collect(), + DateLibrary::Jiff => traits.into_iter().collect(), + } +} + impl TypeSpace { pub(crate) fn convert_schema<'a>( &mut self, @@ -810,69 +872,37 @@ impl TypeSpace { format: &Option, validation: Option<&StringValidation>, ) -> Result<(TypeEntry, &'a Option>)> { - match format.as_ref().map(String::as_str) { - Some("uuid") => { - self.add_dependency(typespace::codespace::Dependency::new("uuid")); - // ::uuid::Uuid Default, but we ignore it because there's no - // useful value. We assume the uuid feature in schemars. + let date = date_library(); + match (format.as_ref().map(String::as_str), date) { + (Some(format @ ("date" | "date-time")), Some(library)) => { + self.add_dependency(typespace::codespace::Dependency::new(library.crate_name())); Ok(( - TypeEntry::new_native( - "::uuid::Uuid", - [ - TypespaceTrait::Clone, - TypespaceTrait::Debug, - TypespaceTrait::Serialize, - TypespaceTrait::Deserialize, - TypespaceTrait::Display, - TypespaceTrait::FromStr, - TypespaceTrait::Eq, - TypespaceTrait::PartialEq, - TypespaceTrait::Ord, - TypespaceTrait::PartialOrd, - TypespaceTrait::Hash, - TypespaceTrait::JsonSchema, - ] - .into_iter() - .collect::(), - ), + TypeEntry::new_native(date_path(format, library), date_traits(library)), metadata, )) } - - Some("date") => { - self.add_dependency(typespace::codespace::Dependency::new("chrono")); - // ::chrono::naive::NaiveDate implements Default, but there's - // no useful value. We assume the chrono feaeture in schemars. - Ok(( - TypeEntry::new_native( - "::chrono::naive::NaiveDate", - [ - TypespaceTrait::Clone, - TypespaceTrait::Debug, - TypespaceTrait::Serialize, - TypespaceTrait::Deserialize, - TypespaceTrait::Display, - TypespaceTrait::FromStr, - TypespaceTrait::Eq, - TypespaceTrait::PartialEq, - TypespaceTrait::Ord, - TypespaceTrait::PartialOrd, - TypespaceTrait::Hash, - TypespaceTrait::JsonSchema, - ] - .into_iter() - .collect::(), - ), - metadata, - )) + (format, _) => { + self.convert_format(type_name, original_schema, metadata, format, validation) } - Some("date-time") => { - self.add_dependency(typespace::codespace::Dependency::new("chrono")); - // ::chrono::DateTime implements Default, but not usefully. - // We assume the chrono feaeture in schemars. + } + } + + fn convert_format<'a>( + &mut self, + type_name: Name, + original_schema: &'a Schema, + metadata: &'a Option>, + format: Option<&str>, + validation: Option<&StringValidation>, + ) -> Result<(TypeEntry, &'a Option>)> { + match format { + Some("uuid") => { + self.add_dependency(typespace::codespace::Dependency::new("uuid")); + // ::uuid::Uuid Default, but we ignore it because there's no + // useful value. We assume the uuid feature in schemars. Ok(( TypeEntry::new_native( - "::chrono::DateTime<::chrono::offset::Utc>", + "::uuid::Uuid", [ TypespaceTrait::Clone, TypespaceTrait::Debug, diff --git a/typify-impl/src/lib.rs b/typify-impl/src/lib.rs index f8a10585..ab9cb3cb 100644 --- a/typify-impl/src/lib.rs +++ b/typify-impl/src/lib.rs @@ -126,8 +126,8 @@ pub struct TypeSpace { name_to_id: BTreeMap, ref_to_id: BTreeMap, - /// The crates needed for native types: `chrono` and `uuid` for the string - /// formats it maps to them, and each crate an `x-rust-type` extension + /// The crates needed for native types: `uuid` and the date library + /// (`chrono` or `jiff`) for the string formats they map to, and each crate an `x-rust-type` extension /// names, at the version [`TypeSpaceSettings::with_crate`] declared for /// it. Recorded on the `TypespaceBuilder` so the finalized typespace /// reports them with the crates of what typespace renders itself. diff --git a/typify-impl/tests/test_date_fallback.rs b/typify-impl/tests/test_date_fallback.rs new file mode 100644 index 00000000..42e22df3 --- /dev/null +++ b/typify-impl/tests/test_date_fallback.rs @@ -0,0 +1,31 @@ +// Copyright 2026 Oxide Computer Company + +//! With no date library enabled, `date` and `date-time` are plain strings. + +#![cfg(not(any(feature = "chrono", feature = "jiff")))] + +use schemars::schema::RootSchema; +use typify_impl::{TypeSpace, TypeSpaceSettings}; + +#[test] +fn dates_without_a_library_are_strings() { + let schema: RootSchema = serde_json::from_value(serde_json::json!({ + "title": "Event", + "type": "object", + "properties": { + "when": { "type": "string", "format": "date-time" }, + "day": { "type": "string", "format": "date" } + }, + "required": ["when", "day"] + })) + .unwrap(); + let mut type_space = TypeSpace::new(&TypeSpaceSettings::default()); + type_space.add_root_schema(schema).unwrap(); + let rendered = type_space.to_stream().unwrap().to_string(); + assert!( + rendered.contains(":: std :: string :: String"), + "{rendered}" + ); + assert!(!rendered.contains("chrono"), "{rendered}"); + assert!(!rendered.contains("jiff"), "{rendered}"); +} diff --git a/typify-impl/tests/test_date_json_schema.rs b/typify-impl/tests/test_date_json_schema.rs new file mode 100644 index 00000000..db7d7b18 --- /dev/null +++ b/typify-impl/tests/test_date_json_schema.rs @@ -0,0 +1,47 @@ +// Copyright 2026 Oxide Computer Company + +//! A date native omits `JsonSchema` under jiff, so a type that requires it +//! and holds a jiff date is refused when rendered. + +#![cfg(all(feature = "jiff", not(feature = "chrono")))] + +use schemars::schema::RootSchema; +use typespace::TypespaceTrait; +use typify_impl::{Error, TypeSpace, TypeSpaceSettings}; + +fn schema() -> RootSchema { + serde_json::from_value(serde_json::json!({ + "title": "Event", + "type": "object", + "properties": { + "when": { "type": "string", "format": "date-time" } + }, + "required": ["when"] + })) + .unwrap() +} + +/// Requiring `JsonSchema` of a type holding a jiff `Timestamp` is refused, +/// naming the jiff type as the one that lacks the impl. +#[test] +fn json_schema_requirement_refuses_a_jiff_date() { + let mut settings = TypeSpaceSettings::default(); + settings.map_typespace_settings(|s| s.with_required_trait(TypespaceTrait::JsonSchema)); + let mut type_space = TypeSpace::new(&settings); + type_space.add_root_schema(schema()).unwrap(); + + let err = type_space.to_stream().unwrap_err(); + assert!( + matches!(err, Error::Typespace(_)) && err.to_string().contains("jiff::Timestamp"), + "{err}" + ); +} + +/// Without the requirement, the same schema generates a jiff date. +#[test] +fn a_jiff_date_generates_without_json_schema() { + let mut type_space = TypeSpace::new(&TypeSpaceSettings::default()); + type_space.add_root_schema(schema()).unwrap(); + let rendered = type_space.to_stream().unwrap().to_string(); + assert!(rendered.contains(":: jiff :: Timestamp"), "{rendered}"); +} diff --git a/typify-impl/tests/test_dependencies.rs b/typify-impl/tests/test_dependencies.rs index 8b3d465b..9f8a0cdc 100644 --- a/typify-impl/tests/test_dependencies.rs +++ b/typify-impl/tests/test_dependencies.rs @@ -31,7 +31,14 @@ fn formats_report_their_crates() { type_space .add_type_with_name(&schema, Some("Thing".to_string())) .unwrap(); - assert_eq!(names(&type_space), ["chrono", "serde", "uuid"]); + let expected: &[&str] = if cfg!(feature = "jiff") { + &["jiff", "serde", "uuid"] + } else if cfg!(feature = "chrono") { + &["chrono", "serde", "uuid"] + } else { + &["serde", "uuid"] + }; + assert_eq!(names(&type_space), expected); } /// A type from an `x-rust-type` extension reports its crate at the diff --git a/typify-impl/tests/test_github.rs b/typify-impl/tests/test_github.rs index 0c85428a..0d0ec24c 100644 --- a/typify-impl/tests/test_github.rs +++ b/typify-impl/tests/test_github.rs @@ -5,6 +5,9 @@ use std::{fs::File, io::BufReader, path::Path}; use schemars::schema::RootSchema; use typify_impl::{TypeSpace, TypeSpaceImpl, TypeSpaceSettings}; +/// `github.out` names chrono types, so this golden only matches the chrono +/// backend. +#[cfg(all(feature = "chrono", not(feature = "jiff")))] #[test] fn test_github() { let mut type_space = TypeSpace::default(); diff --git a/typify-macro/Cargo.toml b/typify-macro/Cargo.toml index 1461c1f3..adc11310 100644 --- a/typify-macro/Cargo.toml +++ b/typify-macro/Cargo.toml @@ -11,6 +11,11 @@ rust-version.workspace = true [lib] proc-macro = true +[features] +default = ["chrono"] +chrono = ["typify-impl/chrono"] +jiff = ["typify-impl/jiff"] + [dependencies] proc-macro2 = { workspace = true } quote = { workspace = true } diff --git a/typify/Cargo.toml b/typify/Cargo.toml index 0a891d72..62aa8fa5 100644 --- a/typify/Cargo.toml +++ b/typify/Cargo.toml @@ -11,8 +11,12 @@ categories = ["api-bindings", "compilers"] rust-version.workspace = true [features] -default = ["macro"] +default = ["macro", "chrono"] macro = ["typify-macro"] +# Selects the date library that `date` and `date-time` strings map to. jiff +# takes precedence when both are enabled. +chrono = ["typify-impl/chrono", "typify-macro?/chrono"] +jiff = ["typify-impl/jiff", "typify-macro?/jiff"] [dependencies] typify-macro = { workspace = true, optional = true } @@ -21,6 +25,7 @@ typify-impl = { workspace = true } [dev-dependencies] chrono = { workspace = true } env_logger = { workspace = true } +jiff = { workspace = true } expectorate = { workspace = true } glob = { workspace = true } quote = { workspace = true } diff --git a/typify/tests/jiff_runtime.rs b/typify/tests/jiff_runtime.rs new file mode 100644 index 00000000..0eb69066 --- /dev/null +++ b/typify/tests/jiff_runtime.rs @@ -0,0 +1,37 @@ +// Copyright 2026 Oxide Computer Company + +//! Runs the generated jiff code, not just compiles it: date-time fields +//! round-trip through serde, and a default date-time parses. + +#![cfg(all(feature = "jiff", not(feature = "chrono")))] + +#[allow(dead_code, unused_imports)] +#[path = "schemas/jiff/types-with-defaults.rs"] +mod generated; + +use generated::EventWithDefault; + +#[test] +fn default_date_time_parses() { + let event = EventWithDefault::default(); + assert_eq!(event.when.to_string(), "1970-01-01T00:00:00Z"); +} + +#[test] +fn date_time_normalizes_offsets_to_utc() { + let event: EventWithDefault = + serde_json::from_str(r#"{"when": "2024-03-05T12:34:56+02:00"}"#).unwrap(); + assert_eq!(event.when.to_string(), "2024-03-05T10:34:56Z"); +} + +#[test] +fn date_time_round_trips() { + let json = r#"{"when":"2024-03-05T12:34:56Z"}"#; + let event: EventWithDefault = serde_json::from_str(json).unwrap(); + assert_eq!(serde_json::to_string(&event).unwrap(), json); +} + +#[test] +fn invalid_date_time_is_rejected() { + assert!(serde_json::from_str::(r#"{"when": "not-a-date"}"#).is_err()); +} diff --git a/typify/tests/schemas.rs b/typify/tests/schemas.rs index a3a282c3..748b776d 100644 --- a/typify/tests/schemas.rs +++ b/typify/tests/schemas.rs @@ -1,6 +1,6 @@ // Copyright 2025 Oxide Computer Company -use std::{error::Error, fs::File, io::BufReader}; +use std::{error::Error, fs::File, io::BufReader, path::PathBuf}; use expectorate::assert_contents; use glob::glob; @@ -8,26 +8,63 @@ use quote::quote; use schemars::schema::RootSchema; use serde_json::json; use typify::typespace::TypespaceTrait; +#[cfg(all(feature = "chrono", not(feature = "jiff")))] use typify::typespace::settings::ContainerType; use typify::{TypeSpace, TypeSpacePatch, TypeSpaceSettings}; use typify_impl::TypeSpaceImpl; +/// Checked-in outputs that name chrono types. `maps` and `types-with-defaults` +/// are regenerated under jiff; `maps_custom` is chrono-only and is excluded +/// from the jiff compile pass. +const CHRONO_GOLDENS: &[&str] = &["maps", "types-with-defaults", "maps_custom"]; + +/// Whether `stem` has checked-in output that depends on the date library. +fn is_chrono_golden(stem: &str) -> bool { + CHRONO_GOLDENS.contains(&stem) +} + #[test] fn test_schemas() { env_logger::init(); - // Make sure output is up to date. + // Make sure output is up to date. Golden files that name chrono types + // only match the chrono backend; under jiff they are regenerated into + // `tests/schemas/jiff/` instead. + let chrono_active = cfg!(feature = "chrono") && !cfg!(feature = "jiff"); + let jiff_active = cfg!(feature = "jiff"); for entry in glob("tests/schemas/*.json").expect("Failed to read glob pattern") { let entry = entry.unwrap(); + let stem = entry.file_stem().unwrap().to_str().unwrap().to_string(); + if is_chrono_golden(&stem) && !chrono_active { + if jiff_active { + let out_path = PathBuf::from("tests/schemas/jiff").join(format!("{stem}.rs")); + validate_schema(entry.clone(), out_path, TypeSpaceSettings::default()) + .unwrap_or_else(|e| panic!("failed for {}: {e}", entry.to_string_lossy())) + } + continue; + } let out_path = entry.clone().with_extension("rs"); validate_schema(entry.clone(), out_path, TypeSpaceSettings::default()) .unwrap_or_else(|e| panic!("failed for {}: {e}", entry.to_string_lossy())) } - // Make sure it all compiles. - trybuild::TestCases::new().pass("tests/schemas/*.rs"); + // Make sure it all compiles. Under jiff, the chrono-named goldens are + // compiled from `jiff/` instead of the top-level directory. + let cases = trybuild::TestCases::new(); + if jiff_active { + cases.pass("tests/schemas/jiff/*.rs"); + } + for entry in glob("tests/schemas/*.rs").expect("Failed to read glob pattern") { + let entry = entry.unwrap(); + let stem = entry.file_stem().unwrap().to_str().unwrap(); + if chrono_active || !is_chrono_golden(stem) { + cases.pass(&entry); + } + } } /// Ensure that setting the global config to use a custom map type works. +/// Compares against chrono-named golden output, so it runs only under chrono. +#[cfg(all(feature = "chrono", not(feature = "jiff")))] #[test] fn test_custom_map() { let mut settings = TypeSpaceSettings::default(); diff --git a/typify/tests/schemas/jiff/maps.rs b/typify/tests/schemas/jiff/maps.rs new file mode 100644 index 00000000..399b243b --- /dev/null +++ b/typify/tests/schemas/jiff/maps.rs @@ -0,0 +1,176 @@ +#![deny(warnings)] +#[doc = "`DeadSimple`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +#[serde(transparent)] +pub struct DeadSimple(pub ::serde_json::Map<::std::string::String, ::serde_json::Value>); +impl ::std::ops::Deref for DeadSimple { + type Target = ::serde_json::Map<::std::string::String, ::serde_json::Value>; + fn deref(&self) -> &::serde_json::Map<::std::string::String, ::serde_json::Value> { + &self.0 + } +} +impl ::std::convert::From + for ::serde_json::Map<::std::string::String, ::serde_json::Value> +{ + fn from(value: DeadSimple) -> Self { + value.0 + } +} +impl ::std::convert::From<::serde_json::Map<::std::string::String, ::serde_json::Value>> + for DeadSimple +{ + fn from(value: ::serde_json::Map<::std::string::String, ::serde_json::Value>) -> Self { + Self(value) + } +} +#[doc = "`Eh`"] +#[derive( + :: serde :: Deserialize, + :: serde :: Serialize, + Clone, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, +)] +#[serde(transparent)] +pub struct Eh(pub ::std::string::String); +impl ::std::ops::Deref for Eh { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } +} +impl ::std::convert::From for ::std::string::String { + fn from(value: Eh) -> Self { + value.0 + } +} +impl ::std::convert::From<::std::string::String> for Eh { + fn from(value: ::std::string::String) -> Self { + Self(value) + } +} +impl ::std::fmt::Display for Eh { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + self.0.fmt(f) + } +} +impl ::std::str::FromStr for Eh { + type Err = ::std::convert::Infallible; + fn from_str(value: &str) -> ::std::result::Result { + Ok(Self(value.to_string())) + } +} +#[doc = "`MapWithDateKeys`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +#[serde(transparent)] +pub struct MapWithDateKeys(pub ::std::collections::HashMap<::jiff::civil::Date, Value>); +impl ::std::ops::Deref for MapWithDateKeys { + type Target = ::std::collections::HashMap<::jiff::civil::Date, Value>; + fn deref(&self) -> &::std::collections::HashMap<::jiff::civil::Date, Value> { + &self.0 + } +} +impl ::std::convert::From + for ::std::collections::HashMap<::jiff::civil::Date, Value> +{ + fn from(value: MapWithDateKeys) -> Self { + value.0 + } +} +impl ::std::convert::From<::std::collections::HashMap<::jiff::civil::Date, Value>> + for MapWithDateKeys +{ + fn from(value: ::std::collections::HashMap<::jiff::civil::Date, Value>) -> Self { + Self(value) + } +} +#[doc = "`MapWithDateTimeKeys`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +#[serde(transparent)] +pub struct MapWithDateTimeKeys(pub ::std::collections::HashMap<::jiff::Timestamp, Value>); +impl ::std::ops::Deref for MapWithDateTimeKeys { + type Target = ::std::collections::HashMap<::jiff::Timestamp, Value>; + fn deref(&self) -> &::std::collections::HashMap<::jiff::Timestamp, Value> { + &self.0 + } +} +impl ::std::convert::From + for ::std::collections::HashMap<::jiff::Timestamp, Value> +{ + fn from(value: MapWithDateTimeKeys) -> Self { + value.0 + } +} +impl ::std::convert::From<::std::collections::HashMap<::jiff::Timestamp, Value>> + for MapWithDateTimeKeys +{ + fn from(value: ::std::collections::HashMap<::jiff::Timestamp, Value>) -> Self { + Self(value) + } +} +#[doc = "`MapWithKeys`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +#[serde(transparent)] +pub struct MapWithKeys(pub ::std::collections::HashMap); +impl ::std::ops::Deref for MapWithKeys { + type Target = ::std::collections::HashMap; + fn deref(&self) -> &::std::collections::HashMap { + &self.0 + } +} +impl ::std::convert::From for ::std::collections::HashMap { + fn from(value: MapWithKeys) -> Self { + value.0 + } +} +impl ::std::convert::From<::std::collections::HashMap> for MapWithKeys { + fn from(value: ::std::collections::HashMap) -> Self { + Self(value) + } +} +#[doc = "`Value`"] +#[derive( + :: serde :: Deserialize, + :: serde :: Serialize, + Clone, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, +)] +#[serde(transparent)] +pub struct Value(pub ::std::string::String); +impl ::std::ops::Deref for Value { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } +} +impl ::std::convert::From for ::std::string::String { + fn from(value: Value) -> Self { + value.0 + } +} +impl ::std::convert::From<::std::string::String> for Value { + fn from(value: ::std::string::String) -> Self { + Self(value) + } +} +impl ::std::fmt::Display for Value { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + self.0.fmt(f) + } +} +impl ::std::str::FromStr for Value { + type Err = ::std::convert::Infallible; + fn from_str(value: &str) -> ::std::result::Result { + Ok(Self(value.to_string())) + } +} +fn main() {} diff --git a/typify/tests/schemas/jiff/types-with-defaults.rs b/typify/tests/schemas/jiff/types-with-defaults.rs new file mode 100644 index 00000000..f7d650b4 --- /dev/null +++ b/typify/tests/schemas/jiff/types-with-defaults.rs @@ -0,0 +1,515 @@ +#![deny(warnings)] +#[doc = "`EventWithDefault`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +pub struct EventWithDefault { + #[serde(default = "defaults::event_with_default_when")] + pub when: ::jiff::Timestamp, +} +impl ::std::default::Default for EventWithDefault { + fn default() -> Self { + Self { + when: defaults::event_with_default_when(), + } + } +} +impl EventWithDefault { + pub fn builder() -> builder::EventWithDefault { + Default::default() + } +} +#[doc = "`IntegerDefaults`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +pub struct IntegerDefaults { + #[serde(default = "defaults::integer_defaults_big_nullable")] + pub big_nullable: ::std::option::Option<::std::num::NonZeroU64>, + #[serde(default = "defaults::default_nzu64::<::std::num::NonZeroU16, 3>")] + pub little_u16: ::std::num::NonZeroU16, + #[serde(default = "defaults::default_nzu64::<::std::num::NonZeroU8, 2>")] + pub little_u8: ::std::num::NonZeroU8, +} +impl ::std::default::Default for IntegerDefaults { + fn default() -> Self { + Self { + big_nullable: defaults::integer_defaults_big_nullable(), + little_u16: defaults::default_nzu64::<::std::num::NonZeroU16, 3>(), + little_u8: defaults::default_nzu64::<::std::num::NonZeroU8, 2>(), + } + } +} +impl IntegerDefaults { + pub fn builder() -> builder::IntegerDefaults { + Default::default() + } +} +#[doc = "`OuterThing`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug, Default)] +pub struct OuterThing { + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub thing: ::std::option::Option, +} +impl OuterThing { + pub fn builder() -> builder::OuterThing { + Default::default() + } +} +#[doc = "`TestBed`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +pub struct TestBed { + #[serde(default = "defaults::test_bed_any")] + pub any: ::std::vec::Vec<::serde_json::Value>, + #[serde(default = "defaults::test_bed_id")] + pub id: ::uuid::Uuid, +} +impl ::std::default::Default for TestBed { + fn default() -> Self { + Self { + any: defaults::test_bed_any(), + id: defaults::test_bed_id(), + } + } +} +impl TestBed { + pub fn builder() -> builder::TestBed { + Default::default() + } +} +#[doc = "`ThingWithDefaults`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +#[serde(deny_unknown_fields)] +pub struct ThingWithDefaults { + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub a: ::std::option::Option<::std::string::String>, + #[serde( + rename = "type", + skip_serializing_if = "::std::option::Option::is_none" + )] + pub type_: ::std::option::Option<::std::string::String>, +} +impl ::std::default::Default for ThingWithDefaults { + fn default() -> Self { + ThingWithDefaults { + a: Default::default(), + type_: ::std::option::Option::Some("bee".to_string()), + } + } +} +impl ThingWithDefaults { + pub fn builder() -> builder::ThingWithDefaults { + Default::default() + } +} +#[doc = "`UInt`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +#[serde(transparent)] +pub struct UInt(pub i64); +impl ::std::ops::Deref for UInt { + type Target = i64; + fn deref(&self) -> &i64 { + &self.0 + } +} +impl ::std::convert::From for i64 { + fn from(value: UInt) -> Self { + value.0 + } +} +impl ::std::convert::From for UInt { + fn from(value: i64) -> Self { + Self(value) + } +} +impl ::std::fmt::Display for UInt { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + self.0.fmt(f) + } +} +impl ::std::str::FromStr for UInt { + type Err = ::Err; + fn from_str(value: &str) -> ::std::result::Result { + Ok(Self(value.parse()?)) + } +} +#[doc = "`UIntContainer`"] +#[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] +pub struct UIntContainer { + #[serde(default = "defaults::u_int_container_max_path")] + pub max_path: UInt, +} +impl ::std::default::Default for UIntContainer { + fn default() -> Self { + Self { + max_path: defaults::u_int_container_max_path(), + } + } +} +impl UIntContainer { + pub fn builder() -> builder::UIntContainer { + Default::default() + } +} +#[doc = " Types for composing complex structures."] +pub mod builder { + #[derive(Clone, Debug)] + pub struct EventWithDefault { + when: ::std::result::Result<::jiff::Timestamp, ::std::string::String>, + } + impl ::std::default::Default for EventWithDefault { + fn default() -> Self { + Self { + when: Ok(super::defaults::event_with_default_when()), + } + } + } + impl EventWithDefault { + pub fn when(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::jiff::Timestamp>, + T::Error: ::std::fmt::Display, + { + self.when = value + .try_into() + .map_err(|e| format!("error converting supplied value for when: {e}")); + self + } + } + impl ::std::convert::TryFrom for super::EventWithDefault { + type Error = super::error::ConversionError; + fn try_from( + value: EventWithDefault, + ) -> ::std::result::Result { + Ok(Self { when: value.when? }) + } + } + impl ::std::convert::From for EventWithDefault { + fn from(value: super::EventWithDefault) -> Self { + Self { + when: Ok(value.when), + } + } + } + #[derive(Clone, Debug)] + pub struct IntegerDefaults { + big_nullable: ::std::result::Result< + ::std::option::Option<::std::num::NonZeroU64>, + ::std::string::String, + >, + little_u16: ::std::result::Result<::std::num::NonZeroU16, ::std::string::String>, + little_u8: ::std::result::Result<::std::num::NonZeroU8, ::std::string::String>, + } + impl ::std::default::Default for IntegerDefaults { + fn default() -> Self { + Self { + big_nullable: Ok(super::defaults::integer_defaults_big_nullable()), + little_u16: Ok(super::defaults::default_nzu64::<::std::num::NonZeroU16, 3>()), + little_u8: Ok(super::defaults::default_nzu64::<::std::num::NonZeroU8, 2>()), + } + } + } + impl IntegerDefaults { + pub fn big_nullable(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::num::NonZeroU64>>, + T::Error: ::std::fmt::Display, + { + self.big_nullable = value + .try_into() + .map_err(|e| format!("error converting supplied value for big_nullable: {e}")); + self + } + pub fn little_u16(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::num::NonZeroU16>, + T::Error: ::std::fmt::Display, + { + self.little_u16 = value + .try_into() + .map_err(|e| format!("error converting supplied value for little_u16: {e}")); + self + } + pub fn little_u8(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::num::NonZeroU8>, + T::Error: ::std::fmt::Display, + { + self.little_u8 = value + .try_into() + .map_err(|e| format!("error converting supplied value for little_u8: {e}")); + self + } + } + impl ::std::convert::TryFrom for super::IntegerDefaults { + type Error = super::error::ConversionError; + fn try_from( + value: IntegerDefaults, + ) -> ::std::result::Result { + Ok(Self { + big_nullable: value.big_nullable?, + little_u16: value.little_u16?, + little_u8: value.little_u8?, + }) + } + } + impl ::std::convert::From for IntegerDefaults { + fn from(value: super::IntegerDefaults) -> Self { + Self { + big_nullable: Ok(value.big_nullable), + little_u16: Ok(value.little_u16), + little_u8: Ok(value.little_u8), + } + } + } + #[derive(Clone, Debug)] + pub struct OuterThing { + thing: ::std::result::Result< + ::std::option::Option, + ::std::string::String, + >, + } + impl ::std::default::Default for OuterThing { + fn default() -> Self { + Self { + thing: Ok(Default::default()), + } + } + } + impl OuterThing { + pub fn thing(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.thing = value + .try_into() + .map_err(|e| format!("error converting supplied value for thing: {e}")); + self + } + } + impl ::std::convert::TryFrom for super::OuterThing { + type Error = super::error::ConversionError; + fn try_from( + value: OuterThing, + ) -> ::std::result::Result { + Ok(Self { + thing: value.thing?, + }) + } + } + impl ::std::convert::From for OuterThing { + fn from(value: super::OuterThing) -> Self { + Self { + thing: Ok(value.thing), + } + } + } + #[derive(Clone, Debug)] + pub struct TestBed { + any: ::std::result::Result<::std::vec::Vec<::serde_json::Value>, ::std::string::String>, + id: ::std::result::Result<::uuid::Uuid, ::std::string::String>, + } + impl ::std::default::Default for TestBed { + fn default() -> Self { + Self { + any: Ok(super::defaults::test_bed_any()), + id: Ok(super::defaults::test_bed_id()), + } + } + } + impl TestBed { + pub fn any(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec<::serde_json::Value>>, + T::Error: ::std::fmt::Display, + { + self.any = value + .try_into() + .map_err(|e| format!("error converting supplied value for any: {e}")); + self + } + pub fn id(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::uuid::Uuid>, + T::Error: ::std::fmt::Display, + { + self.id = value + .try_into() + .map_err(|e| format!("error converting supplied value for id: {e}")); + self + } + } + impl ::std::convert::TryFrom for super::TestBed { + type Error = super::error::ConversionError; + fn try_from(value: TestBed) -> ::std::result::Result { + Ok(Self { + any: value.any?, + id: value.id?, + }) + } + } + impl ::std::convert::From for TestBed { + fn from(value: super::TestBed) -> Self { + Self { + any: Ok(value.any), + id: Ok(value.id), + } + } + } + #[derive(Clone, Debug)] + pub struct ThingWithDefaults { + a: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + type_: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + } + impl ::std::default::Default for ThingWithDefaults { + fn default() -> Self { + Self { + a: Ok(Default::default()), + type_: Ok(Default::default()), + } + } + } + impl ThingWithDefaults { + pub fn a(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.a = value + .try_into() + .map_err(|e| format!("error converting supplied value for a: {e}")); + self + } + pub fn type_(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.type_ = value + .try_into() + .map_err(|e| format!("error converting supplied value for type_: {e}")); + self + } + } + impl ::std::convert::TryFrom for super::ThingWithDefaults { + type Error = super::error::ConversionError; + fn try_from( + value: ThingWithDefaults, + ) -> ::std::result::Result { + Ok(Self { + a: value.a?, + type_: value.type_?, + }) + } + } + impl ::std::convert::From for ThingWithDefaults { + fn from(value: super::ThingWithDefaults) -> Self { + Self { + a: Ok(value.a), + type_: Ok(value.type_), + } + } + } + #[derive(Clone, Debug)] + pub struct UIntContainer { + max_path: ::std::result::Result, + } + impl ::std::default::Default for UIntContainer { + fn default() -> Self { + Self { + max_path: Ok(super::defaults::u_int_container_max_path()), + } + } + } + impl UIntContainer { + pub fn max_path(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.max_path = value + .try_into() + .map_err(|e| format!("error converting supplied value for max_path: {e}")); + self + } + } + impl ::std::convert::TryFrom for super::UIntContainer { + type Error = super::error::ConversionError; + fn try_from( + value: UIntContainer, + ) -> ::std::result::Result { + Ok(Self { + max_path: value.max_path?, + }) + } + } + impl ::std::convert::From for UIntContainer { + fn from(value: super::UIntContainer) -> Self { + Self { + max_path: Ok(value.max_path), + } + } + } +} +#[doc = " Generation of default values for serde."] +pub mod defaults { + pub(super) fn default_nzu64() -> T + where + T: ::std::convert::TryFrom<::std::num::NonZeroU64>, + >::Error: ::std::fmt::Debug, + { + T::try_from(::std::num::NonZeroU64::try_from(V).unwrap()).unwrap() + } + pub(super) fn event_with_default_when() -> ::jiff::Timestamp { + ::serde_json::from_str::<::jiff::Timestamp>("\"1970-01-01T00:00:00Z\"") + .expect("invalid default provided") + } + pub(super) fn integer_defaults_big_nullable() -> ::std::option::Option<::std::num::NonZeroU64> { + ::std::option::Option::Some(::std::num::NonZeroU64::new(1).unwrap()) + } + pub(super) fn test_bed_any() -> ::std::vec::Vec<::serde_json::Value> { + vec![ + ::serde_json::from_str::<::serde_json::Value>("[8,6,7]") + .expect("invalid default provided"), + ::serde_json::from_str::<::serde_json::Value>("[5,3,0,9]") + .expect("invalid default provided"), + ] + } + pub(super) fn test_bed_id() -> ::uuid::Uuid { + ::serde_json::from_str::<::uuid::Uuid>("\"abc123-is-this-a-uuid\"") + .expect("invalid default provided") + } + pub(super) fn u_int_container_max_path() -> super::UInt { + super::UInt(1_i64) + } +} +#[doc = " Error types."] +pub mod error { + #[doc = r" Error from a `TryFrom` or `FromStr` implementation."] + pub struct ConversionError(::std::borrow::Cow<'static, str>); + impl ::std::error::Error for ConversionError {} + impl ::std::fmt::Display for ConversionError { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> { + ::std::fmt::Display::fmt(&self.0, f) + } + } + impl ::std::fmt::Debug for ConversionError { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> { + ::std::fmt::Debug::fmt(&self.0, f) + } + } + impl From<&'static str> for ConversionError { + fn from(value: &'static str) -> Self { + Self(value.into()) + } + } + impl From for ConversionError { + fn from(value: String) -> Self { + Self(value.into()) + } + } +} +fn main() {} diff --git a/typify/tests/schemas/types-with-defaults.json b/typify/tests/schemas/types-with-defaults.json index f3666710..0dcf3ffc 100644 --- a/typify/tests/schemas/types-with-defaults.json +++ b/typify/tests/schemas/types-with-defaults.json @@ -50,7 +50,7 @@ } } }, - "Doodad": { + "EventWithDefault": { "type": "object", "properties": { "when": { @@ -60,7 +60,7 @@ } } }, - "MrDefaultNumbers": { + "IntegerDefaults": { "type": "object", "properties": { "little_u8": { diff --git a/typify/tests/schemas/types-with-defaults.rs b/typify/tests/schemas/types-with-defaults.rs index 99b6fa2f..5b74249d 100644 --- a/typify/tests/schemas/types-with-defaults.rs +++ b/typify/tests/schemas/types-with-defaults.rs @@ -1,43 +1,43 @@ #![deny(warnings)] -#[doc = "`Doodad`"] +#[doc = "`EventWithDefault`"] #[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] -pub struct Doodad { - #[serde(default = "defaults::doodad_when")] +pub struct EventWithDefault { + #[serde(default = "defaults::event_with_default_when")] pub when: ::chrono::DateTime<::chrono::offset::Utc>, } -impl ::std::default::Default for Doodad { +impl ::std::default::Default for EventWithDefault { fn default() -> Self { Self { - when: defaults::doodad_when(), + when: defaults::event_with_default_when(), } } } -impl Doodad { - pub fn builder() -> builder::Doodad { +impl EventWithDefault { + pub fn builder() -> builder::EventWithDefault { Default::default() } } -#[doc = "`MrDefaultNumbers`"] +#[doc = "`IntegerDefaults`"] #[derive(:: serde :: Deserialize, :: serde :: Serialize, Clone, Debug)] -pub struct MrDefaultNumbers { - #[serde(default = "defaults::mr_default_numbers_big_nullable")] +pub struct IntegerDefaults { + #[serde(default = "defaults::integer_defaults_big_nullable")] pub big_nullable: ::std::option::Option<::std::num::NonZeroU64>, #[serde(default = "defaults::default_nzu64::<::std::num::NonZeroU16, 3>")] pub little_u16: ::std::num::NonZeroU16, #[serde(default = "defaults::default_nzu64::<::std::num::NonZeroU8, 2>")] pub little_u8: ::std::num::NonZeroU8, } -impl ::std::default::Default for MrDefaultNumbers { +impl ::std::default::Default for IntegerDefaults { fn default() -> Self { Self { - big_nullable: defaults::mr_default_numbers_big_nullable(), + big_nullable: defaults::integer_defaults_big_nullable(), little_u16: defaults::default_nzu64::<::std::num::NonZeroU16, 3>(), little_u8: defaults::default_nzu64::<::std::num::NonZeroU8, 2>(), } } } -impl MrDefaultNumbers { - pub fn builder() -> builder::MrDefaultNumbers { +impl IntegerDefaults { + pub fn builder() -> builder::IntegerDefaults { Default::default() } } @@ -150,18 +150,18 @@ impl UIntContainer { #[doc = " Types for composing complex structures."] pub mod builder { #[derive(Clone, Debug)] - pub struct Doodad { + pub struct EventWithDefault { when: ::std::result::Result<::chrono::DateTime<::chrono::offset::Utc>, ::std::string::String>, } - impl ::std::default::Default for Doodad { + impl ::std::default::Default for EventWithDefault { fn default() -> Self { Self { - when: Ok(super::defaults::doodad_when()), + when: Ok(super::defaults::event_with_default_when()), } } } - impl Doodad { + impl EventWithDefault { pub fn when(mut self, value: T) -> Self where T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>, @@ -173,21 +173,23 @@ pub mod builder { self } } - impl ::std::convert::TryFrom for super::Doodad { + impl ::std::convert::TryFrom for super::EventWithDefault { type Error = super::error::ConversionError; - fn try_from(value: Doodad) -> ::std::result::Result { + fn try_from( + value: EventWithDefault, + ) -> ::std::result::Result { Ok(Self { when: value.when? }) } } - impl ::std::convert::From for Doodad { - fn from(value: super::Doodad) -> Self { + impl ::std::convert::From for EventWithDefault { + fn from(value: super::EventWithDefault) -> Self { Self { when: Ok(value.when), } } } #[derive(Clone, Debug)] - pub struct MrDefaultNumbers { + pub struct IntegerDefaults { big_nullable: ::std::result::Result< ::std::option::Option<::std::num::NonZeroU64>, ::std::string::String, @@ -195,16 +197,16 @@ pub mod builder { little_u16: ::std::result::Result<::std::num::NonZeroU16, ::std::string::String>, little_u8: ::std::result::Result<::std::num::NonZeroU8, ::std::string::String>, } - impl ::std::default::Default for MrDefaultNumbers { + impl ::std::default::Default for IntegerDefaults { fn default() -> Self { Self { - big_nullable: Ok(super::defaults::mr_default_numbers_big_nullable()), + big_nullable: Ok(super::defaults::integer_defaults_big_nullable()), little_u16: Ok(super::defaults::default_nzu64::<::std::num::NonZeroU16, 3>()), little_u8: Ok(super::defaults::default_nzu64::<::std::num::NonZeroU8, 2>()), } } } - impl MrDefaultNumbers { + impl IntegerDefaults { pub fn big_nullable(mut self, value: T) -> Self where T: ::std::convert::TryInto<::std::option::Option<::std::num::NonZeroU64>>, @@ -236,10 +238,10 @@ pub mod builder { self } } - impl ::std::convert::TryFrom for super::MrDefaultNumbers { + impl ::std::convert::TryFrom for super::IntegerDefaults { type Error = super::error::ConversionError; fn try_from( - value: MrDefaultNumbers, + value: IntegerDefaults, ) -> ::std::result::Result { Ok(Self { big_nullable: value.big_nullable?, @@ -248,8 +250,8 @@ pub mod builder { }) } } - impl ::std::convert::From for MrDefaultNumbers { - fn from(value: super::MrDefaultNumbers) -> Self { + impl ::std::convert::From for IntegerDefaults { + fn from(value: super::IntegerDefaults) -> Self { Self { big_nullable: Ok(value.big_nullable), little_u16: Ok(value.little_u16), @@ -462,14 +464,13 @@ pub mod defaults { { T::try_from(::std::num::NonZeroU64::try_from(V).unwrap()).unwrap() } - pub(super) fn doodad_when() -> ::chrono::DateTime<::chrono::offset::Utc> { + pub(super) fn event_with_default_when() -> ::chrono::DateTime<::chrono::offset::Utc> { ::serde_json::from_str::<::chrono::DateTime<::chrono::offset::Utc>>( "\"1970-01-01T00:00:00Z\"", ) .expect("invalid default provided") } - pub(super) fn mr_default_numbers_big_nullable() -> ::std::option::Option<::std::num::NonZeroU64> - { + pub(super) fn integer_defaults_big_nullable() -> ::std::option::Option<::std::num::NonZeroU64> { ::std::option::Option::Some(::std::num::NonZeroU64::new(1).unwrap()) } pub(super) fn test_bed_any() -> ::std::vec::Vec<::serde_json::Value> {