Add markdown support.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Don't create Strings to convert to bytes later, just serialize directly to bytes in the first place
authored by Steve Pentland · committed by David Peter · parent df1500d · Browse files · 5 files·+67 added−25 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+67 added−25 removed
- other:+67 added−25 removed
Provenance
- Commit
8b933dc- Tree
cfb9eb5- Author
Steve Pentland <stevepentland@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
df1500d
5 files changed+67 added−25 removed
modified:src/hyperfine/export/csv.rs+3 added-10 removed
1 unmodified line2 3 use csv::WriterBuilder;4 use std::io::{Error, ErrorKind, Result};5 6+#[derive(Default)]7 pub struct CsvExporter {}8 9 impl Exporter for CsvExporter {9- fn serialize(&self, results: &Vec<ExportEntry>) -> Result<String> {10+ fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {11 let mut writer = WriterBuilder::new().from_writer(vec![]);12 for res in results {13 writer.serialize(res)?;14 }15 16 writer17 .into_inner()17- .ok()18- .and_then(|bytes| String::from_utf8(bytes).ok())19- .ok_or(Error::new(ErrorKind::Other, "Error serializing to CSV"))18+ .map_err(|e| Error::new(ErrorKind::Other, e))19 }20 }22-23-impl CsvExporter {24- pub fn new() -> Self {25- CsvExporter {}26- }27-}modified:src/hyperfine/export/json.rs+4 added-9 removed
1 use super::{ExportEntry, Exporter};2 3 use std::io::{Error, ErrorKind, Result};4 5-use serde_json::to_string_pretty;5+use serde_json::to_vec_pretty;6 7 #[derive(Serialize, Debug)]8 struct HyperfineSummary<'a> {9 results: &'a Vec<ExportEntry>,10 }11 12+#[derive(Default)]13 pub struct JsonExporter {}14 15 impl Exporter for JsonExporter {15- fn serialize(&self, results: &Vec<ExportEntry>) -> Result<String> {16- to_string_pretty(&HyperfineSummary { results }).map_err(|e| Error::new(ErrorKind::Other, e))16+ fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {17+ to_vec_pretty(&HyperfineSummary { results }).map_err(|e| Error::new(ErrorKind::Other, e))18 }19 }19-20-impl JsonExporter {21- pub fn new() -> Self {22- JsonExporter {}23- }24-}added:src/hyperfine/export/markdown.rs+38 added
1+use super::{ExportEntry, Exporter};2+3+use std::io::Result;4+5+const MULTIPLIER: f64 = 1e3;6+7+#[derive(Default)]8+pub struct MarkdownExporter {}9+10+impl Exporter for MarkdownExporter {11+ fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {12+ let mut destination = start_table();13+14+ for result in results {15+ add_table_row(&mut destination, result);16+ }17+18+ Ok(destination)19+ }20+}21+22+fn start_table() -> Vec<u8> {23+ "| Benchmark | Mean [ms] | Min. [ms] | Max. [ms] |\n|----|----|----|----|\n"24+ .bytes()25+ .collect()26+}27+fn add_table_row(dest: &mut Vec<u8>, entry: &ExportEntry) {28+ dest.extend(29+ format!(30+ "| {} | {:.1} ± {:.1} | {:.1} | {:.1} |\n",31+ entry.command.replace("|", "\\|"),32+ entry.mean * MULTIPLIER,33+ entry.stddev * MULTIPLIER,34+ entry.min * MULTIPLIER,35+ entry.max * MULTIPLIER36+ ).as_bytes(),37+ );38+}modified:src/hyperfine/export/mod.rs+12 added-6 removed
1 mod csv;2 mod json;3+mod markdown;4 5 use self::csv::CsvExporter;6 use self::json::JsonExporter;7+use self::markdown::MarkdownExporter;8 9 use std::io::{Result, Write};10 use std::fs::File;11 54 unmodified lines66 Csv,67 68 /// JSON format69 Json,70+71+ /// Markdown table72+ Markdown,73 }74 75 /// Interface for different exporters.76 trait Exporter {77 /// Export the given entries in the serialized form.73- fn serialize(&self, results: &Vec<ExportEntry>) -> Result<String>;78+ fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>>;79 }80 81 struct ExporterWithFilename {82 exporter: Box<Exporter>,15 unmodified lines98 99 /// Add an additional exporter to the ExportManager100 pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) {101 let exporter: Box<Exporter> = match export_type {97- ExportType::Csv => Box::new(CsvExporter::new()),98- ExportType::Json => Box::new(JsonExporter::new()),102+ ExportType::Csv => Box::new(CsvExporter::default()),103+ ExportType::Json => Box::new(JsonExporter::default()),104+ ExportType::Markdown => Box::new(MarkdownExporter::default()),105 };106 self.exporters.push(ExporterWithFilename {107 exporter,108 filename: filename.to_string(),3 unmodified lines112 /// Write the given results to all Exporters contained within this manager113 pub fn write_results(&self, results: Vec<ExportEntry>) -> Result<()> {114 for e in &self.exporters {115 let file_content = e.exporter.serialize(&results)?;110- write_to_file(&e.filename, file_content)?;116+ write_to_file(&e.filename, &file_content)?;117 }118 Ok(())119 }120 }121 122 /// Write the given content to a file with the specified name117-fn write_to_file(filename: &String, content: String) -> Result<()> {123+fn write_to_file(filename: &String, content: &Vec<u8>) -> Result<()> {124 let mut file = File::create(filename)?;119- file.write_all(content.as_bytes())125+ file.write_all(content)126 }modified:src/main.rs+10 added
150 unmodified lines151 .takes_value(true)152 .value_name("FILE")153 .help("Export the timing results as JSON to the given FILE."),154 )155+ .arg(156+ Arg::with_name("export-md")157+ .long("export-md")158+ .takes_value(true)159+ .value_name("FILE")160+ .help("Export the timing results to a markdown table in the given file"),161+ )162 .help_message("Print this help message.")163 .version_message("Show version information.")164 .get_matches();165 28 unmodified lines194 }195 if let Some(filename) = matches.value_of("export-csv") {196 export_manager.add_exporter(ExportType::Csv, filename);197 }198+ if let Some(filename) = matches.value_of("export-md") {199+ export_manager.add_exporter(ExportType::Markdown, filename);200+ }201 202 // We default Windows to NoColor if full had been specified.203 if cfg!(windows) && options.output_style == OutputStyleOption::Full {204 options.output_style = OutputStyleOption::NoColor;26 unmodified lines