jsontypedef / json-typedef-codegen

A CLI tool that generates code from JSON Typedef schemas
https://jsontypedef.com/docs/tools/jtd-codegen
MIT License
160 stars 31 forks source link

Better handling of optional properties in Rust #45

Open pchampin opened 2 years ago

pchampin commented 2 years ago

The problem

Currently, optional properties have their type systematically wrapped in Option<Box<...>> in Rust. This is not satisfying. This creates an unnecessary allocation on the heap, as well as a significant memory overhead for atomic types (especially small ones such as i8 or u8).

The Box is actually here only to ensure that the generated Rust code will compile when recursive types are involved.

Proposed solution

This PR introduces a detection of recursive types, and only uses Box for them. Any other type in optional properties is now simply wrapped in Option<...>.

Note that this strategy it is still overly defensive. Recursive types are wrapped in Box everywhere, including places where this would not be necessary (and not just in Option<...>). This could maybe be improved, but I consider that this is still better than the current situation. Of course the user can still override this with metadata.rustType.

This PR is still marked WIP because

But before continuing, I would like to get the maintainers opinion on that proposition ;)