Should Option have as_ptr methods?


#1

Because of the null pointer optimisation, an Option<T> can be represented as a simple pointer if T: NonZero. To make FFI easier, would it make sense to add as_ptr() and as_mut_ptr() methods (returning *const T and *mut T respectively) to Option<T>?

My use case is that I’m writing FFI bindings for one of my libraries and it’s quite common to return a Option<&T> or Option<Box<T>> which then gets cast to *const T. It’d be better if I could replace those casts with a method call, seeing as it’s all too easy for me to think the null pointer optimisation applies when it doesn’t, which can lead to bad things happening. That way even though I’m using unsafe all over the place, the compiler can still help prevent some memory bugs.


#2

What happens if you just write the obvious match statement? Does the code compile to what you expect? If not, we should probably fix that. That way you’re not depending on the null-pointer optimization, but you are benefiting from it.


#3

I am frequently annoyed by the lack of a standard function to convert Option<&T> and friends to a pointer. Sure it’s possible to write code to do this manually, but this is unnecessary busy work for something that is simple and generally useful. Plus, there’s always the suspicion when you do it yourself of whether or not the compiler correctly optimizes it.

In my case I’m not using it for unsafe FFI, but rather for comparisons and hashmaps where I want to use reference equality rather than deep equality as is the default.

I believe this has previously been requested on Github, but it didn’t go anywhere.