Refactor command.rs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Peter · committed by David Peter · parent bf4d78d · Browse files · 1 file·+128 added−120 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+128 added−120 removed
- other:+128 added−120 removed
Provenance
- Commit
833529f- Tree
9624ed1- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
bf4d78d
1 file changed+128 added−120 removed
modified:src/command.rs+128 added-120 removed
93 unmodified lines94 result95 }96 }97 98-/// Finds all the strings that appear multiple times in the input iterator, returning them in99-/// sorted order. If no string appears more than once, the result is an empty vector.100-fn find_duplicates<'a, I: IntoIterator<Item = &'a str>>(i: I) -> Vec<&'a str> {101- let mut counts = BTreeMap::<&'a str, usize>::new();102- for s in i {103- *counts.entry(s).or_default() += 1;104- }105- counts106- .into_iter()107- .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })108- .collect()109-}110-111-fn build_parameterized_commands<'a, T: Numeric>(112- param_min: T,113- param_max: T,114- step: T,115- command_names: Vec<&'a str>,116- command_strings: Vec<&'a str>,117- param_name: &'a str,118-) -> Result<Vec<Command<'a>>, ParameterScanError> {119- let param_range = RangeStep::new(param_min, param_max, step)?;120- let param_count = param_range.size_hint().1.unwrap();121- let command_name_count = command_names.len();122-123- // `--command-name` should appear exactly once or exactly B times,124- // where B is the total number of benchmarks.125- if command_name_count > 1 && command_name_count != param_count {126- return Err(ParameterScanError::UnexpectedCommandNameCount(127- command_name_count,128- param_count,129- ));130- }131-132- let mut i = 0;133- let mut commands = vec![];134- for value in param_range {135- for cmd in &command_strings {136- let name = command_names137- .get(i)138- .or_else(|| command_names.get(0))139- .copied();140- commands.push(Command::new_parametrized(141- name,142- cmd,143- vec![(param_name, ParameterValue::Numeric(value.into()))],144- ));145- i += 1;146- }147- }148- Ok(commands)149-}150-151-fn get_parameterized_commands<'a>(152- command_names: Option<Values<'a>>,153- command_strings: Values<'a>,154- mut vals: clap::Values<'a>,155- step: Option<&str>,156-) -> Result<Vec<Command<'a>>, ParameterScanError> {157- let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());158- let command_strings = command_strings.collect::<Vec<&str>>();159- let param_name = vals.next().unwrap();160- let param_min = vals.next().unwrap();161- let param_max = vals.next().unwrap();162-163- // attempt to parse as integers164- if let (Ok(param_min), Ok(param_max), Ok(step)) = (165- param_min.parse::<i32>(),166- param_max.parse::<i32>(),167- step.unwrap_or("1").parse::<i32>(),168- ) {169- return build_parameterized_commands(170- param_min,171- param_max,172- step,173- command_names,174- command_strings,175- param_name,176- );177- }178-179- // try parsing them as decimals180- let param_min = Decimal::from_str(param_min)?;181- let param_max = Decimal::from_str(param_max)?;182-183- if step.is_none() {184- return Err(ParameterScanError::StepRequired);185- }186-187- let step = Decimal::from_str(step.unwrap())?;188- build_parameterized_commands(189- param_min,190- param_max,191- step,192- command_names,193- command_strings,194- param_name,195- )196-}197-98+/// A collection of commands that should be benchmarked99 pub struct Commands<'a>(Vec<Command<'a>>);100 101 impl<'a> Commands<'a> {102 pub fn from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands> {1 unmodified line104 let command_strings = matches.values_of("command").unwrap();105 106 if let Some(args) = matches.values_of("parameter-scan") {107 let step_size = matches.value_of("parameter-step-size");207- Ok(Self(get_parameterized_commands(108+ Ok(Self(Self::get_parameter_scan_commands(109 command_names,110 command_strings,111 args,112 step_size,11 unmodified lines124 })125 .collect();126 {127 let duplicates =227- find_duplicates(param_names_and_values.iter().map(|(name, _)| *name));128+ Self::find_duplicates(param_names_and_values.iter().map(|(name, _)| *name));129 if !duplicates.is_empty() {130 bail!("Duplicate parameter names: {}", &duplicates.join(", "));131 }132 }78 unmodified lines211 212 pub fn len(&self) -> usize {213 self.0.len()214 }215+216+ /// Finds all the strings that appear multiple times in the input iterator, returning them in217+ /// sorted order. If no string appears more than once, the result is an empty vector.218+ fn find_duplicates<'b, I: IntoIterator<Item = &'b str>>(i: I) -> Vec<&'b str> {219+ let mut counts = BTreeMap::<&'b str, usize>::new();220+ for s in i {221+ *counts.entry(s).or_default() += 1;222+ }223+ counts224+ .into_iter()225+ .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })226+ .collect()227+ }228+229+ fn build_parameter_scan_commands<'b, T: Numeric>(230+ param_name: &'b str,231+ param_min: T,232+ param_max: T,233+ step: T,234+ command_names: Vec<&'b str>,235+ command_strings: Vec<&'b str>,236+ ) -> Result<Vec<Command<'b>>, ParameterScanError> {237+ let param_range = RangeStep::new(param_min, param_max, step)?;238+ let param_count = param_range.size_hint().1.unwrap();239+ let command_name_count = command_names.len();240+241+ // `--command-name` should appear exactly once or exactly B times,242+ // where B is the total number of benchmarks.243+ if command_name_count > 1 && command_name_count != param_count {244+ return Err(ParameterScanError::UnexpectedCommandNameCount(245+ command_name_count,246+ param_count,247+ ));248+ }249+250+ let mut i = 0;251+ let mut commands = vec![];252+ for value in param_range {253+ for cmd in &command_strings {254+ let name = command_names255+ .get(i)256+ .or_else(|| command_names.get(0))257+ .copied();258+ commands.push(Command::new_parametrized(259+ name,260+ cmd,261+ vec![(param_name, ParameterValue::Numeric(value.into()))],262+ ));263+ i += 1;264+ }265+ }266+ Ok(commands)267+ }268+269+ fn get_parameter_scan_commands<'b>(270+ command_names: Option<Values<'b>>,271+ command_strings: Values<'b>,272+ mut vals: clap::Values<'b>,273+ step: Option<&str>,274+ ) -> Result<Vec<Command<'b>>, ParameterScanError> {275+ let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());276+ let command_strings = command_strings.collect::<Vec<&str>>();277+ let param_name = vals.next().unwrap();278+ let param_min = vals.next().unwrap();279+ let param_max = vals.next().unwrap();280+281+ // attempt to parse as integers282+ if let (Ok(param_min), Ok(param_max), Ok(step)) = (283+ param_min.parse::<i32>(),284+ param_max.parse::<i32>(),285+ step.unwrap_or("1").parse::<i32>(),286+ ) {287+ return Self::build_parameter_scan_commands(288+ param_name,289+ param_min,290+ param_max,291+ step,292+ command_names,293+ command_strings,294+ );295+ }296+297+ // try parsing them as decimals298+ let param_min = Decimal::from_str(param_min)?;299+ let param_max = Decimal::from_str(param_max)?;300+301+ if step.is_none() {302+ return Err(ParameterScanError::StepRequired);303+ }304+305+ let step = Decimal::from_str(step.unwrap())?;306+ Self::build_parameter_scan_commands(307+ param_name,308+ param_min,309+ param_max,310+ step,311+ command_names,312+ command_strings,313+ )314+ }315 }316 317 #[test]318 fn test_get_shell_command_nonoverlapping() {86 unmodified lines405 assert_eq!(commands[1].get_shell_command(), "echo 2");406 }407 408 #[test]408-fn test_build_parameter_range_commands() {409+fn test_build_parameter_scan_commands() {410 use crate::app::get_cli_arguments;411 let matches = get_cli_arguments(vec![412 "hyperfine",413 "echo {val}",14 unmodified lines428 assert_eq!(commands[1].get_shell_command(), "echo 2");429 }430 431 #[test]431-fn test_get_parameterized_commands_int() {432- let commands =433- build_parameterized_commands(1i32, 7i32, 3i32, vec![], vec!["echo {val}"], "val").unwrap();432+fn test_parameter_scan_commands_int() {433+ let commands = Commands::build_parameter_scan_commands(434+ "val",435+ 1i32,436+ 7i32,437+ 3i32,438+ vec![],439+ vec!["echo {val}"],440+ )441+ .unwrap();442 assert_eq!(commands.len(), 3);443 assert_eq!(commands[2].get_name(), "echo 7");444 assert_eq!(commands[2].get_shell_command(), "echo 7");445 }446 447 #[test]440-fn test_get_parameterized_commands_decimal() {448+fn test_parameter_scan_commands_decimal() {449 let param_min = Decimal::from_str("0").unwrap();450 let param_max = Decimal::from_str("1").unwrap();451 let step = Decimal::from_str("0.33").unwrap();452 445- let commands = build_parameterized_commands(453+ let commands = Commands::build_parameter_scan_commands(454+ "val",455 param_min,456 param_max,457 step,458 vec![],459 vec!["echo {val}"],451- "val",460 )461 .unwrap();462 assert_eq!(commands.len(), 4);463 assert_eq!(commands[3].get_name(), "echo 0.99");464 assert_eq!(commands[3].get_shell_command(), "echo 0.99");465 }466 467 #[test]460-fn test_get_parameterized_command_names() {461- let commands = build_parameterized_commands(468+fn test_parameterr_scan_commands_names() {469+ let commands = Commands::build_parameter_scan_commands(470+ "val",471 1i32,472 3i32,473 1i32,474 vec!["name-{val}"],475 vec!["echo {val}"],467- "val",476 )477 .unwrap();478 assert_eq!(commands.len(), 3);479 let command_names = commands4 unmodified lines484 }485 486 #[test]487 fn test_get_specified_command_names() {480- let commands = build_parameterized_commands(488+ let commands = Commands::build_parameter_scan_commands(489+ "val",490 1i32,491 3i32,492 1i32,493 vec!["name-a", "name-b", "name-c"],494 vec!["echo {val}"],486- "val",495 )496 .unwrap();497 assert_eq!(commands.len(), 3);498 let command_names = commands4 unmodified lines503 }504 505 #[test]506 fn test_different_command_name_count_with_parameters() {499- let result = build_parameterized_commands(507+ let result = Commands::build_parameter_scan_commands(508+ "val",509 1i32,510 3i32,511 1i32,512 vec!["name-1", "name-2"],513 vec!["echo {val}"],505- "val",514 );507- assert_eq!(508- format!("{}", result.unwrap_err()),509- "'--command-name' has been specified 2 times. It has to appear exactly once, or exactly 3 times (number of benchmarks)"510- );515+ assert!(matches!(516+ result.unwrap_err(),517+ ParameterScanError::UnexpectedCommandNameCount(2, 3)518+ ));519 }