google / google/zerocopy

`Zero` integer types

Open
#2,273 2 comments 0 reactions 0 assignees View on GitHub
customer-request
Dominant language
Rust
Stars
2.6k
Forks
179
Avg merge
1d 19h
Merged PRs (30d)
29

Description

We've implemented some protocols that are designed to require all-zeroes in segments of the message. We ended up making this statically required by defining wrapper types around an `enum`. Example for `u32`:

```rust
#[derive(Clone, Copy, Default, IntoBytes, Immutable, FromZeros)]
#[repr(u32)]
enum AlignedZeroU32 {
#[default]
Zero = 0,
}

#[repr(C, packed)]
#[derive(Clone, Copy, Default, IntoBytes, FromZeros, Immutable)]
pub struct ZeroU32(AlignedZeroU32);
impl PartialEq for ZeroU32 {
fn eq(&self, other: &ZeroU32) -> bool { true }
}

impl fmt::Debug for ZeroU32 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
// No need to debug the inner field.
fmt.debug_struct("ZeroU32").finish()
}
}

// PartialEq against u32 with `== 0`, U32 with `== U32::ZERO`
```

There were enough hurdles to jump through to implement this correctly that it'd be convenient to have these as types within `zerocopy`. This doesn't use `zerocopy::Unalign` because `PartialEq` and `Debug` require manual implementations

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.