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 <mail@beyermatthias.de>
This commit is contained in:
Matthias Beyer 2022-12-29 18:41:42 +01:00 committed by Scott Boggs
parent 21dd421656
commit dbbdb8e5c0
3 changed files with 17 additions and 4 deletions

View File

@ -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),

View File

@ -48,8 +48,11 @@ pub fn to_vec(data: &Data) -> Result<Vec<u8>> {
pub fn to_writer<W: Write>(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

View File

@ -48,8 +48,11 @@ pub fn to_vec(data: &Data) -> Result<Vec<u8>> {
pub fn to_writer<W: Write>(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