this post was submitted on 15 Nov 2025
6 points (100.0% liked)

Rust

7509 readers
17 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 2 years ago
MODERATORS
 

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.

you are viewing a single comment's thread
view the rest of the comments
[–] TehPers@beehaw.org 1 points 1 week 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.