Use String instead of bytes, change error handling

This commit is contained in:
sharkdp authored and David Peter committed 2018-03-20 21:40:06 +01:00
1 parent bd81fe65a2
commit 4b8cc34815
3 files changed
+18 -15

No files matched your search

+6 -5
View File
@@ -6,16 +6,17 @@ use std::io::{Error, ErrorKind, Result};
pub struct CsvExporter {}
impl Exporter for CsvExporter {
fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {
fn serialize(&self, results: &Vec<ExportEntry>) -> Result<String> {
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"))
}
}
+9 -7
View File
@@ -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<ExportEntry>) -> Result<Vec<u8>> {
let serialized = to_vec_pretty(&HyperfineSummary { results });
fn serialize(&self, results: &Vec<ExportEntry>) -> Result<String> {
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),
)
})
}
}
+3 -3
View File
@@ -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<ExportEntry>) -> Result<Vec<u8>>;
fn serialize(&self, results: &Vec<ExportEntry>) -> Result<String>;
}
/// 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<u8>) -> 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(())
}