Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 19 additions & 20 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ Examples: --length=64, --length=4KiB, --length=0xff";

const SKIP_HELP_TEXT: &str = "Skip the first N bytes of the input. The N argument can also \
include a unit (see `--length` for details).
A negative value is valid and will seek from the end of the file.";
A negative value is valid and will seek from the end of the file.
This option may be repeated; each skip is applied in order (offsets add).";

const BLOCK_SIZE_HELP_TEXT: &str = "Sets the size of the `block` unit to SIZE.
Examples: --block-size=1024, --block-size=4kB";
Expand Down Expand Up @@ -80,8 +81,14 @@ struct Opt {
)]
length: Option<String>,

#[arg(help(SKIP_HELP_TEXT), short, long, value_name("N"))]
skip: Option<String>,
#[arg(
help(SKIP_HELP_TEXT),
short,
long,
value_name("N"),
action(ArgAction::Append)
)]
skip: Vec<String>,

#[arg(
help(BLOCK_SIZE_HELP_TEXT),
Expand Down Expand Up @@ -319,20 +326,14 @@ fn run() -> Result<()> {
PositiveI64::new(x).ok_or_else(|| anyhow!("block size argument must be positive"))
})?;

let skip_arg = opt
.skip
.as_ref()
.map(|s| {
parse_byte_offset(s, block_size).context(anyhow!(
"failed to parse `--skip` arg {:?} as byte count",
s
))
})
.transpose()?;

let skip_offset = if let Some(ByteOffset { kind, value }) = skip_arg {
let mut skip_offset = 0;
for s in &opt.skip {
let ByteOffset { kind, value } = parse_byte_offset(s, block_size).context(anyhow!(
"failed to parse `--skip` arg {:?} as byte count",
s
))?;
let value = value.into_inner();
reader
skip_offset = reader
.seek(match kind {
ByteOffsetKind::ForwardFromBeginning | ByteOffsetKind::ForwardFromLastOffset => {
SeekFrom::Current(value)
Expand All @@ -345,10 +346,8 @@ fn run() -> Result<()> {
This could be caused by a negative offset that is too large or by \
an input that is not seek-able (e.g. if the input comes from a pipe)."
)
})?
} else {
0
};
})?;
}

let parse_byte_count = |s| -> Result<u64> {
Ok(parse_byte_offset(s, block_size)?
Expand Down
17 changes: 17 additions & 0 deletions tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,23 @@ mod skip {
);
}

#[test]
fn multiple_skips_are_additive() {
hexyl()
.arg("ascii")
.arg("--color=never")
.arg("--skip=2")
.arg("--skip=2")
.arg("--length=4")
.assert()
.success()
.stdout(
"┌────────┬─────────────────────────┬─────────────────────────┬────────┬────────┐\n\
│00000004│ 34 35 36 37 ┊ │4567 ┊ │\n\
└────────┴─────────────────────────┴─────────────────────────┴────────┴────────┘\n",
);
}

#[test]
fn prints_warning_when_skipping_past_the_end() {
hexyl()
Expand Down
Loading