Skip to content

Commit

Permalink
Make serde_with schemars support extensible
Browse files Browse the repository at this point in the history
Implementing JsonSchema directly on serde_with::Schema<T, TA> works fine
when within serde_with. Once you are outside the crate, however, the
orphan rules prevent you from adding impls of the form

impl JsonSchema for Schema<T, MyCustomType> { ... }

We would like users to be able to make that impl (or something
equivalent) so we need to find a way to make it work. We make this work
by adding a new layer of trait indirection.

This commit introduces an new JsonSchemaAs<T> trait, adds a blanket

impl<T, TA> JsonSchema for Schema<T, TA> where TA: JsonSchemaAs<T>

and then changes all the existing impls to be for JsonSchemaAs<T>.

Now, when a user wants to add json schema support for their own type
they can implement JsonSchemaAs<T> for their custom type and the orphan
rules will allow it.

As a bonus, this seems to have made the extraordinarily confusing
"reached recursion limit" errors that I have been encountering
disappear. Which is nice.
  • Loading branch information
swlynch99 committed Jan 19, 2024
1 parent 170b6e1 commit b0ee3ab
Show file tree
Hide file tree
Showing 2 changed files with 196 additions and 60 deletions.
2 changes: 1 addition & 1 deletion serde_with/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ pub mod json;
mod key_value_map;
pub mod rust;
#[cfg(feature = "schemars_0_8")]
mod schemars_0_8;
pub mod schemars_0_8;
pub mod ser;
#[cfg(feature = "std")]
mod serde_conv;
Expand Down
Loading

0 comments on commit b0ee3ab

Please sign in to comment.