3 ms·
As the article notes in an edit, there's a method for this: split_at_mut(). It's very useful, and I reach for it quite a bit in low-level array code. It might
by pcwalton 9y ago
As the article notes in an edit, there's a method for this: split_at_mut(). It's very useful, and I reach for it quite a bit in low-level array code.
It might be nice to have some sort of pattern matching syntax for it, I suppose:
let [ref mut a..16, ref mut b..] = *c;
Meh. Sure is ugly. I'm not sure adding syntax would be worth it.
- phaylon 9y agoWell, if we're having some bike-shedding fun: let (a, b) = c[..16..];
- comex 9y agoI feel like split_at_mut is a bit of a red herring - sure, it's exactly what the author was looking for and unable to find, but it's masking a bigger problem/opportunity here. Why does the author have to worry about aliasing in the first place? If they're dealing with POD types, there's no memory safety issue implicated by allowing overlapping slices (except possibly when accessing from multiple threads). No-alias guarantees can improve performance in many cases (though rustc currently isn't doing the best job conveying them to LLVM), but not always, and especially in something like a video codec, the author may prefer to manually optimize memory access patterns. In my own code, I worked around this by using &[Cell<u8>] as an aliasable mutable buffer type. I had a function to cast to it from &mut [u8], as well as functions to read and write integers of various sizes by directly casting the pointer (although this may not be necessary, as LLVM can probably optimize the naive approach of calling .get()/.set() on each Cell individually). Simple enough, and I'm pretty sure it's safe, but I've never seen anyone else use this approach, and I don't know of any crates.io crates that implement it. Maybe I should write one...
- dbaupp 9y agoIt is safe, and was even modeled explicitly as part of https://www.ralfj.de/blog/2017/07/08/rustbelt.html https://www.ralfj.de/blog/2017/07/08/rustbelt.html . There's the external https://crates.io/crates/alias https://crates.io/crates/alias and even an approved RFC for adopting it into std: https://github.com/rust-lang/rust/issues/43038 https://github.com/rust-lang/rust/issues/43038 .
- comex 9y agoDoh, way ahead of me then. Though it seems there are more steps needed, e.g. adding support to the ‘bytes’ crate.