[Unsafe review] Framebuffer splitting
I'm writing helper library for minifb. It allows to split buffer ([u32]) into windows, like tmux split-window -{v,h}. There is some raw pointer juggling, but I think it's safe. Miri doesn't shows any errors.
Main part is fn split_{v,h}(&mut self, pos: usize) -> Option<(FBWindow, FBWindow)>, where split_h can't be implemented using safe Rust (or, at least, easily).
With split_v, you have top and bottom part, which you could implement using split_at_mut. But for split_h, you would have two overlapping mutable slice, which is illegal. You could hold Vec<&mut [u32]> with slice per line, but it would somewhat inefficient. So FBWindow hold pointer to start of window, its size, and stride (which is a width of underlying buffer, and allows calculating next lines).
The only unsafe blocks are in indexing.
Posted May 1, 2020, 2:13 PM UTC · edited
You can easily implement it without unsafe, just using slices and split_at and split_at_mut.
https://doc.rust-lang.org/std/primitive.slice.html#method.split_at
It's a 2-D array, stored as a linear buffer. You can implement splitting one dimension simply using
split_at, but splitting the other dimension is difficult because the parts of the two result buffers are interleaved.Sadly, it won't work for horizontal split. For two horizontal windows layout looks like this:
which is stored in buffer as:
so I can't split it into two slices here.