PyO3 / pyo3

Rust bindings for the Python interpreter
https://pyo3.rs
Other
11.44k stars 693 forks source link

add `c_str!` macro to create `&'static CStr` #4255

Closed davidhewitt closed 2 weeks ago

davidhewitt commented 2 weeks ago

With Rust 1.77 finally stabilising c"" c-string literals, I've wanted for a little while to be able to make better use of &'static CStr inside PyO3.

This PR proposes a pathway to doing that, by adding a c_str!("foo") macro to create a static c-string safely. With MSRV 1.63 we're able to support this on all versions.

This has the nice effect of moving work from runtime to compile time, because at the moment we have a lot of &str which need to be converted to &CStr using runtime checks. In the future when MSRV passes 1.77 we have a trivial cleanup to swap everything to c"" literals.

The only user-facing changes:

Icxolu commented 2 weeks ago

Big 👍 for this from me as well! This is a lot nicer and safer than having to remember to add the \0 and it also gets rid of a lot of casting which is nice to see.

davidhewitt commented 2 weeks ago

Given the two broadly positive sentiments, I think I'm going to merge this once I get CI passing. It'll make #4254 easier to finish implementing, which I want to complete ASAP with a view to then shipping 0.22.

If there are changes which are wanted (like the PythonDoc changes proposed above) let's put them into follow-up PRs or issues to land after we've shipped and unblocked everyone downstream from 3.13 testing.