Skip to content
Myr

Fixes to limit `--command-name` count appear exactly once or same count with parameters.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Steven Gu · committed by David Peter · parent 538dd06 · Browse files · 4 files+136 added−33 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+136 added−33 removed

  • other:+136 added−33 removed

4 files+136 added−33 removed

modified:src/hyperfine/error.rs+16 added
10 unmodified lines
11 EmptyRange,12 TooLarge,13 ZeroStep,14 StepRequired,15 DifferentCommandNameCountWithParameters(usize, usize),16}1718impl From<num::ParseIntError> for ParameterScanError {19 fn from(e: num::ParseIntError) -> ParameterScanError {
20 unmodified lines
40 "A step size is required when the range bounds are \41 floating point numbers. The step size can be specified \42 with the '--parameter-step-size' parameter"43 ),44 ParameterScanError::DifferentCommandNameCountWithParameters(real, expected) => {45 write!(46 f,47 "Current --command-name count is {}: expected {} as parameters",48 real, expected49 )50 }51 }52 }53}54
3 unmodified lines
58pub enum OptionsError<'a> {59 RunsBelowTwo,60 EmptyRunsRange,61 TooManyCommandNames(usize),62 DifferentCommandNameCountWithParameters(usize, usize),63 NumericParsingError(&'a str, ParseIntError),64}6566impl<'a> fmt::Display for OptionsError<'a> {
3 unmodified lines
70 OptionsError::RunsBelowTwo => write!(f, "Number of runs below two"),71 OptionsError::TooManyCommandNames(n) => {72 write!(f, "Too many --command-name options: expected {} at most", n)73 }74 OptionsError::DifferentCommandNameCountWithParameters(real, expected) => {75 write!(76 f,77 "Current --command-name count is {}: expected {} as parameters",78 real, expected79 )80 }81 OptionsError::NumericParsingError(cmd, ref err) => write!(82 f,83 "Could not read numeric argument to '--{cmd}': {err}",84 cmd = cmd,
7 unmodified lines
modified:src/hyperfine/parameter_range.rs+90 added-26 removed
1use crate::hyperfine::error::ParameterScanError;2use crate::hyperfine::types::{Command, NumericType, ParameterValue};3use clap::Values;4use rust_decimal::Decimal;5use std::convert::TryInto;6use std::ops::{Add, AddAssign, Div, Sub};7use std::str::FromStr;89trait Numeric:
35 unmodified lines
45 end,46 step,47 }48 }4950 fn validate(&self) -> Result<(), ParameterScanError> {51 if self.end < self.state {52 return Err(ParameterScanError::EmptyRange);53 }5455 if self.step == T::from(0) {56 return Err(ParameterScanError::ZeroStep);57 }5859 const MAX_PARAMETERS: usize = 100_000;60 match self.size_hint() {61 (_, Some(size)) if size <= MAX_PARAMETERS => Ok(()),62 _ => Err(ParameterScanError::TooLarge),63 }64 }65}6667impl<T: Numeric> Iterator for RangeStep<T> {68 type Item = T;
6 unmodified lines
75 self.state += self.step;7677 Some(return_val)78 }62}7964fn validate_params<T: Numeric>(start: T, end: T, step: T) -> Result<(), ParameterScanError> {65 if end < start {66 return Err(ParameterScanError::EmptyRange);67 }80 fn size_hint(&self) -> (usize, Option<usize>) {81 if self.step == T::from(0) {82 return (usize::MAX, None);83 }8469 if step == T::from(0) {70 return Err(ParameterScanError::ZeroStep);85 let steps = (self.end - self.state + T::from(1)) / self.step;86 steps87 .into()88 .try_into()89 .map_or((usize::MAX, None), |u| (u, Some(u)))90 }7273 const MAX_PARAMETERS: i32 = 100_000;74 let steps = (end - start + T::from(1)) / step;75 if steps > T::from(MAX_PARAMETERS) {76 return Err(ParameterScanError::TooLarge);77 }7879 Ok(())91}9293fn build_parameterized_commands<'a, T: Numeric>(94 param_min: T,
2 unmodified lines
97 command_names: Vec<&'a str>,98 command_strings: Vec<&'a str>,99 param_name: &'a str,100) -> Result<Vec<Command<'a>>, ParameterScanError> {90 validate_params(param_min, param_max, step)?;101 let param_range = RangeStep::new(param_min, param_max, step);92 let mut commands = vec![];102 param_range.validate()?;103 let param_count = param_range.size_hint().1.unwrap();104 let command_name_count = command_names.len();105106 // `--command-name` should appear exactly once or same count with parameters.107 if command_name_count > 1 && command_name_count != param_count {108 return Err(ParameterScanError::DifferentCommandNameCountWithParameters(109 command_name_count,110 param_count,111 ));112 }113114 let mut i = 0;95 let name_count = command_names.len();115 let mut commands = vec![];116 for value in param_range {117 for cmd in &command_strings {98 // Sets the command name by index (remainder) if exists.99 let name = if name_count > 0 {100 Some(command_names[i % name_count])101 } else {102 None103 };104 i += 1;105118 let name = command_names119 .get(i)120 .or_else(|| command_names.get(0))121 .map(|s| *s);122 commands.push(Command::new_parametrized(123 name,124 cmd,125 vec![(param_name, ParameterValue::Numeric(value.into()))],126 ));127 i += 1;128 }129 }130 Ok(commands)131}
67 unmodified lines
199 assert_eq!(param_range[10], Decimal::from(1));200}201202#[test]203fn test_range_step_validate() {204 let range_step = RangeStep::new(0, 10, 3);205 assert!(range_step.validate().is_ok());206207 let range_step = RangeStep::new(208 Decimal::from(0),209 Decimal::from(1),210 Decimal::from_str("0.1").unwrap(),211 );212 assert!(range_step.validate().is_ok());213214 let range_step = RangeStep::new(11, 10, 1);215 assert_eq!(216 format!("{}", range_step.validate().unwrap_err()),217 "Empty parameter range"218 );219220 let range_step = RangeStep::new(0, 10, 0);221 assert_eq!(222 format!("{}", range_step.validate().unwrap_err()),223 "Zero is not a valid parameter step"224 );225226 let range_step = RangeStep::new(0, 100_001, 1);227 assert_eq!(228 format!("{}", range_step.validate().unwrap_err()),229 "Parameter range is too large"230 );231}232233#[test]234fn test_get_parameterized_commands_int() {235 let commands =236 build_parameterized_commands(1i32, 7i32, 3i32, vec![], vec!["echo {val}"], "val").unwrap();237 assert_eq!(commands.len(), 3);
57 unmodified lines
295 .map(|c| c.get_name())296 .collect::<Vec<String>>();297 assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);298}299300#[test]301fn test_different_command_name_count_with_parameters() {302 let result = build_parameterized_commands(303 1i32,304 3i32,305 1i32,306 vec!["name-1", "name-2"],307 vec!["echo {val}"],308 "val",309 );310 assert_eq!(311 format!("{}", result.unwrap_err()),312 "Current --command-name count is 2: expected 3 as parameters"313 );314}
modified:src/hyperfine/types.rs+16 added
1use rust_decimal::prelude::ToPrimitive;2use rust_decimal::Decimal;3/// This module contains common internal types.4use serde::*;5use std::collections::BTreeMap;6use std::convert::TryFrom;7use std::fmt;89use crate::hyperfine::units::{Second, Unit};10
30 unmodified lines
41 NumericType::Decimal(self)42 }43}4445impl TryFrom<NumericType> for usize {46 type Error = ();4748 fn try_from(numeric: NumericType) -> Result<Self, Self::Error> {49 match numeric {50 NumericType::Int(i) => usize::try_from(i).map_err(|_| ()),51 NumericType::Decimal(d) => match d.to_u64() {52 Some(u) => usize::try_from(u).map_err(|_| ()),53 None => Err(()),54 },55 }56 }57}5859#[derive(Debug, Clone, PartialEq, Eq)]60pub enum ParameterValue {61 Text(String),62 Numeric(NumericType),
293 unmodified lines
modified:src/main.rs+14 added-7 removed
253 unmodified lines
254 if param_space_size == 0 {255 return Vec::new();256 }257258 // `--command-name` should appear exactly once or same count with parameters.259 let command_name_count = command_names.len();260 if command_name_count > 1 && command_name_count != param_space_size {261 let err = OptionsError::DifferentCommandNameCountWithParameters(262 command_name_count,263 param_space_size,264 );265 error(&err.to_string());266 }267268 let mut i = 0;259 let name_count = command_names.len();269 let mut commands = Vec::with_capacity(param_space_size);270 let mut index = vec![0usize; dimensions.len()];271 'outer: loop {263 // Sets the command name by index (remainder) if exists.264 let name = if name_count > 0 {265 Some(command_names[i % name_count])266 } else {267 None268 };272 let name = command_names273 .get(i)274 .or_else(|| command_names.get(0))275 .map(|s| *s);276 i += 1;277278 let (command_index, params_indices) = index.split_first().unwrap();279 let parameters = param_names_and_values
128 unmodified lines