Conversation
|
r? @kennytm (rust-highfive has picked a reviewer for you, use r? to override) |
|
Isn't it better to convert the pair of pointers coming from C or C++ into something like a slice, for Rust usage? What do you need all those pointers for in Rust code? |
|
If let start = !1 as *const [u8; 2];
let end = !0 as *const [u8; 2];
(start..end).next(); |
In FFI, I definitely don't think so. Materializing a reference (to a slice, or even to individual elements) is more prone to UB in Rust than directly working with the foreign pointers as pointers. One basically has to be an expert in Rust aliasing rules, which are not necessarily cogently written down at this point yet, in order to do it correctly. Whereas someone with basic C++ knowledge can write the pointer-based code and have it be correct. Compare: let start: *mut T = ...;
let end: *mut T = ...;
for ptr in start..end {
// Only the preconditions of the C++ callee come into play, which a C++ dev
// is already going to be comfortable reasoning about. Nothing about stacked
// borrows, concurrency, initializedness, inhabitedness, alignedness, or other
// Rust-isms is relevant.
unsafe { cpp(ptr); }
}let mut slice = std::slice::from_raw_parts_mut(...); // suddenly a pile of extremely subtle
// invariants in order for this to be allowed
for elem in slice {
unsafe { cpp(elem as *mut T); } // probably UB
} |
Good call. Hopefully this is fixable within the constraints of the |
dtolnay
left a comment
There was a problem hiding this comment.
`Step` invariants not upheld
It turns out the desired semantics for pointer ranges is incompatible with the current requirements of Step, so I've opened #91000 with a different approach. Closing this PR in favor of that one.
This PR adds
std::iter::Stepimpls for*const Tand*mut T, enabling iteration over a range of pointers, such as produced by<[T]>::as_ptr_rangeand<[T]>::as_mut_ptr_range.It is common for systems interacting with C++ to need to use pointer ranges for iteration, as
begin/endpointer pairs are a design pattern in the C++ standard library.