External Publication
Visit Post

`BitSlice` or a sound way to implement one

Rust Internals [Unofficial] May 6, 2026
Source

canndrew:

This is definitely only possible with language support. At the assembly level you can overwrite individual bits at a memory address with AND/ORD. But at the library level you're faced with the problem that you can't overwrite neighbouring bits you don't own, and you can't read+update them because they may be uninitialized or be being written concurrently.

The problem is that even at the assembly level, there's a risk of overwriting neighbouring bits you don't own (unless you use atomic read-modify-write instructions, which are frequently much slower than their nonatomic equivalents) – this doesn't matter in a single-threaded context (because you are overwriting them with the value they already have) but might in a multithreaded context. I think most languages don't expose an easy way to do this because most processors don't expose an easy way to do it, and languages are normally designed around processor functionality.

Even in the single-threaded context, the time paid due to the extra instructions is likely going to be higher than the time saved due to the lower memory usage unless you have a lot of values that aren't a whole number of bytes. In practice, this would only normally come up when you have an array of them (e.g. with a map, the savings would be negligible compared to the size of the keys). As such, it probably makes more sense to have bit-array / bit-slice / bit-vector types specifically rather than bit-references in general.

Discussion in the ATmosphere

Loading comments...