From 4b8cc3481546c0d49b1f11cc13f0da68e45c2e1f Mon Sep 17 00:00:00 2001 From: sharkdp Date: Tue, 20 Mar 2018 20:47:19 +0100 Subject: [PATCH] Use String instead of bytes, change error handling --- src/hyperfine/export/csv.rs | 11 ++++++----- src/hyperfine/export/json.rs | 16 +++++++++------- src/hyperfine/export/mod.rs | 6 +++--- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/hyperfine/export/csv.rs b/src/hyperfine/export/csv.rs index f1be1b8..9653b91 100644 --- a/src/hyperfine/export/csv.rs +++ b/src/hyperfine/export/csv.rs @@ -6,16 +6,17 @@ use std::io::{Error, ErrorKind, Result}; pub struct CsvExporter {} impl Exporter for CsvExporter { - fn serialize(&self, results: &Vec) -> Result> { + fn serialize(&self, results: &Vec) -> Result { let mut writer = WriterBuilder::new().from_writer(vec![]); for res in results { writer.serialize(res)?; } - if let Ok(inner) = writer.into_inner() { - return Ok(inner); - } - Err(Error::new(ErrorKind::Other, "Error serializing to CSV")) + writer + .into_inner() + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + .ok_or(Error::new(ErrorKind::Other, "Error serializing to CSV")) } } diff --git a/src/hyperfine/export/json.rs b/src/hyperfine/export/json.rs index a3bad56..e4e6631 100644 --- a/src/hyperfine/export/json.rs +++ b/src/hyperfine/export/json.rs @@ -2,7 +2,7 @@ use super::{ExportEntry, Exporter}; use std::io::{Error, ErrorKind, Result}; -use serde_json::to_vec_pretty; +use serde_json::to_string_pretty; #[derive(Serialize, Debug)] struct HyperfineSummary<'a> { @@ -12,13 +12,15 @@ struct HyperfineSummary<'a> { pub struct JsonExporter {} impl Exporter for JsonExporter { - fn serialize(&self, results: &Vec) -> Result> { - let serialized = to_vec_pretty(&HyperfineSummary { results }); + fn serialize(&self, results: &Vec) -> Result { + let serialized = to_string_pretty(&HyperfineSummary { results }); - match serialized { - Ok(file_content) => Ok(file_content), - Err(e) => Err(Error::new(ErrorKind::Other, format!("{:?}", e))), - } + serialized.map_err(|e| { + Error::new( + ErrorKind::Other, + format!("Error while serializing to JSON: {:}", e), + ) + }) } } diff --git a/src/hyperfine/export/mod.rs b/src/hyperfine/export/mod.rs index 612eded..c79bdf1 100644 --- a/src/hyperfine/export/mod.rs +++ b/src/hyperfine/export/mod.rs @@ -70,7 +70,7 @@ pub enum ExportType { /// Interface for different exporters. trait Exporter { /// Export the given entries in the serialized form. - fn serialize(&self, values: &Vec) -> Result>; + fn serialize(&self, results: &Vec) -> Result; } /// Handles the management of multiple file exporters. @@ -107,8 +107,8 @@ impl ExportManager { } /// Write the given content to a file with the specified name -fn write_to_file(filename: &str, content: Vec) -> Result<()> { +fn write_to_file(filename: &str, content: String) -> Result<()> { let mut file = File::create(filename)?; - file.write_all(&content)?; + file.write_all(content.as_bytes())?; Ok(()) }