Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use UnsafeCell to get around rules for uninitialized memory

Tags:

rust

unsafe

Rust's rules about uninitialized memory drive me up the wall.

It's undefined behavior to create a &mut [u8] if the [u8] is uninitialized—and then pass that to read() which fills the bytes. This cripples the io::Read trait if you care about those kinds of things.

UnsafeCell is a bit of safety valve for a lot of things in Rust. Could UnsafeCell<[u8]> be used to create a &mut [u8] to uninitialized memory, or is that still off limits?

I think given how UnsafeCell tells the compiler to be very conservative with its assumptions, it probably would work, regardless of whether it's allowed. But that's another hill to die on.

How wrong am I?

like image 511
Eloff Avatar asked Oct 31 '25 02:10

Eloff


1 Answers

For all references, &T, the value T needs to be initialized. UnsafeCell does not change that.

UnsafeCell is the wrong tool anyway - it is a primitive that provides interior mutability (e.g. the ability to mutate behind an immutable reference). Nothing to do with uninitialized data. The more relevant primitive would be MaybeUninit since that designed for handling uninitialized or partially initialized values. However, that can't help you here either since &[u8] still requires those u8s to be initialized no matter how they are backed. The Read interface would need to be changed to accept &[MaybeUninit<u8>] or something similar.

You are right that this somewhat "cripples" the trait. This is known and there is an issue for expanding it to support uninitialized buffers.

like image 154
kmdreko Avatar answered Nov 03 '25 13:11

kmdreko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!