-
Notifications
You must be signed in to change notification settings - Fork 111
[codec] Add Zeroed type #1804
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
fedemagnani
wants to merge
1
commit into
commonwarexyz:main
Choose a base branch
from
fedemagnani:issue-1703
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
[codec] Add Zeroed type #1804
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,3 +12,4 @@ pub mod net; | |
pub mod primitives; | ||
pub mod tuple; | ||
pub mod vec; | ||
pub mod zeroed; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
//! Zero-padded data codec implementation. | ||
use crate::{error::Error, util::at_least, EncodeSize, Read, Write}; | ||
use bytes::{Buf, BufMut}; | ||
|
||
/// A codec for zero-padded data of a specified length. | ||
/// | ||
/// When decoding, it validates that all bytes in the specified range are zero, | ||
/// returning an error if any non-zero bytes are found. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Zeroed { | ||
n: usize, | ||
} | ||
|
||
impl Zeroed { | ||
/// Creates a new `Zeroed` instance for `n` bytes. | ||
pub fn new(n: usize) -> Self { | ||
Self { n } | ||
} | ||
} | ||
|
||
impl Read for Zeroed { | ||
type Cfg = usize; | ||
|
||
/// Reads and validates zero-padded data from the buffer. | ||
/// | ||
/// The configuration specifies the expected number of zero bytes to read. | ||
/// This method validates that all bytes in the specified range are zero, | ||
/// returning an error if any non-zero bytes are encountered. | ||
/// | ||
/// ```rust | ||
/// use commonware_codec::{Read, EncodeSize}; | ||
/// use commonware_codec::types::zeroed::Zeroed; | ||
/// | ||
/// let mut buf = &[0u8, 0u8, 0u8, 0u8][..]; | ||
/// let zeroed = Zeroed::read_cfg(&mut buf, &4).unwrap(); | ||
/// assert_eq!(zeroed.encode_size(), 4); | ||
/// ``` | ||
fn read_cfg(buf: &mut impl Buf, n: &Self::Cfg) -> Result<Self, Error> { | ||
at_least(buf, *n)?; | ||
|
||
let mut remaining = *n; | ||
while remaining > 0 { | ||
let chunk = buf.chunk(); | ||
let len: usize = chunk.len().min(remaining); | ||
if chunk[..len].iter().any(|&b| b != 0) { | ||
return Err(Error::Invalid("Zeroed", "bytes are not zero")); | ||
} | ||
buf.advance(len); | ||
remaining -= len; | ||
} | ||
|
||
Ok(Self { n: *n }) | ||
} | ||
} | ||
|
||
impl Write for Zeroed { | ||
/// Writes zero bytes to the buffer. | ||
/// | ||
/// This method writes exactly `n` zero bytes to the provided buffer | ||
fn write(&self, buf: &mut impl BufMut) { | ||
buf.put_bytes(0, self.n); | ||
} | ||
} | ||
|
||
impl EncodeSize for Zeroed { | ||
/// Returns the encoded size of the zero-padded data. | ||
fn encode_size(&self) -> usize { | ||
self.n | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::Encode; | ||
use bytes::BytesMut; | ||
|
||
#[test] | ||
fn test_zeroed() { | ||
let zeroed = Zeroed::new(4); | ||
let encoded = zeroed.encode(); | ||
assert_eq!(encoded.len(), 4); | ||
} | ||
|
||
#[test] | ||
fn test_read() { | ||
let mut buf = &[0u8, 0u8, 0u8, 0u8][..]; | ||
let zeroed = Zeroed::read_cfg(&mut buf, &4).unwrap(); | ||
assert_eq!(zeroed.encode_size(), 4); | ||
} | ||
|
||
#[test] | ||
fn test_faulty_read_not_zero() { | ||
let mut buf = &[0u8, 0u8, 0u8, 1u8][..]; | ||
assert!(matches!( | ||
Zeroed::read_cfg(&mut buf, &4), | ||
Err(Error::Invalid("Zeroed", "bytes are not zero")) | ||
)); | ||
} | ||
|
||
#[test] | ||
fn test_faulty_read_too_short() { | ||
let mut buf = &[0u8, 0u8, 0u8][..]; | ||
assert!(matches!( | ||
Zeroed::read_cfg(&mut buf, &4), | ||
Err(Error::EndOfBuffer) | ||
)); | ||
} | ||
|
||
#[test] | ||
fn test_write() { | ||
let zeroed = Zeroed::new(4); | ||
let mut buf = BytesMut::new(); | ||
zeroed.write(&mut buf); | ||
assert_eq!(buf.len(), 4); | ||
assert!(buf.iter().all(|&b| b == 0)); | ||
} | ||
|
||
#[test] | ||
fn test_encode_size() { | ||
let zeroed = Zeroed::new(4); | ||
assert_eq!(zeroed.encode_size(), 4); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would it make more sense to have
Zeroed<const N: usize>
similar to theFixedSize
type inutils/
? Then theread_cfg
Read::Cfgtype could be
()`There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unfortunately it looks like that in stable Rust currently, only constants that are independent of generic type resolution can be used in const generics.
Associated constants of traits (e.g. V::SIZE) are type-dependent and therefore cannot currently appear in const generic arguments. This is the tracking issue on rust to enable generic const expres