rustls / rustls-ffi

Use Rustls from any language
Other
127 stars 30 forks source link

arc_castable!, box_castable!, ref_castable! macros #404

Closed cpu closed 5 months ago

cpu commented 6 months ago

Throughout the project we follow a pattern of implementing safe bridge types for FFI by:

  1. Creating a snake_case_named opaque struct.
  2. Implementing Castable for the struct: a. specifying a RustType (some native Rust type). b. specifying an Ownership (OwnershipBox, OwnershipArc, OwnershipRef).

In the case of OwnershipRef we may also need to add a PhantomData field referencing a lifetime to the opaque struct.

To reduce the boilerplate of doing all of the above over and over this commit adds three new macros (loosely inspired by the Rustls enum_builder! macro) that accomplish the task with less ceremony (as suggested in https://github.com/rustls/rustls-ffi/issues/151): arc_castable!, box_castable!, and ref_castable!.

Care has been taken to avoid the downside mentioned in 151 about rustdoc comments. The macros ensure the doc comments we add are associated with the correct type and not the macro itself. We can verify this fact by noting that the generated rustls.h header file that contains these comments has not changed with the introduction of the macros.

Existing instances of the pattern are updated to use these macros with one exception: the rustls_client_hello type implements Castable with OwnershipRef for rustls_client_hello<'a>, but it isn't the same opaque struct pattern as used elsewhere and so is best implemented by hand.

I've spot checked the expansion of the macros against my expectations and was happy with the results. If you want to do the same thing, here's a cargo expand of 10c5324.

Resolves https://github.com/rustls/rustls-ffi/issues/151