Skip to content
Myr

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

10 files+460 added−457 removed

added:src/parameter/mod.rs+19 added
1use crate::numeric::NumericType;23pub mod range;4pub mod tokenize;56#[derive(Debug, Clone, PartialEq, Eq)]7pub enum ParameterValue {8 Text(String),9 Numeric(NumericType),10}1112impl<'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
1use std::convert::TryInto;2use std::ops::{Add, AddAssign, Div, Sub};3use std::str::FromStr;45use clap::Values;6use rust_decimal::Decimal;78use super::ParameterValue;9use crate::command::Command;10use crate::error::ParameterScanError;11use crate::numeric::NumericType;1213trait 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}25impl<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}3839#[derive(Debug)]40struct RangeStep<T> {41 state: T,42 end: T,43 step: T,44}4546impl<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 }5152 if step == T::from(0) {53 return Err(ParameterScanError::ZeroStep);54 }5556 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}6768impl<T: Numeric> Iterator for RangeStep<T> {69 type Item = T;7071 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;7778 Some(return_val)79 }8081 fn size_hint(&self) -> (usize, Option<usize>) {82 range_step_size_hint(self.state, self.end, self.step)83 }84}8586fn 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 }9091 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}9798fn 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();109110 // `--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 }118119 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}137138pub 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();149150 // 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 }165166 // try parsing them as decimals167 let param_min = Decimal::from_str(param_min)?;168 let param_max = Decimal::from_str(param_max)?;169170 if step.is_none() {171 return Err(ParameterScanError::StepRequired);172 }173174 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}184185#[test]186fn test_integer_range() {187 let param_range: Vec<i32> = RangeStep::new(0, 10, 3).unwrap().collect();188189 assert_eq!(param_range.len(), 4);190 assert_eq!(param_range[0], 0);191 assert_eq!(param_range[3], 9);192}193194#[test]195fn 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();199200 let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step)201 .unwrap()202 .collect();203204 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}208209#[test]210fn test_range_step_validate() {211 let result = RangeStep::new(0, 10, 3);212 assert!(result.is_ok());213214 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());220221 let result = RangeStep::new(11, 10, 1);222 assert_eq!(format!("{}", result.unwrap_err()), "Empty parameter range");223224 let result = RangeStep::new(0, 10, 0);225 assert_eq!(226 format!("{}", result.unwrap_err()),227 "Zero is not a valid parameter step"228 );229230 let result = RangeStep::new(0, 100_001, 1);231 assert_eq!(232 format!("{}", result.unwrap_err()),233 "Parameter range is too large"234 );235}236237#[test]238fn 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}245246#[test]247fn 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();251252 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}265266#[test]267fn 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}284285#[test]286fn 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}303304#[test]305fn 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
1pub fn tokenize(values: &str) -> Vec<String> {2 let mut tokens = vec![];3 let mut buf = String::new();45 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 }2728 tokens.push(buf);2930 tokens31}3233#[test]34fn 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}4546#[test]47fn 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"]);5051 assert_eq!(tokenize(r"hello\,world!,baz"), vec!["hello,world!", "baz"]);52}5354#[test]55fn 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
1use std::collections::BTreeMap;2use std::fmt;34use crate::{error::OptionsError, parameter_range::get_parameterized_commands};4use crate::error::OptionsError;5use crate::parameter::range::get_parameterized_commands;67use clap::ArgMatches;88use crate::tokenize::tokenize;9use crate::types::ParameterValue;9use crate::parameter::tokenize::tokenize;10use crate::parameter::ParameterValue;1112use anyhow::{bail, Result};1314/// A command that should be benchmarked.
310 unmodified lines
modified:src/error.rs+1 added-2 removed
1use std::num;2use std::num::ParseIntError;1use std::num::{self, ParseIntError};23use rust_decimal::Error as DecimalError;4use thiserror::Error;5
47 unmodified lines
modified:src/main.rs+10 added-12 removed
1use std::env;23use app::get_arg_matches;4use benchmark::result::BenchmarkResult;5use benchmark::{mean_shell_spawning_time, run_benchmark};6use command::{build_commands, Command};7use export::ExportManager;8use options::{Options, OutputStyleOption};910use anyhow::{bail, Result};11use colored::*;1213pub mod app;14pub mod benchmark;15pub mod command;16pub mod error;17pub mod export;18pub mod min_max;19pub mod numeric;20pub mod options;21pub mod outlier_detection;22pub mod output;14pub mod parameter_range;23pub mod parameter;24pub mod relative_speed;25pub mod shell;26pub mod timer;18pub mod tokenize;19pub mod types;27pub mod units;2822use app::get_arg_matches;23use benchmark::result::BenchmarkResult;24use benchmark::{mean_shell_spawning_time, run_benchmark};25use command::{build_commands, Command};26use export::ExportManager;27use options::{Options, OutputStyleOption};2829use anyhow::{bail, Result};3029pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {30 if results.len() < 2 {31 return;32 }
91 unmodified lines
added:src/numeric.rs+48 added
1use std::convert::TryFrom;2use std::fmt;34use rust_decimal::prelude::ToPrimitive;5use rust_decimal::Decimal;6use serde::Serialize;78#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)]9#[serde(untagged)]10pub enum NumericType {11 Int(i32),12 Decimal(Decimal),13}1415impl 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}2324impl From<i32> for NumericType {25 fn from(x: i32) -> NumericType {26 NumericType::Int(x)27 }28}2930impl From<Decimal> for NumericType {31 fn from(x: Decimal) -> NumericType {32 NumericType::Decimal(x)33 }34}3536impl TryFrom<NumericType> for usize {37 type Error = ();3839 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
1use std::convert::TryInto;2use std::ops::{Add, AddAssign, Div, Sub};3use std::str::FromStr;45use clap::Values;6use rust_decimal::Decimal;78use crate::command::Command;9use crate::error::ParameterScanError;10use crate::types::{NumericType, ParameterValue};1112trait 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}24impl<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}3738#[derive(Debug)]39struct RangeStep<T> {40 state: T,41 end: T,42 step: T,43}4445impl<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 }5051 if step == T::from(0) {52 return Err(ParameterScanError::ZeroStep);53 }5455 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}6667impl<T: Numeric> Iterator for RangeStep<T> {68 type Item = T;6970 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;7677 Some(return_val)78 }7980 fn size_hint(&self) -> (usize, Option<usize>) {81 range_step_size_hint(self.state, self.end, self.step)82 }83}8485fn 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 }8990 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}9697fn 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();108109 // `--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 }117118 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}136137pub 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();148149 // 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 }164165 // try parsing them as decimals166 let param_min = Decimal::from_str(param_min)?;167 let param_max = Decimal::from_str(param_max)?;168169 if step.is_none() {170 return Err(ParameterScanError::StepRequired);171 }172173 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}183184#[test]185fn test_integer_range() {186 let param_range: Vec<i32> = RangeStep::new(0, 10, 3).unwrap().collect();187188 assert_eq!(param_range.len(), 4);189 assert_eq!(param_range[0], 0);190 assert_eq!(param_range[3], 9);191}192193#[test]194fn 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();198199 let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step)200 .unwrap()201 .collect();202203 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}207208#[test]209fn test_range_step_validate() {210 let result = RangeStep::new(0, 10, 3);211 assert!(result.is_ok());212213 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());219220 let result = RangeStep::new(11, 10, 1);221 assert_eq!(format!("{}", result.unwrap_err()), "Empty parameter range");222223 let result = RangeStep::new(0, 10, 0);224 assert_eq!(225 format!("{}", result.unwrap_err()),226 "Zero is not a valid parameter step"227 );228229 let result = RangeStep::new(0, 100_001, 1);230 assert_eq!(231 format!("{}", result.unwrap_err()),232 "Parameter range is too large"233 );234}235236#[test]237fn 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}244245#[test]246fn 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();250251 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}264265#[test]266fn 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}283284#[test]285fn 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}302303#[test]304fn 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
1pub fn tokenize(values: &str) -> Vec<String> {2 let mut tokens = vec![];3 let mut buf = String::new();45 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 }2728 tokens.push(buf);2930 tokens31}3233#[test]34fn 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}4546#[test]47fn 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"]);5051 assert_eq!(tokenize(r"hello\,world!,baz"), vec!["hello,world!", "baz"]);52}5354#[test]55fn 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
1use std::convert::TryFrom;2use std::fmt;34use rust_decimal::prelude::ToPrimitive;5use rust_decimal::Decimal;6use serde::Serialize;78#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)]9#[serde(untagged)]10pub enum NumericType {11 Int(i32),12 Decimal(Decimal),13}1415impl 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}2324impl From<i32> for NumericType {25 fn from(x: i32) -> NumericType {26 NumericType::Int(x)27 }28}2930impl From<Decimal> for NumericType {31 fn from(x: Decimal) -> NumericType {32 NumericType::Decimal(x)33 }34}3536impl TryFrom<NumericType> for usize {37 type Error = ();3839 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}4950#[derive(Debug, Clone, PartialEq, Eq)]51pub enum ParameterValue {52 Text(String),53 Numeric(NumericType),54}5556impl<'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}