Better (safer) C/Swift String interop

I’ll prefix this with this is all based off working on GitHub - vapor/authentication: 👤 Lightweight authentication framework for Swift and trying to make the C bcrypt interop as safe as possible.

The recent 6.2 changes have been great at exposing span-based APIs for passing in buffers we want to write to. This removed all of the need for unsafe code on the Swift side. However we’re still required to annotate calls with unsafe when enabling strict memory safety because the generated Swift APIs require an Unsafe*Pointer when passing in a String to a const char *, despite the fact you can just pass a String without needing to turn it into a pointer.

This feels counter intuitive from a user’s point of view so I wanted to make sure I’m not missing any annotations? The workaround seems to be to annotate the String call sites with the same bounds and lifetime annotations (e.g. Add bcrypt and OTP traits by 0xTim · Pull Request #77 · vapor/authentication · GitHub) and then you can use myString.utf8CString.span but this seems more work from the user’s side than it needs to be

2 Likes