Could you borrow a bit?
Borrowing a bit would be like partially borrowing a struct. You need a reference that's a pointer to a whole but only allowed access to a part.
More complications arise if you wanted simultaneous borrows of different bits in the same byte - basically, mutable access to those can't co-exist thread-safely.
The layout of &bool prevents having this kind of functionality.
Implementation-wise I can imagine either an approach like &bit<N> for borrowing the Nth bit in a byte for N known at compile time, or we need to extend the representation of what a reference to a bit contains, maybe a far pointer where the sub-byte position is given in the metadata (like length for slices).
Similarly, there are other parallels to slice references that a reference to a single bit would need to come with: you shouldn't be allowed to perform operations like mem::replace on it! It could be through being !Sized, or some comparable mechanism. That's because operations like mem::replace are generally implemented by considering only the size of the type - in bytes - and then copying that amount of bytes around. You don't want that, because it would result in all the neighboring bits in the same byte being replaced along with the one you were meaning to reference.
I wonder if the feature discussions in Public view of rust-lang | Zulip team chat have any power of supporting references to less-than-byte (or otherwise intermixed in the encoding) amounts of data.[1]
- I have yet to catch up with all the details / ideas being discussed there more in-depth. ↩︎
Discussion in the ATmosphere