r/rust•
Shadow0133

[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.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=78d9d07681b5c2b5fcb7f6a6f97b9b27

Posted May 1, 2020, 2:13 PM UTC · edited

58

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

2
throwaway_lmkg•

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.

6
Shadow0133OP•

Sadly, it won't work for horizontal split. For two horizontal windows layout looks like this:

llrr
llrr

which is stored in buffer as:

llrrllrr

so I can't split it into two slices here.

4
throwaway_lmkg•

I don't think that using pointers instead of slices is really saving you anything. You're handing out two objects that allow simultaneous access into the same array, and using custom indexer implementation to ensure that the two objects cannot access the same element of the shared array. I think that you could take your pointer arithmetic and convert it to index arithmetic with no changes.

I'm not following the logic around stride. If it's doing what I think it's doing, then shouldn't it be changed on one of the split methods?

I would do more tests around splitting a split of a split of a split.

2
Shadow0133OP•

stride is width of the underlying buffer, so it's always the same.

If I used mutable slices, horizontal split would make them overlap, which is illegal.

2

It is better call it `internal_stride` or `buf_stride` to make it more descriptive.

1
[deleted]•

[deleted]

1
jhk9x•

Why not make the FBWindow hold indexs only and let FBBuffer deal with the buffer fbbuffer.mut_window(fbwindow).fill(0).

1
Shadow0133OP•

That would work, but I think I prefer ergonomics and encapsulation of current solution (fn draw(&mut Buffer, Window) vs fn draw(&mut Window)). Thanks for the idea tho.

1