Any possibility of interior mutability?

I have a struct like

struct MyThing<'a> {
    buf: &'a [u8]
}

I want to make it as efficient as possible by validating the bytes then doing unchecked memory offsets. This would be unsafe if someone used interior mutability to change the content. Is this possible?

It's not possible to change content of &[u8] in any way. Existence of this type is itself a guarantee that these bytes won't change.

You would need &mut [u8] or &[Cell<u8>] or &[UnsafeCell<u8>] or some other type.

3 Likes

Thanks.

Kornel is correct that the bytes of a &[u8] cannot change while that value exists, but note that reassigning the buf field of a MyThing value would still be problematic if you're doing unchecked stuff to it in safe methods. You have to make the field private and ensure that none of the code in your crate reassigns it after creation.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.