Skip to content
Myr

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

5 files+67 added−25 removed

modified:src/hyperfine/export/csv.rs+3 added-10 removed
1 unmodified line
23use csv::WriterBuilder;4use std::io::{Error, ErrorKind, Result};56#[derive(Default)]7pub struct CsvExporter {}89impl 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 }1516 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}2223impl CsvExporter {24 pub fn new() -> Self {25 CsvExporter {}26 }27}
modified:src/hyperfine/export/json.rs+4 added-9 removed
1use super::{ExportEntry, Exporter};23use std::io::{Error, ErrorKind, Result};45use serde_json::to_string_pretty;5use serde_json::to_vec_pretty;67#[derive(Serialize, Debug)]8struct HyperfineSummary<'a> {9 results: &'a Vec<ExportEntry>,10}1112#[derive(Default)]13pub struct JsonExporter {}1415impl 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}1920impl JsonExporter {21 pub fn new() -> Self {22 JsonExporter {}23 }24}
added:src/hyperfine/export/markdown.rs+38 added
1use super::{ExportEntry, Exporter};23use std::io::Result;45const MULTIPLIER: f64 = 1e3;67#[derive(Default)]8pub struct MarkdownExporter {}910impl Exporter for MarkdownExporter {11 fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {12 let mut destination = start_table();1314 for result in results {15 add_table_row(&mut destination, result);16 }1718 Ok(destination)19 }20}2122fn start_table() -> Vec<u8> {23 "| Benchmark | Mean [ms] | Min. [ms] | Max. [ms] |\n|----|----|----|----|\n"24 .bytes()25 .collect()26}27fn 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
1mod csv;2mod json;3mod markdown;45use self::csv::CsvExporter;6use self::json::JsonExporter;7use self::markdown::MarkdownExporter;89use std::io::{Result, Write};10use std::fs::File;11
54 unmodified lines
66 Csv,6768 /// JSON format69 Json,7071 /// Markdown table72 Markdown,73}7475/// Interface for different exporters.76trait 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}8081struct ExporterWithFilename {82 exporter: Box<Exporter>,
15 unmodified lines
9899 /// 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 lines
112 /// 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}121122/// Write the given content to a file with the specified name117fn write_to_file(filename: &String, content: String) -> Result<()> {123fn 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 lines
151 .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 lines
194 }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 }201202 // 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