Add type which encodes statically that a sequence of bytes are all zero
- Dominant language
- Rust
- Stars
- 2.6k
- Forks
- 179
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 29
Description
*See also: #2273*
Especially in combination with the `FromZeroes` trait, it would be useful to be able to represent statically that a sequence of bytes are currently zero. Some operations which produce guaranteed-zero bytes (such as allocating new virtual memory pages) could get a performance or safety benefit from this functionality.
One hypothetical API would look like this, but there could be other ways of designing this:
```rust
// All bytes are 0. Note that there may be subtle interactions with
// interior mutability when handing out immutable references.
#[repr(transparent)]
pub struct Zero(T);
// `T: AsBytes` allows us to inspect `T`'s bytes to confirm that they're all 0
impl Zero {
pub fn new(t: T) -> Option> { ... }
pub fn try_from_slice(ts: &[T]) -> Option<&[Zero]> { ... }
}
impl Zero {
pub unsafe fn new_unchecked(t: T) -> Zero { ... }
}
impl Zero {
pub fn try_from_ref(t: &T) -> Option<&Zero> { ... }
}
impl Zero {
pub unsafe fn from_ref_unchecked(t: &T) -> &Zero { ... }
}
impl Deref for Zero { ... }
pub unsafe trait FromZeroes {
fn from_bytes(bytes: Zero>) -> Self { ... }
fn from_slice(bytes: &[Zero]) -> Option<&[Self]> { ... }
// Maybe modify existing zeroing methods to return a `Zero`?
fn new_zeroed() -> Zero { ... }
}
```
Contributor guide
Assessment
This issue has not been assessed yet.