rust-lang / unsafe-code-guidelines

Forum for discussion about what unsafe code can and can't do
https://rust-lang.github.io/unsafe-code-guidelines
Apache License 2.0
657 stars 57 forks source link

std::slice::from_raw_parts alternative that would allow NULL pointer if len == 0 by returning an empty slice? #496

Closed procedural closed 7 months ago

procedural commented 7 months ago

Currently, it's not allowed to pass a NULL pointer to std::slice::from_raw_parts, but

I have a pointer that comes from a C function that can be either:

A) A non-NULL with a len > 0 B) A NULL with a len == 0

It would be neat if I could just write:

let values = unsafe { std::slice::from_raw_parts_or_empty(c_ptr_to_values, len) }; // Still panic if c_ptr_to_values == NULL and len > 0.
for value in values {
    // This can be skipped if values is an empty slice when c_ptr_to_values == NULL and len == 0.
    // Or values can be iterated when c_ptr_to_values != NULL and len > 0.
}
RalfJung commented 7 months ago

I think this is a t-libs-api issue, there are no open questions from the UCG side here. UCG is concerned with the language aspects of writing unsafe.

procedural commented 7 months ago

@RalfJung thanks, sure, I didn't know where to ask this. Can this issue be moved to the related repo?

RalfJung commented 7 months ago

t-libs-api has their own process that that wouldn't really make sense.

Discussing this on https://internals.rust-lang.org/ might be a good idea, otherwise the process is to file an ACP. You can also always ask on Zulip. :)