Skip to content

Commit

Permalink
added sum-flag
Browse files Browse the repository at this point in the history
  • Loading branch information
Phydon committed May 7, 2024
1 parent aed3e77 commit 78d9a6f
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ fn main() {
let chars_flag = matches.get_flag("chars");
let lines_flag = matches.get_flag("lines");
let show_errors_flag = matches.get_flag("show-errors");
let sum_flag = matches.get_flag("sum");
let word_flag = matches.get_flag("words");

if let Some(_) = matches.subcommand_matches("log") {
Expand Down Expand Up @@ -129,6 +130,8 @@ fn main() {
count += count_chars(content);
} else if bytes_flag {
count += count_bytes(content);
} else if sum_flag {
count += sum(content);
} else {
// count words by default
count += count_words(content);
Expand Down Expand Up @@ -170,6 +173,16 @@ fn count_bytes(content: String) -> usize {
content.par_bytes().count()
}

fn sum(content: String) -> usize {
content
.par_split_whitespace()
.filter_map(|x| match x.parse::<usize>() {
Ok(n) => Some(n),
_ => None,
})
.sum()
}

fn read_stdin() -> String {
let mut input = io::stdin()
.lock()
Expand Down Expand Up @@ -199,11 +212,15 @@ fn countx() -> Command {
"Leann Phydon <[email protected]>".italic().dimmed()
))
// TODO update version
.version("1.2.2")
.version("1.2.3")
.author("Leann Phydon <[email protected]>")
.arg(
Arg::new("arg")
.help("The filepath to work with")
.long_help(format!(
"{}\n{}",
"The filepath to work with", "Reads stdin if left empty"
))
.action(ArgAction::Set)
.num_args(1)
.value_name("PATH"),
Expand Down Expand Up @@ -240,6 +257,13 @@ fn countx() -> Command {
.help("Show errors (ignores errors by default)")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("sum")
.short('s')
.long("sum")
.help("Sum up all integers")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("words")
.short('w')
Expand Down Expand Up @@ -289,6 +313,14 @@ $ echo 'Some pipe input' | cx
3
"###
);

println!("\n{}\n----------", "Example 3".bold());
println!(
r###"
$ echo 'This 42 is 1337 a t35t 666' | cx --sum
2045
"###
);
}

fn check_create_config_dir() -> io::Result<PathBuf> {
Expand Down Expand Up @@ -365,6 +397,14 @@ mod tests {
assert_eq!(result, expected);
}

#[test]
fn sum_test() {
let input = "This 42 is 1337 a t35t 666".to_string();
let result = sum(input);
let expected = 2045;
assert_eq!(result, expected);
}

#[test]
fn count_words_empty_test() {
let input = "".to_string();
Expand Down Expand Up @@ -396,4 +436,12 @@ mod tests {
let expected = 0;
assert_eq!(result, expected);
}

#[test]
fn sum_empty_test() {
let input = "".to_string();
let result = sum(input);
let expected = 0;
assert_eq!(result, expected);
}
}

0 comments on commit 78d9a6f

Please sign in to comment.