Skip to content

Commit

Permalink
Merge pull request #1411 from jqnatividad/count-optimize-width
Browse files Browse the repository at this point in the history
`count`: optimize `--width` option
  • Loading branch information
jqnatividad authored Nov 11, 2023
2 parents d76a569 + 9a11a84 commit b1e2b05
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
18 changes: 14 additions & 4 deletions src/cmd/count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,27 @@ fn count_input(
let mut rdr = conf.reader()?;
let mut count = 0_u64;
let mut max_width = 0_usize;
let mut record_numfields = 0_usize;
let mut record_numdelimiters = 0_usize;
let mut record = csv::ByteRecord::new();

if compute_width {
let mut curr_width;

// read the first record to get the number of delimiters
// and the width of the first record
rdr.read_byte_record(&mut record)?;
max_width = record.as_slice().len();
count = 1;

// number of delimiters is number of fields minus 1
// we subtract 1 because the last field doesn't have a delimiter
record_numdelimiters = record.len().saturating_sub(1);

while rdr.read_byte_record(&mut record)? {
count += 1;

curr_width = record.as_slice().len();
if curr_width > max_width {
record_numfields = record.len();
max_width = curr_width;
}
}
Expand All @@ -111,7 +121,7 @@ fn count_input(
count += 1;
}
}
// record_numfields is a count of the delimiters
// record_numdelimiters is a count of the delimiters
// which we also want to count when returning width
Ok((count, max_width + record_numfields))
Ok((count, max_width + record_numdelimiters))
}
10 changes: 6 additions & 4 deletions tests/test_count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,18 @@ fn count_width() {
wrk.create_indexed(
"in.csv",
vec![
svec!["letter", "number"],
svec!["alpha", "13"],
svec!["beta", "24"],
svec!["letter", "number", "flag"],
svec!["alphabetic", "13", "true"],
svec!["beta", "24", "false"],
svec!["gamma", "37.1", "true"],
svec!("delta", "42.5", "false"),
],
);
let mut cmd = wrk.command("count");
cmd.arg("--width").arg("in.csv");

let got: String = wrk.stdout(&mut cmd);
let expected = "2;9";
let expected = "4;18";
assert_eq!(got, expected.to_string());
}

Expand Down

0 comments on commit b1e2b05

Please sign in to comment.