Is this OK to do?
fn main() {
let test = &mut 77f32;
{
let ptr1 = test as *mut f32;
let ptr2 = test as *mut f32;
unsafe {
*ptr2 = 32f32;
};
}
assert_eq!(*test, 32f32);
}
In the actual app the circumstance is that I have an API that needs to return a pointer to an object. The consumer of that API knows whether or not it is safe to mutate the pointer because it has exclusive access, or whether it is safe to read the pointer, because all of the other pointers will only read as well. AKA, the client is doing the borrow checking, so my API was just returning mutable pointers that it expects the client to cast to what it actually needs and knows that is safe. ( this is for an ECS scripting API )
Does this work? Is two mutable pointers UB if I don't dereference it? I assume just having them can't be UB because I can actually create 100 mutable pointers to the same object in 100% safe Rust, as long as I don't dereference it.
fn main() {
let test = &mut 77f32;
let mut v = vec![];
for _ in 0..100 {
v.push(test as *mut f32);
}
}
I just realized that I'm pretty sure that proves it, but I'll leave the post up anyway in case there is more wisdom to be gained. ![]()
Oh, like would it be better to leave them *const pointers and then the client can decide that it's safe to cast them to *mut pointers if it needs to mutate?
PS: I just realized that I do know the size and the lifetime of the pointer I have, even if I don't know the mutability, so it's probably just safer to return a &mut [u8] and let the client handle casting that as it needs. Still, maybe returning a &[u8] that the client can cast to a &mut [u8] is better than always returning a &mut [u8] and expecting the client not to mutate it if it isn't allowed to.
Except it seems like Rust doesn't like you to transmut from &[u8] to &mut [u8] without an ( overridable ) compile error, so maybe just returning &mut [u8] does make sense?
Sorry for the sort of rambling post ![]()