New parameter module
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 865290a · Browse files · 10 files·+460 added−457 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+460 added−457 removed
- other:+460 added−457 removed
Provenance
- Commit
47091a5- Tree
ac2aa23- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
865290a
10 files changed+460 added−457 removed
added:src/parameter/mod.rs+19 added
1+use crate::numeric::NumericType;2+3+pub mod range;4+pub mod tokenize;5+6+#[derive(Debug, Clone, PartialEq, Eq)]7+pub enum ParameterValue {8+ Text(String),9+ Numeric(NumericType),10+}11+12+impl<'a> ToString for ParameterValue {13+ fn to_string(&self) -> String {14+ match self {15+ ParameterValue::Text(ref value) => value.clone(),16+ ParameterValue::Numeric(value) => value.to_string(),17+ }18+ }19+}added:src/parameter/range.rs+318 added
1+use std::convert::TryInto;2+use std::ops::{Add, AddAssign, Div, Sub};3+use std::str::FromStr;4+5+use clap::Values;6+use rust_decimal::Decimal;7+8+use super::ParameterValue;9+use crate::command::Command;10+use crate::error::ParameterScanError;11+use crate::numeric::NumericType;12+13+trait Numeric:14+ Add<Output = Self>15+ + Sub<Output = Self>16+ + Div<Output = Self>17+ + AddAssign18+ + PartialOrd19+ + Copy20+ + Clone21+ + From<i32>22+ + Into<NumericType>23+{24+}25+impl<26+ T: Add<Output = Self>27+ + Sub<Output = Self>28+ + Div<Output = Self>29+ + AddAssign30+ + PartialOrd31+ + Copy32+ + Clone33+ + From<i32>34+ + Into<NumericType>,35+ > Numeric for T36+{37+}38+39+#[derive(Debug)]40+struct RangeStep<T> {41+ state: T,42+ end: T,43+ step: T,44+}45+46+impl<T: Numeric> RangeStep<T> {47+ fn new(start: T, end: T, step: T) -> Result<Self, ParameterScanError> {48+ if end < start {49+ return Err(ParameterScanError::EmptyRange);50+ }51+52+ if step == T::from(0) {53+ return Err(ParameterScanError::ZeroStep);54+ }55+56+ const MAX_PARAMETERS: usize = 100_000;57+ match range_step_size_hint(start, end, step) {58+ (_, Some(size)) if size <= MAX_PARAMETERS => Ok(Self {59+ state: start,60+ end,61+ step,62+ }),63+ _ => Err(ParameterScanError::TooLarge),64+ }65+ }66+}67+68+impl<T: Numeric> Iterator for RangeStep<T> {69+ type Item = T;70+71+ fn next(&mut self) -> Option<Self::Item> {72+ if self.state > self.end {73+ return None;74+ }75+ let return_val = self.state;76+ self.state += self.step;77+78+ Some(return_val)79+ }80+81+ fn size_hint(&self) -> (usize, Option<usize>) {82+ range_step_size_hint(self.state, self.end, self.step)83+ }84+}85+86+fn range_step_size_hint<T: Numeric>(start: T, end: T, step: T) -> (usize, Option<usize>) {87+ if step == T::from(0) {88+ return (usize::MAX, None);89+ }90+91+ let steps = (end - start + T::from(1)) / step;92+ steps93+ .into()94+ .try_into()95+ .map_or((usize::MAX, None), |u| (u, Some(u)))96+}97+98+fn build_parameterized_commands<'a, T: Numeric>(99+ param_min: T,100+ param_max: T,101+ step: T,102+ command_names: Vec<&'a str>,103+ command_strings: Vec<&'a str>,104+ param_name: &'a str,105+) -> Result<Vec<Command<'a>>, ParameterScanError> {106+ let param_range = RangeStep::new(param_min, param_max, step)?;107+ let param_count = param_range.size_hint().1.unwrap();108+ let command_name_count = command_names.len();109+110+ // `--command-name` should appear exactly once or exactly B times,111+ // where B is the total number of benchmarks.112+ if command_name_count > 1 && command_name_count != param_count {113+ return Err(ParameterScanError::UnexpectedCommandNameCount(114+ command_name_count,115+ param_count,116+ ));117+ }118+119+ let mut i = 0;120+ let mut commands = vec![];121+ for value in param_range {122+ for cmd in &command_strings {123+ let name = command_names124+ .get(i)125+ .or_else(|| command_names.get(0))126+ .copied();127+ commands.push(Command::new_parametrized(128+ name,129+ cmd,130+ vec![(param_name, ParameterValue::Numeric(value.into()))],131+ ));132+ i += 1;133+ }134+ }135+ Ok(commands)136+}137+138+pub fn get_parameterized_commands<'a>(139+ command_names: Option<Values<'a>>,140+ command_strings: Values<'a>,141+ mut vals: clap::Values<'a>,142+ step: Option<&str>,143+) -> Result<Vec<Command<'a>>, ParameterScanError> {144+ let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());145+ let command_strings = command_strings.collect::<Vec<&str>>();146+ let param_name = vals.next().unwrap();147+ let param_min = vals.next().unwrap();148+ let param_max = vals.next().unwrap();149+150+ // attempt to parse as integers151+ if let (Ok(param_min), Ok(param_max), Ok(step)) = (152+ param_min.parse::<i32>(),153+ param_max.parse::<i32>(),154+ step.unwrap_or("1").parse::<i32>(),155+ ) {156+ return build_parameterized_commands(157+ param_min,158+ param_max,159+ step,160+ command_names,161+ command_strings,162+ param_name,163+ );164+ }165+166+ // try parsing them as decimals167+ let param_min = Decimal::from_str(param_min)?;168+ let param_max = Decimal::from_str(param_max)?;169+170+ if step.is_none() {171+ return Err(ParameterScanError::StepRequired);172+ }173+174+ let step = Decimal::from_str(step.unwrap())?;175+ build_parameterized_commands(176+ param_min,177+ param_max,178+ step,179+ command_names,180+ command_strings,181+ param_name,182+ )183+}184+185+#[test]186+fn test_integer_range() {187+ let param_range: Vec<i32> = RangeStep::new(0, 10, 3).unwrap().collect();188+189+ assert_eq!(param_range.len(), 4);190+ assert_eq!(param_range[0], 0);191+ assert_eq!(param_range[3], 9);192+}193+194+#[test]195+fn test_decimal_range() {196+ let param_min = Decimal::from(0);197+ let param_max = Decimal::from(1);198+ let step = Decimal::from_str("0.1").unwrap();199+200+ let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step)201+ .unwrap()202+ .collect();203+204+ assert_eq!(param_range.len(), 11);205+ assert_eq!(param_range[0], Decimal::from(0));206+ assert_eq!(param_range[10], Decimal::from(1));207+}208+209+#[test]210+fn test_range_step_validate() {211+ let result = RangeStep::new(0, 10, 3);212+ assert!(result.is_ok());213+214+ let result = RangeStep::new(215+ Decimal::from(0),216+ Decimal::from(1),217+ Decimal::from_str("0.1").unwrap(),218+ );219+ assert!(result.is_ok());220+221+ let result = RangeStep::new(11, 10, 1);222+ assert_eq!(format!("{}", result.unwrap_err()), "Empty parameter range");223+224+ let result = RangeStep::new(0, 10, 0);225+ assert_eq!(226+ format!("{}", result.unwrap_err()),227+ "Zero is not a valid parameter step"228+ );229+230+ let result = RangeStep::new(0, 100_001, 1);231+ assert_eq!(232+ format!("{}", result.unwrap_err()),233+ "Parameter range is too large"234+ );235+}236+237+#[test]238+fn test_get_parameterized_commands_int() {239+ let commands =240+ build_parameterized_commands(1i32, 7i32, 3i32, vec![], vec!["echo {val}"], "val").unwrap();241+ assert_eq!(commands.len(), 3);242+ assert_eq!(commands[2].get_name(), "echo 7");243+ assert_eq!(commands[2].get_shell_command(), "echo 7");244+}245+246+#[test]247+fn test_get_parameterized_commands_decimal() {248+ let param_min = Decimal::from_str("0").unwrap();249+ let param_max = Decimal::from_str("1").unwrap();250+ let step = Decimal::from_str("0.33").unwrap();251+252+ let commands = build_parameterized_commands(253+ param_min,254+ param_max,255+ step,256+ vec![],257+ vec!["echo {val}"],258+ "val",259+ )260+ .unwrap();261+ assert_eq!(commands.len(), 4);262+ assert_eq!(commands[3].get_name(), "echo 0.99");263+ assert_eq!(commands[3].get_shell_command(), "echo 0.99");264+}265+266+#[test]267+fn test_get_parameterized_command_names() {268+ let commands = build_parameterized_commands(269+ 1i32,270+ 3i32,271+ 1i32,272+ vec!["name-{val}"],273+ vec!["echo {val}"],274+ "val",275+ )276+ .unwrap();277+ assert_eq!(commands.len(), 3);278+ let command_names = commands279+ .iter()280+ .map(|c| c.get_name())281+ .collect::<Vec<String>>();282+ assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]);283+}284+285+#[test]286+fn test_get_specified_command_names() {287+ let commands = build_parameterized_commands(288+ 1i32,289+ 3i32,290+ 1i32,291+ vec!["name-a", "name-b", "name-c"],292+ vec!["echo {val}"],293+ "val",294+ )295+ .unwrap();296+ assert_eq!(commands.len(), 3);297+ let command_names = commands298+ .iter()299+ .map(|c| c.get_name())300+ .collect::<Vec<String>>();301+ assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);302+}303+304+#[test]305+fn test_different_command_name_count_with_parameters() {306+ let result = build_parameterized_commands(307+ 1i32,308+ 3i32,309+ 1i32,310+ vec!["name-1", "name-2"],311+ vec!["echo {val}"],312+ "val",313+ );314+ assert_eq!(315+ format!("{}", result.unwrap_err()),316+ "'--command-name' has been specified 2 times. It has to appear exactly once, or exactly 3 times (number of benchmarks)"317+ );318+}added:src/parameter/tokenize.rs+60 added
1+pub fn tokenize(values: &str) -> Vec<String> {2+ let mut tokens = vec![];3+ let mut buf = String::new();4+5+ let mut iter = values.chars();6+ while let Some(c) = iter.next() {7+ match c {8+ '\\' => match iter.next() {9+ Some(c2 @ ',') | Some(c2 @ '\\') => {10+ buf.push(c2);11+ }12+ Some(c2) => {13+ buf.push('\\');14+ buf.push(c2);15+ }16+ None => buf.push('\\'),17+ },18+ ',' => {19+ tokens.push(buf);20+ buf = String::new();21+ }22+ _ => {23+ buf.push(c);24+ }25+ };26+ }27+28+ tokens.push(buf);29+30+ tokens31+}32+33+#[test]34+fn test_tokenize_single_value() {35+ assert_eq!(tokenize(r""), vec![""]);36+ assert_eq!(tokenize(r"foo"), vec!["foo"]);37+ assert_eq!(tokenize(r" "), vec![" "]);38+ assert_eq!(tokenize(r"hello\, world!"), vec!["hello, world!"]);39+ assert_eq!(tokenize(r"\,"), vec![","]);40+ assert_eq!(tokenize(r"\,\,\,"), vec![",,,"]);41+ assert_eq!(tokenize(r"\n"), vec![r"\n"]);42+ assert_eq!(tokenize(r"\\"), vec![r"\"]);43+ assert_eq!(tokenize(r"\\\,"), vec![r"\,"]);44+}45+46+#[test]47+fn test_tokenize_multiple_values() {48+ assert_eq!(tokenize(r"foo,bar,baz"), vec!["foo", "bar", "baz"]);49+ assert_eq!(tokenize(r"hello world,foo"), vec!["hello world", "foo"]);50+51+ assert_eq!(tokenize(r"hello\,world!,baz"), vec!["hello,world!", "baz"]);52+}53+54+#[test]55+fn test_tokenize_empty_values() {56+ assert_eq!(tokenize(r"foo,,bar"), vec!["foo", "", "bar"]);57+ assert_eq!(tokenize(r",bar"), vec!["", "bar"]);58+ assert_eq!(tokenize(r"bar,"), vec!["bar", ""]);59+ assert_eq!(tokenize(r",,"), vec!["", "", ""]);60+}modified:src/command.rs+4 added-3 removed
1 use std::collections::BTreeMap;2 use std::fmt;3 4-use crate::{error::OptionsError, parameter_range::get_parameterized_commands};4+use crate::error::OptionsError;5+use crate::parameter::range::get_parameterized_commands;6 7 use clap::ArgMatches;8 8-use crate::tokenize::tokenize;9-use crate::types::ParameterValue;9+use crate::parameter::tokenize::tokenize;10+use crate::parameter::ParameterValue;11 12 use anyhow::{bail, Result};13 14 /// A command that should be benchmarked.310 unmodified linesmodified:src/error.rs+1 added-2 removed
1-use std::num;2-use std::num::ParseIntError;1+use std::num::{self, ParseIntError};2 3 use rust_decimal::Error as DecimalError;4 use thiserror::Error;5 47 unmodified linesmodified:src/main.rs+10 added-12 removed
1 use std::env;2 3+use app::get_arg_matches;4+use benchmark::result::BenchmarkResult;5+use benchmark::{mean_shell_spawning_time, run_benchmark};6+use command::{build_commands, Command};7+use export::ExportManager;8+use options::{Options, OutputStyleOption};9+10+use anyhow::{bail, Result};11 use colored::*;12 13 pub mod app;14 pub mod benchmark;15 pub mod command;16 pub mod error;17 pub mod export;18 pub mod min_max;19+pub mod numeric;20 pub mod options;21 pub mod outlier_detection;22 pub mod output;14-pub mod parameter_range;23+pub mod parameter;24 pub mod relative_speed;25 pub mod shell;26 pub mod timer;18-pub mod tokenize;19-pub mod types;27 pub mod units;28 22-use app::get_arg_matches;23-use benchmark::result::BenchmarkResult;24-use benchmark::{mean_shell_spawning_time, run_benchmark};25-use command::{build_commands, Command};26-use export::ExportManager;27-use options::{Options, OutputStyleOption};28-29-use anyhow::{bail, Result};30-29 pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {30 if results.len() < 2 {31 return;32 }91 unmodified linesadded:src/numeric.rs+48 added
1+use std::convert::TryFrom;2+use std::fmt;3+4+use rust_decimal::prelude::ToPrimitive;5+use rust_decimal::Decimal;6+use serde::Serialize;7+8+#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)]9+#[serde(untagged)]10+pub enum NumericType {11+ Int(i32),12+ Decimal(Decimal),13+}14+15+impl fmt::Display for NumericType {16+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {17+ match *self {18+ NumericType::Int(i) => fmt::Display::fmt(&i, f),19+ NumericType::Decimal(i) => fmt::Display::fmt(&i, f),20+ }21+ }22+}23+24+impl From<i32> for NumericType {25+ fn from(x: i32) -> NumericType {26+ NumericType::Int(x)27+ }28+}29+30+impl From<Decimal> for NumericType {31+ fn from(x: Decimal) -> NumericType {32+ NumericType::Decimal(x)33+ }34+}35+36+impl TryFrom<NumericType> for usize {37+ type Error = ();38+39+ fn try_from(numeric: NumericType) -> Result<Self, Self::Error> {40+ match numeric {41+ NumericType::Int(i) => usize::try_from(i).map_err(|_| ()),42+ NumericType::Decimal(d) => match d.to_u64() {43+ Some(u) => usize::try_from(u).map_err(|_| ()),44+ None => Err(()),45+ },46+ }47+ }48+}deleted:src/parameter_range.rs-317 removed
1-use std::convert::TryInto;2-use std::ops::{Add, AddAssign, Div, Sub};3-use std::str::FromStr;4-5-use clap::Values;6-use rust_decimal::Decimal;7-8-use crate::command::Command;9-use crate::error::ParameterScanError;10-use crate::types::{NumericType, ParameterValue};11-12-trait Numeric:13- Add<Output = Self>14- + Sub<Output = Self>15- + Div<Output = Self>16- + AddAssign17- + PartialOrd18- + Copy19- + Clone20- + From<i32>21- + Into<NumericType>22-{23-}24-impl<25- T: Add<Output = Self>26- + Sub<Output = Self>27- + Div<Output = Self>28- + AddAssign29- + PartialOrd30- + Copy31- + Clone32- + From<i32>33- + Into<NumericType>,34- > Numeric for T35-{36-}37-38-#[derive(Debug)]39-struct RangeStep<T> {40- state: T,41- end: T,42- step: T,43-}44-45-impl<T: Numeric> RangeStep<T> {46- fn new(start: T, end: T, step: T) -> Result<Self, ParameterScanError> {47- if end < start {48- return Err(ParameterScanError::EmptyRange);49- }50-51- if step == T::from(0) {52- return Err(ParameterScanError::ZeroStep);53- }54-55- const MAX_PARAMETERS: usize = 100_000;56- match range_step_size_hint(start, end, step) {57- (_, Some(size)) if size <= MAX_PARAMETERS => Ok(Self {58- state: start,59- end,60- step,61- }),62- _ => Err(ParameterScanError::TooLarge),63- }64- }65-}66-67-impl<T: Numeric> Iterator for RangeStep<T> {68- type Item = T;69-70- fn next(&mut self) -> Option<Self::Item> {71- if self.state > self.end {72- return None;73- }74- let return_val = self.state;75- self.state += self.step;76-77- Some(return_val)78- }79-80- fn size_hint(&self) -> (usize, Option<usize>) {81- range_step_size_hint(self.state, self.end, self.step)82- }83-}84-85-fn range_step_size_hint<T: Numeric>(start: T, end: T, step: T) -> (usize, Option<usize>) {86- if step == T::from(0) {87- return (usize::MAX, None);88- }89-90- let steps = (end - start + T::from(1)) / step;91- steps92- .into()93- .try_into()94- .map_or((usize::MAX, None), |u| (u, Some(u)))95-}96-97-fn build_parameterized_commands<'a, T: Numeric>(98- param_min: T,99- param_max: T,100- step: T,101- command_names: Vec<&'a str>,102- command_strings: Vec<&'a str>,103- param_name: &'a str,104-) -> Result<Vec<Command<'a>>, ParameterScanError> {105- let param_range = RangeStep::new(param_min, param_max, step)?;106- let param_count = param_range.size_hint().1.unwrap();107- let command_name_count = command_names.len();108-109- // `--command-name` should appear exactly once or exactly B times,110- // where B is the total number of benchmarks.111- if command_name_count > 1 && command_name_count != param_count {112- return Err(ParameterScanError::UnexpectedCommandNameCount(113- command_name_count,114- param_count,115- ));116- }117-118- let mut i = 0;119- let mut commands = vec![];120- for value in param_range {121- for cmd in &command_strings {122- let name = command_names123- .get(i)124- .or_else(|| command_names.get(0))125- .copied();126- commands.push(Command::new_parametrized(127- name,128- cmd,129- vec![(param_name, ParameterValue::Numeric(value.into()))],130- ));131- i += 1;132- }133- }134- Ok(commands)135-}136-137-pub fn get_parameterized_commands<'a>(138- command_names: Option<Values<'a>>,139- command_strings: Values<'a>,140- mut vals: clap::Values<'a>,141- step: Option<&str>,142-) -> Result<Vec<Command<'a>>, ParameterScanError> {143- let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());144- let command_strings = command_strings.collect::<Vec<&str>>();145- let param_name = vals.next().unwrap();146- let param_min = vals.next().unwrap();147- let param_max = vals.next().unwrap();148-149- // attempt to parse as integers150- if let (Ok(param_min), Ok(param_max), Ok(step)) = (151- param_min.parse::<i32>(),152- param_max.parse::<i32>(),153- step.unwrap_or("1").parse::<i32>(),154- ) {155- return build_parameterized_commands(156- param_min,157- param_max,158- step,159- command_names,160- command_strings,161- param_name,162- );163- }164-165- // try parsing them as decimals166- let param_min = Decimal::from_str(param_min)?;167- let param_max = Decimal::from_str(param_max)?;168-169- if step.is_none() {170- return Err(ParameterScanError::StepRequired);171- }172-173- let step = Decimal::from_str(step.unwrap())?;174- build_parameterized_commands(175- param_min,176- param_max,177- step,178- command_names,179- command_strings,180- param_name,181- )182-}183-184-#[test]185-fn test_integer_range() {186- let param_range: Vec<i32> = RangeStep::new(0, 10, 3).unwrap().collect();187-188- assert_eq!(param_range.len(), 4);189- assert_eq!(param_range[0], 0);190- assert_eq!(param_range[3], 9);191-}192-193-#[test]194-fn test_decimal_range() {195- let param_min = Decimal::from(0);196- let param_max = Decimal::from(1);197- let step = Decimal::from_str("0.1").unwrap();198-199- let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step)200- .unwrap()201- .collect();202-203- assert_eq!(param_range.len(), 11);204- assert_eq!(param_range[0], Decimal::from(0));205- assert_eq!(param_range[10], Decimal::from(1));206-}207-208-#[test]209-fn test_range_step_validate() {210- let result = RangeStep::new(0, 10, 3);211- assert!(result.is_ok());212-213- let result = RangeStep::new(214- Decimal::from(0),215- Decimal::from(1),216- Decimal::from_str("0.1").unwrap(),217- );218- assert!(result.is_ok());219-220- let result = RangeStep::new(11, 10, 1);221- assert_eq!(format!("{}", result.unwrap_err()), "Empty parameter range");222-223- let result = RangeStep::new(0, 10, 0);224- assert_eq!(225- format!("{}", result.unwrap_err()),226- "Zero is not a valid parameter step"227- );228-229- let result = RangeStep::new(0, 100_001, 1);230- assert_eq!(231- format!("{}", result.unwrap_err()),232- "Parameter range is too large"233- );234-}235-236-#[test]237-fn test_get_parameterized_commands_int() {238- let commands =239- build_parameterized_commands(1i32, 7i32, 3i32, vec![], vec!["echo {val}"], "val").unwrap();240- assert_eq!(commands.len(), 3);241- assert_eq!(commands[2].get_name(), "echo 7");242- assert_eq!(commands[2].get_shell_command(), "echo 7");243-}244-245-#[test]246-fn test_get_parameterized_commands_decimal() {247- let param_min = Decimal::from_str("0").unwrap();248- let param_max = Decimal::from_str("1").unwrap();249- let step = Decimal::from_str("0.33").unwrap();250-251- let commands = build_parameterized_commands(252- param_min,253- param_max,254- step,255- vec![],256- vec!["echo {val}"],257- "val",258- )259- .unwrap();260- assert_eq!(commands.len(), 4);261- assert_eq!(commands[3].get_name(), "echo 0.99");262- assert_eq!(commands[3].get_shell_command(), "echo 0.99");263-}264-265-#[test]266-fn test_get_parameterized_command_names() {267- let commands = build_parameterized_commands(268- 1i32,269- 3i32,270- 1i32,271- vec!["name-{val}"],272- vec!["echo {val}"],273- "val",274- )275- .unwrap();276- assert_eq!(commands.len(), 3);277- let command_names = commands278- .iter()279- .map(|c| c.get_name())280- .collect::<Vec<String>>();281- assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]);282-}283-284-#[test]285-fn test_get_specified_command_names() {286- let commands = build_parameterized_commands(287- 1i32,288- 3i32,289- 1i32,290- vec!["name-a", "name-b", "name-c"],291- vec!["echo {val}"],292- "val",293- )294- .unwrap();295- assert_eq!(commands.len(), 3);296- let command_names = commands297- .iter()298- .map(|c| c.get_name())299- .collect::<Vec<String>>();300- assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);301-}302-303-#[test]304-fn test_different_command_name_count_with_parameters() {305- let result = build_parameterized_commands(306- 1i32,307- 3i32,308- 1i32,309- vec!["name-1", "name-2"],310- vec!["echo {val}"],311- "val",312- );313- assert_eq!(314- format!("{}", result.unwrap_err()),315- "'--command-name' has been specified 2 times. It has to appear exactly once, or exactly 3 times (number of benchmarks)"316- );317-}deleted:src/tokenize.rs-60 removed
1-pub fn tokenize(values: &str) -> Vec<String> {2- let mut tokens = vec![];3- let mut buf = String::new();4-5- let mut iter = values.chars();6- while let Some(c) = iter.next() {7- match c {8- '\\' => match iter.next() {9- Some(c2 @ ',') | Some(c2 @ '\\') => {10- buf.push(c2);11- }12- Some(c2) => {13- buf.push('\\');14- buf.push(c2);15- }16- None => buf.push('\\'),17- },18- ',' => {19- tokens.push(buf);20- buf = String::new();21- }22- _ => {23- buf.push(c);24- }25- };26- }27-28- tokens.push(buf);29-30- tokens31-}32-33-#[test]34-fn test_tokenize_single_value() {35- assert_eq!(tokenize(r""), vec![""]);36- assert_eq!(tokenize(r"foo"), vec!["foo"]);37- assert_eq!(tokenize(r" "), vec![" "]);38- assert_eq!(tokenize(r"hello\, world!"), vec!["hello, world!"]);39- assert_eq!(tokenize(r"\,"), vec![","]);40- assert_eq!(tokenize(r"\,\,\,"), vec![",,,"]);41- assert_eq!(tokenize(r"\n"), vec![r"\n"]);42- assert_eq!(tokenize(r"\\"), vec![r"\"]);43- assert_eq!(tokenize(r"\\\,"), vec![r"\,"]);44-}45-46-#[test]47-fn test_tokenize_multiple_values() {48- assert_eq!(tokenize(r"foo,bar,baz"), vec!["foo", "bar", "baz"]);49- assert_eq!(tokenize(r"hello world,foo"), vec!["hello world", "foo"]);50-51- assert_eq!(tokenize(r"hello\,world!,baz"), vec!["hello,world!", "baz"]);52-}53-54-#[test]55-fn test_tokenize_empty_values() {56- assert_eq!(tokenize(r"foo,,bar"), vec!["foo", "", "bar"]);57- assert_eq!(tokenize(r",bar"), vec!["", "bar"]);58- assert_eq!(tokenize(r"bar,"), vec!["bar", ""]);59- assert_eq!(tokenize(r",,"), vec!["", "", ""]);60-}deleted:src/types.rs-63 removed
1-use std::convert::TryFrom;2-use std::fmt;3-4-use rust_decimal::prelude::ToPrimitive;5-use rust_decimal::Decimal;6-use serde::Serialize;7-8-#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)]9-#[serde(untagged)]10-pub enum NumericType {11- Int(i32),12- Decimal(Decimal),13-}14-15-impl fmt::Display for NumericType {16- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {17- match *self {18- NumericType::Int(i) => fmt::Display::fmt(&i, f),19- NumericType::Decimal(i) => fmt::Display::fmt(&i, f),20- }21- }22-}23-24-impl From<i32> for NumericType {25- fn from(x: i32) -> NumericType {26- NumericType::Int(x)27- }28-}29-30-impl From<Decimal> for NumericType {31- fn from(x: Decimal) -> NumericType {32- NumericType::Decimal(x)33- }34-}35-36-impl TryFrom<NumericType> for usize {37- type Error = ();38-39- fn try_from(numeric: NumericType) -> Result<Self, Self::Error> {40- match numeric {41- NumericType::Int(i) => usize::try_from(i).map_err(|_| ()),42- NumericType::Decimal(d) => match d.to_u64() {43- Some(u) => usize::try_from(u).map_err(|_| ()),44- None => Err(()),45- },46- }47- }48-}49-50-#[derive(Debug, Clone, PartialEq, Eq)]51-pub enum ParameterValue {52- Text(String),53- Numeric(NumericType),54-}55-56-impl<'a> ToString for ParameterValue {57- fn to_string(&self) -> String {58- match self {59- ParameterValue::Text(ref value) => value.clone(),60- ParameterValue::Numeric(value) => value.to_string(),61- }62- }63-}