For example, is there any problems with doing this?

fn main() {  
	static mut BUF: [u8; 0x400] = [0; 0x400];  
	let buf = &mut unsafe { BUF };  
}  

and is this code the same as just using an array directly? From my understanding local variables get put on the stack but do the static variables do too?

I’m essentially trying to find the most performant way to get a simple read/write buffer.

  • TehPers@beehaw.org
    link
    fedilink
    English
    arrow-up
    1
    ·
    2 days ago

    Another commenter already explained why this is unsound, so I’ll skip that, though static mut is almost universally unsound.

    Note, of course, that main() won’t be called more than once, so if you can, I would honestly just make this a stack variable containing a Box<[u8; 0x400]> instead. Alternatively, a Box<[u8]> can make it simpler to pass around, and a Vec<u8> that is pre-allocated with Vec::with_capacity lets you track the current length as well with the buffer (if it’s going to have a variable length of actually useful data).

    If you want to make it a static for some reason, I’d recommend making it just static and thread_local, then wrapping it in some kind of cell. Making it thread local will mean you don’t need to lock to access it safely.