I have a pointer buf: *const T pointing to the start of an allocation of n elements of T, and I define the following check:
let in_alloc = buf <= ptr && ptr < unsafe { buf.add(n) };
Is it guaranteed that in_alloc is true for any ptr that lies in the allocation of buf, and false in any other case? We may assume that ptr is a valid pointer to a T object (so not misaligned/null/dangling), however it may or may not be from the same allocation as buf. Finally we may assume T is not zero-sized.
Answering the title, comparing any two pointers is well-defined since pointers implement Ord.
With pointers being totally ordered, the body of the question follows easily from this. You have a set of n distinct pointers, starting at buf + 0 and ending at buf + (n - 1). If ptr is less than buf it can't be equal to any of them. If ptr is greater than buf + (n - 1) it also cannot be equal to them. If ptr is one of them, both expressions evaluate to true.
You can somewhat sidestep the issue and use Range instead:
let end = unsafe { buf.add(n) };
let in_alloc = (buf..end).contains(ptr);
This is often used, for example, to check if a slice contains a pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With