Skip to content

Commit

Permalink
feat: add block getters (#264)
Browse files Browse the repository at this point in the history
* feat: add block getters

* fix: block size valid values
  • Loading branch information
cakekindel authored Mar 20, 2023
1 parent 45dc72e commit 6dc24f3
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 10 deletions.
18 changes: 9 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions toad-msg/src/msg/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,12 @@ pub trait MessageOptions {
.map(|_| ())
}

/// [`opt::known::no_repeat::BLOCK1`]
fn block1(&self) -> Option<block::Block> {
self.get_u32(opt::known::no_repeat::BLOCK1)
.map(block::Block::from)
}

/// [`opt::known::no_repeat::BLOCK1`]
fn set_block1(&mut self, size: u16, num: u32, more: bool) -> Result<(), Self::SetError> {
let block = block::Block::new(size, num, more);
Expand All @@ -416,6 +422,12 @@ pub trait MessageOptions {
.map(|_| ())
}

/// [`opt::known::no_repeat::BLOCK2`]
fn block2(&self) -> Option<block::Block> {
self.get_u32(opt::known::no_repeat::BLOCK2)
.map(block::Block::from)
}

/// [`opt::known::no_repeat::BLOCK2`]
fn set_block2(&mut self, size: u16, num: u32, more: bool) -> Result<(), Self::SetError> {
let block = block::Block::new(size, num, more);
Expand Down
20 changes: 19 additions & 1 deletion toad-msg/src/msg/opt/known/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ impl Block {
pub fn new(size: u16, num: u32, more: bool) -> Self {
let num = num << 4;
let more = u32::from(more) << 3;
let size = f32::from(size).log2() as u32 - 4;
let size = f32::from(size.max(16).min(1024)).log2() as u32 - 4;

Self(num | more | size)
}
Expand Down Expand Up @@ -39,6 +39,12 @@ impl From<Block> for u32 {
}
}

impl From<u32> for Block {
fn from(n: u32) -> Self {
Block(n)
}
}

#[cfg(test)]
mod test {
use super::*;
Expand All @@ -58,4 +64,16 @@ mod test {
assert_eq!(Block::new(32, 2, false), Block(33));
assert_eq!(Block::new(128, 3, true), Block(59));
}

#[test]
fn size_rounds_down_to_nearest_power_of_two() {
assert_eq!(Block::new(0, 1, false).size(), 16);
assert_eq!(Block::new(10, 1, false).size(), 16);
assert_eq!(Block::new(17, 1, false).size(), 16);
assert_eq!(Block::new(31, 1, false).size(), 16);
assert_eq!(Block::new(33, 1, false).size(), 32);
assert_eq!(Block::new(64, 1, false).size(), 64);
assert_eq!(Block::new(1024, 1, false).size(), 1024);
assert_eq!(Block::new(2048, 1, false).size(), 1024);
}
}

0 comments on commit 6dc24f3

Please sign in to comment.