From 9432677d3a0d275105acf5cc58ec3c92a12327cb Mon Sep 17 00:00:00 2001 From: sharkdp Date: Sat, 31 Oct 2020 10:10:46 +0100 Subject: [PATCH] Disallow block sizes of 0 closes #110 --- CHANGELOG.md | 1 + src/bin/hexyl.rs | 40 ++++++++++++++++++++++++++++---------- tests/integration_tests.rs | 15 ++++++++++++++ 3 files changed, 46 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c625950..6e7d7a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - Argument `--length` silently takes precedence over `--bytes`, see #105 - Print warning on empty content, see #107 and #108 +- Disallow block sizes of zero, see #110 ## Other diff --git a/src/bin/hexyl.rs b/src/bin/hexyl.rs index 71042dd..81a3ccd 100644 --- a/src/bin/hexyl.rs +++ b/src/bin/hexyl.rs @@ -135,12 +135,8 @@ fn run() -> Result<(), AnyhowError> { .map_err(|e| anyhow!(e)) .and_then(|x| { PositiveI64::new(x) - .ok_or_else(|| anyhow!("negative block sizes don't make sense")) + .ok_or_else(|| anyhow!("block size argument must be positive")) }) - .context(anyhow!( - "failed to parse `--block-size` arg {:?} as positive integer", - bs - )) }) .transpose()? .unwrap_or_else(|| PositiveI64::new(512).unwrap()); @@ -250,12 +246,36 @@ fn main() { } } +#[derive(Clone, Copy, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub struct NonNegativeI64(i64); + +impl NonNegativeI64 { + pub fn new(x: i64) -> Option { + if x.is_negative() { + None + } else { + Some(Self(x)) + } + } + + pub fn into_inner(self) -> i64 { + self.0 + } +} + +impl Into for NonNegativeI64 { + fn into(self) -> u64 { + u64::try_from(self.0) + .expect("invariant broken: NonNegativeI64 should contain a non-negative i64 value") + } +} + #[derive(Clone, Copy, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)] pub struct PositiveI64(i64); impl PositiveI64 { pub fn new(x: i64) -> Option { - if x.is_negative() { + if x < 1 { None } else { Some(Self(x)) @@ -285,7 +305,7 @@ enum ByteOffsetKind { #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] struct ByteOffset { - value: PositiveI64, + value: NonNegativeI64, kind: ByteOffsetKind, } @@ -294,7 +314,7 @@ struct ByteOffset { struct NegativeOffsetSpecifiedError; impl ByteOffset { - fn assume_forward_offset_from_start(&self) -> Result { + fn assume_forward_offset_from_start(&self) -> Result { let &Self { value, kind } = self; match kind { ByteOffsetKind::ForwardFromBeginning | ByteOffsetKind::ForwardFromLastOffset => { @@ -351,7 +371,7 @@ fn parse_byte_offset(n: &str, block_size: PositiveI64) -> Result