Skip to content

Commit

Permalink
Merge pull request #1726 from jqnatividad/slice-negative_index
Browse files Browse the repository at this point in the history
`slice`: support negative `--index` option values
  • Loading branch information
jqnatividad authored Apr 5, 2024
2 parents e991faf + bd4e993 commit 51a483c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
16 changes: 14 additions & 2 deletions src/cmd/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ slice options:
-l, --len <arg> The length of the slice (can be used instead
of --end).
-i, --index <arg> Slice a single record (shortcut for -s N -l 1).
If negative, starts from the last record.
Common options:
-h, --help Display this message
Expand Down Expand Up @@ -51,7 +52,7 @@ struct Args {
flag_start: Option<isize>,
flag_end: Option<usize>,
flag_len: Option<usize>,
flag_index: Option<usize>,
flag_index: Option<isize>,
flag_output: Option<String>,
flag_no_headers: bool,
flag_delimiter: Option<Delimiter>,
Expand Down Expand Up @@ -105,7 +106,18 @@ impl Args {
start = Some(start_arg as usize);
}
}
util::range(start, self.flag_end, self.flag_len, self.flag_index)
let index = if let Some(flag_index) = self.flag_index {
if flag_index < 0 {
let index = (util::count_rows(&self.rconfig()).unwrap() as usize)
.abs_diff(flag_index.unsigned_abs());
Some(index)
} else {
Some(flag_index as usize)
}
} else {
None
};
util::range(start, self.flag_end, self.flag_len, index)
}

fn rconfig(&self) -> Config {
Expand Down
19 changes: 18 additions & 1 deletion tests/test_slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ fn test_slice(
assert_eq!(got, expected);
}

fn test_index(name: &str, idx: usize, expected: &str, headers: bool, use_index: bool) {
fn test_index(name: &str, idx: isize, expected: &str, headers: bool, use_index: bool) {
let (wrk, mut cmd) = setup(name, headers, use_index);
cmd.arg("--index").arg(&idx.to_string());
if !headers {
Expand Down Expand Up @@ -186,3 +186,20 @@ fn slice_index_withindex() {
fn slice_index_no_headers_withindex() {
test_index("slice_index_no_headers_withindex", 1, "b", false, true);
}

#[test]
fn slice_neg_index() {
test_index("slice_neg_index", -1, "e", true, false);
}
#[test]
fn slice_neg_index_no_headers() {
test_index("slice_neg_index_no_headers", -1, "e", false, false);
}
#[test]
fn slice_neg_index_withindex() {
test_index("slice_neg_index_withindex", -2, "d", true, true);
}
#[test]
fn slice_neg_index_no_headers_withindex() {
test_index("slice_neg_index_no_headers_withindex", -2, "d", false, true);
}

0 comments on commit 51a483c

Please sign in to comment.