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
Provenance
- Commit
d4a0e9a- Tree
19f41bb- Author
Steven Gu <asongala@163.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
538dd06
4 files changed+136 added−33 removed
modified:src/hyperfine/error.rs+16 added
10 unmodified lines11 EmptyRange,12 TooLarge,13 ZeroStep,14 StepRequired,15+ DifferentCommandNameCountWithParameters(usize, usize),16 }17 18 impl From<num::ParseIntError> for ParameterScanError {19 fn from(e: num::ParseIntError) -> ParameterScanError {20 unmodified lines40 "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 lines58 pub enum OptionsError<'a> {59 RunsBelowTwo,60 EmptyRunsRange,61 TooManyCommandNames(usize),62+ DifferentCommandNameCountWithParameters(usize, usize),63 NumericParsingError(&'a str, ParseIntError),64 }65 66 impl<'a> fmt::Display for OptionsError<'a> {3 unmodified lines70 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 linesmodified:src/hyperfine/parameter_range.rs+90 added-26 removed
1 use crate::hyperfine::error::ParameterScanError;2 use crate::hyperfine::types::{Command, NumericType, ParameterValue};3 use clap::Values;4 use rust_decimal::Decimal;5+use std::convert::TryInto;6 use std::ops::{Add, AddAssign, Div, Sub};7 use std::str::FromStr;8 9 trait Numeric:35 unmodified lines45 end,46 step,47 }48 }49+50+ fn validate(&self) -> Result<(), ParameterScanError> {51+ if self.end < self.state {52+ return Err(ParameterScanError::EmptyRange);53+ }54+55+ if self.step == T::from(0) {56+ return Err(ParameterScanError::ZeroStep);57+ }58+59+ 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 }66 67 impl<T: Numeric> Iterator for RangeStep<T> {68 type Item = T;6 unmodified lines75 self.state += self.step;76 77 Some(return_val)78 }62-}79 64-fn 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+ }84 69- 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 }72-73- 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- }78-79- Ok(())91 }92 93 fn build_parameterized_commands<'a, T: Numeric>(94 param_min: T,2 unmodified lines97 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();105 106+ // `--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+ }113+114 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;105-118+ 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 lines199 assert_eq!(param_range[10], Decimal::from(1));200 }201 202 #[test]203+fn test_range_step_validate() {204+ let range_step = RangeStep::new(0, 10, 3);205+ assert!(range_step.validate().is_ok());206+207+ 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());213+214+ let range_step = RangeStep::new(11, 10, 1);215+ assert_eq!(216+ format!("{}", range_step.validate().unwrap_err()),217+ "Empty parameter range"218+ );219+220+ 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+ );225+226+ 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+}232+233+#[test]234 fn 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 lines295 .map(|c| c.get_name())296 .collect::<Vec<String>>();297 assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);298 }299+300+#[test]301+fn 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
1+use rust_decimal::prelude::ToPrimitive;2 use rust_decimal::Decimal;3 /// This module contains common internal types.4 use serde::*;5 use std::collections::BTreeMap;6+use std::convert::TryFrom;7 use std::fmt;8 9 use crate::hyperfine::units::{Second, Unit};10 30 unmodified lines41 NumericType::Decimal(self)42 }43 }44 45+impl TryFrom<NumericType> for usize {46+ type Error = ();47+48+ 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+}58+59 #[derive(Debug, Clone, PartialEq, Eq)]60 pub enum ParameterValue {61 Text(String),62 Numeric(NumericType),293 unmodified linesmodified:src/main.rs+14 added-7 removed
253 unmodified lines254 if param_space_size == 0 {255 return Vec::new();256 }257 258+ // `--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+ }267+268 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;277 278 let (command_index, params_indices) = index.split_first().unwrap();279 let parameters = param_names_and_values128 unmodified lines