Skip to content
Myr

Move Command struct to new 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 b5bd054 · Browse files · 6 files+130 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

6 files+130 added−120 removed

  • other:+130 added−120 removed

6 files+130 added−120 removed

modified:src/hyperfine/benchmark.rs+2 added-1 removed
3 unmodified lines
45use colored::*;6use statistical::{mean, median, standard_deviation};78use crate::hyperfine::command::Command;9use crate::hyperfine::format::{format_duration, format_duration_unit};10use crate::hyperfine::internal::{get_progress_bar, max, min, MIN_EXECUTION_TIME};11use crate::hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};12use crate::hyperfine::shell::execute_and_time;13use crate::hyperfine::timer::wallclocktimer::WallClockTimer;14use crate::hyperfine::timer::{TimerStart, TimerStop};15use crate::hyperfine::types::{15 BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption,16 BenchmarkResult, CmdFailureAction, HyperfineOptions, OutputStyleOption,17};18use crate::hyperfine::units::Second;19use crate::hyperfine::warnings::Warnings;20
465 unmodified lines
added:src/hyperfine/command.rs+115 added
1use std::collections::BTreeMap;2use std::fmt;34use super::types::ParameterValue;56/// A command that should be benchmarked.7#[derive(Debug, Clone, PartialEq, Eq)]8pub struct Command<'a> {9 /// The command name (without parameter substitution)10 name: Option<&'a str>,1112 /// The command that should be executed (without parameter substitution)13 expression: &'a str,1415 /// Zero or more parameter values.16 parameters: Vec<(&'a str, ParameterValue)>,17}1819impl<'a> Command<'a> {20 pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {21 Command {22 name,23 expression,24 parameters: Vec::new(),25 }26 }2728 pub fn new_parametrized(29 name: Option<&'a str>,30 expression: &'a str,31 parameters: Vec<(&'a str, ParameterValue)>,32 ) -> Command<'a> {33 Command {34 name,35 expression,36 parameters,37 }38 }3940 pub fn get_name(&self) -> String {41 self.name.map_or_else(42 || self.get_shell_command(),43 |name| self.replace_parameters_in(name),44 )45 }4647 pub fn get_shell_command(&self) -> String {48 self.replace_parameters_in(self.expression)49 }5051 pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {52 &self.parameters53 }5455 fn replace_parameters_in(&self, original: &str) -> String {56 let mut result = String::new();57 let mut replacements = BTreeMap::<String, String>::new();58 for (param_name, param_value) in &self.parameters {59 replacements.insert(60 format!("{{{param_name}}}", param_name = param_name),61 param_value.to_string(),62 );63 }64 let mut remaining = original;65 // Manually replace consecutive occurrences to avoid double-replacing: e.g.,66 //67 // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'68 //69 // should not ever run 'echo baz baz'. See `test_get_shell_command_nonoverlapping`.70 'outer: while let Some(head) = remaining.chars().next() {71 for (k, v) in &replacements {72 if remaining.starts_with(k.as_str()) {73 result.push_str(v);74 remaining = &remaining[k.len()..];75 continue 'outer;76 }77 }78 result.push(head);79 remaining = &remaining[head.len_utf8()..];80 }81 result82 }83}8485#[test]86fn test_get_shell_command_nonoverlapping() {87 let cmd = Command::new_parametrized(88 None,89 "echo {foo} {bar}",90 vec![91 ("foo", ParameterValue::Text("{bar} baz".into())),92 ("bar", ParameterValue::Text("quux".into())),93 ],94 );95 assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux");96}9798#[test]99fn test_get_parameterized_command_name() {100 let cmd = Command::new_parametrized(101 Some("name-{bar}-{foo}"),102 "echo {foo} {bar}",103 vec![104 ("foo", ParameterValue::Text("baz".into())),105 ("bar", ParameterValue::Text("quux".into())),106 ],107 );108 assert_eq!(cmd.get_name(), "name-quux-baz");109}110111impl<'a> fmt::Display for Command<'a> {112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {113 write!(f, "{}", self.get_shell_command())114 }115}
modified:src/hyperfine/mod.rs+1 added
1pub mod app;2pub mod benchmark;3pub mod command;4pub mod error;5pub mod export;6pub mod format;7pub mod internal;
7 unmodified lines
modified:src/hyperfine/parameter_range.rs+7 added-4 removed
1use crate::hyperfine::error::ParameterScanError;2use crate::hyperfine::types::{Command, NumericType, ParameterValue};3use clap::Values;4use rust_decimal::Decimal;1use std::convert::TryInto;2use std::ops::{Add, AddAssign, Div, Sub};3use std::str::FromStr;45use clap::Values;6use rust_decimal::Decimal;78use crate::hyperfine::command::Command;9use crate::hyperfine::error::ParameterScanError;10use crate::hyperfine::types::{NumericType, ParameterValue};1112trait Numeric:13 Add<Output = Self>14 + Sub<Output = Self>15 + Div<Output = Self>
302 unmodified lines
modified:src/hyperfine/types.rs+3 added-114 removed
1use rust_decimal::prelude::ToPrimitive;2use rust_decimal::Decimal;3/// This module contains common internal types.1use serde::*;2use std::collections::BTreeMap;3use std::convert::TryFrom;4use std::fmt;56use rust_decimal::prelude::ToPrimitive;7use rust_decimal::Decimal;89use crate::hyperfine::units::{Second, Unit};1011#[cfg(not(windows))]12pub const DEFAULT_SHELL: &str = "sh";
57 unmodified lines
70 }71 }72}7374/// A command that should be benchmarked.75#[derive(Debug, Clone, PartialEq, Eq)]76pub struct Command<'a> {77 /// The command name (without parameter substitution)78 name: Option<&'a str>,7980 /// The command that should be executed (without parameter substitution)81 expression: &'a str,8283 /// Zero or more parameter values.84 parameters: Vec<(&'a str, ParameterValue)>,85}8687impl<'a> Command<'a> {88 pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {89 Command {90 name,91 expression,92 parameters: Vec::new(),93 }94 }9596 pub fn new_parametrized(97 name: Option<&'a str>,98 expression: &'a str,99 parameters: Vec<(&'a str, ParameterValue)>,100 ) -> Command<'a> {101 Command {102 name,103 expression,104 parameters,105 }106 }107108 pub fn get_name(&self) -> String {109 self.name.map_or_else(110 || self.get_shell_command(),111 |name| self.replace_parameters_in(name),112 )113 }114115 pub fn get_shell_command(&self) -> String {116 self.replace_parameters_in(self.expression)117 }118119 pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {120 &self.parameters121 }122123 fn replace_parameters_in(&self, original: &str) -> String {124 let mut result = String::new();125 let mut replacements = BTreeMap::<String, String>::new();126 for (param_name, param_value) in &self.parameters {127 replacements.insert(128 format!("{{{param_name}}}", param_name = param_name),129 param_value.to_string(),130 );131 }132 let mut remaining = original;133 // Manually replace consecutive occurrences to avoid double-replacing: e.g.,134 //135 // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'136 //137 // should not ever run 'echo baz baz'. See `test_get_shell_command_nonoverlapping`.138 'outer: while let Some(head) = remaining.chars().next() {139 for (k, v) in &replacements {140 if remaining.starts_with(k.as_str()) {141 result.push_str(v);142 remaining = &remaining[k.len()..];143 continue 'outer;144 }145 }146 result.push(head);147 remaining = &remaining[head.len_utf8()..];148 }149 result150 }151}152153#[test]154fn test_get_shell_command_nonoverlapping() {155 let cmd = Command::new_parametrized(156 None,157 "echo {foo} {bar}",158 vec![159 ("foo", ParameterValue::Text("{bar} baz".into())),160 ("bar", ParameterValue::Text("quux".into())),161 ],162 );163 assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux");164}165166#[test]167fn test_get_parameterized_command_name() {168 let cmd = Command::new_parametrized(169 Some("name-{bar}-{foo}"),170 "echo {foo} {bar}",171 vec![172 ("foo", ParameterValue::Text("baz".into())),173 ("bar", ParameterValue::Text("quux".into())),174 ],175 );176 assert_eq!(cmd.get_name(), "name-quux-baz");177}178179impl<'a> fmt::Display for Command<'a> {180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {181 write!(f, "{}", self.get_shell_command())182 }183}18474/// Action to take when an executed command fails.75#[derive(Debug, Clone, Copy, PartialEq)]76pub enum CmdFailureAction {77 /// Exit with an error message
168 unmodified lines
modified:src/main.rs+2 added-1 removed
9 unmodified lines
10mod hyperfine;1112use crate::hyperfine::app::get_arg_matches;13use crate::hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};14use crate::hyperfine::command::Command;15use crate::hyperfine::error::OptionsError;16use crate::hyperfine::export::{ExportManager, ExportType};17use crate::hyperfine::internal::{tokenize, write_benchmark_comparison};18use crate::hyperfine::parameter_range::get_parameterized_commands;19use crate::hyperfine::types::{19 CmdFailureAction, Command, HyperfineOptions, OutputStyleOption, ParameterValue,20 CmdFailureAction, HyperfineOptions, OutputStyleOption, ParameterValue,21};22use crate::hyperfine::units::Unit;2324/// Print error message to stderr and terminate
384 unmodified lines