madsmtm / objc2

Bindings to Apple's frameworks in Rust
https://docs.rs/objc2/
MIT License
280 stars 35 forks source link

Use `&CStr` instead of `&str` in runtime functions #564

Open madsmtm opened 4 months ago

madsmtm commented 4 months ago

Objective-C runtimes use C strings, which we convert to and from &str in objc2::runtime. This unfortunately makes our interop not zero-cost, as we often have to allocate to get an extra zero-byte in the string.

Instead, we should expose the methods with a type of &CStr. This will make those functions accept and return non-UTF-8 strings though, but I think that is also strictly the correct thing to do? Usually, the strings will be C identifiers, which are a restricted subset of ASCII, and Swift's Unicode identifiers are encoded as UTF-8, but I don't think that's required as part of the contract? I.e. I'm allowed to make classes with a non-UTF-8 name, and that's sound, it'll just be very unexpected.

I'm not going to do this before c"..." string literatals are stable though, as the ergonomics are considerably worse without that.