Skip to content

Commit

Permalink
allow all std::io::Write impls in bytes_encode_into_writer instead of…
Browse files Browse the repository at this point in the history
… only Vec<u8>, use Either for the 2 different errors
  • Loading branch information
antonilol committed Aug 18, 2024
1 parent 08ca164 commit a5c96f1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
1 change: 1 addition & 0 deletions heed-traits/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ readme = "../README.md"
edition = "2021"

[dependencies]
either = "1.13.0"
28 changes: 21 additions & 7 deletions heed-traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

use std::cmp::{Ord, Ordering};
use std::error::Error as StdError;
use std::io;

use either::Either;

/// A boxed `Send + Sync + 'static` error.
pub type BoxedError = Box<dyn StdError + Send + Sync + 'static>;
Expand All @@ -29,14 +32,25 @@ pub trait BytesEncode<'a> {
/// Encode the given item as bytes.
fn bytes_encode(item: &'a Self::EItem) -> Result<Self::ReturnBytes, Self::Error>;

/// Encode the given item as bytes and write it into the writer. This function by default
/// forwards to `bytes_encode`.
fn bytes_encode_into_writer(
/// Encode the given item as bytes and write it into the writer. Returns the amount of bytes
/// that were written. This function by default forwards to
/// [`bytes_encode`][BytesEncode::bytes_encode].
///
/// # Errors
///
/// [`Either`] is used to handle the 2 different errors this function can return.
/// [`Either::Left`] is used for errors from [`bytes_encode`][BytesEncode::bytes_encode] and
/// [`Either::Right`] is used for errors from the writer (I/O errors).
fn bytes_encode_into_writer<W: io::Write>(
item: &'a Self::EItem,
writer: &mut Vec<u8>,
) -> Result<(), Self::Error> {
writer.extend_from_slice(Self::bytes_encode(item)?.as_ref());
Ok(())
writer: &mut W,
) -> Result<usize, Either<Self::Error, io::Error>> {
let bytes = Self::bytes_encode(item).map_err(Either::Left)?;
let bytes = bytes.as_ref();

writer.write_all(bytes).map_err(Either::Right)?;

Ok(bytes.len())
}
}

Expand Down

0 comments on commit a5c96f1

Please sign in to comment.