From dbbdb8e5c00e7bd78b1635c995df3dd98b0bc597 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 29 Dec 2022 18:41:42 +0100 Subject: [PATCH] Add error variant for when not all bytes are written cargo-clippy tells us that the `crate::helpers::json::to_writer` and `crate::helpers::toml::to_writer` functions were implemented without checking the return value of the `write()` function called inside. That might lead to serious issues on the user site, if indeed not all bytes were written. This patch fixes the issue of the user not knowning about the issue by introducing a new error variant and returning it in case of unfinished writes. Signed-off-by: Matthias Beyer --- src/errors.rs | 7 +++++++ src/helpers/json.rs | 7 +++++-- src/helpers/toml.rs | 7 +++++-- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index 673d956..d018b34 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -64,6 +64,13 @@ pub enum Error { /// Error deserializing from toml #[error("Error deserializing from toml")] TomlDe(#[from] TomlDeError), + + #[cfg(any(feature = "toml", feature = "json"))] + /// Error raised in the helpers::json::to_writer or helpers::toml::to_writer function if not + /// all bytes were written to the writer + #[error("Not all bytes were written")] + NotAllBytesWritten, + /// Error converting an http header to a string #[error("Error converting an http header to a string")] HeaderStrError(#[from] HeaderStrError), diff --git a/src/helpers/json.rs b/src/helpers/json.rs index e12e602..ea0cb43 100644 --- a/src/helpers/json.rs +++ b/src/helpers/json.rs @@ -48,8 +48,11 @@ pub fn to_vec(data: &Data) -> Result> { pub fn to_writer(data: &Data, writer: W) -> Result<()> { let mut buf_writer = BufWriter::new(writer); let vec = to_vec(data)?; - buf_writer.write(&vec)?; - Ok(()) + if vec.len() != buf_writer.write(&vec)? { + Err(crate::Error::NotAllBytesWritten) + } else { + Ok(()) + } } /// Attempts to serialize a Data struct to a file diff --git a/src/helpers/toml.rs b/src/helpers/toml.rs index 086bbe2..620a845 100644 --- a/src/helpers/toml.rs +++ b/src/helpers/toml.rs @@ -48,8 +48,11 @@ pub fn to_vec(data: &Data) -> Result> { pub fn to_writer(data: &Data, writer: W) -> Result<()> { let mut buf_writer = BufWriter::new(writer); let vec = to_vec(data)?; - buf_writer.write(&vec)?; - Ok(()) + if vec.len() != !buf_writer.write(&vec)? { + Err(crate::Error::NotAllBytesWritten) + } else { + Ok(()) + } } /// Attempts to serialize a Data struct to a file