Skip to content

Commit a5c96f1

Browse files
committed
allow all std::io::Write impls in bytes_encode_into_writer instead of only Vec<u8>, use Either for the 2 different errors
1 parent 08ca164 commit a5c96f1

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

heed-traits/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ readme = "../README.md"
99
edition = "2021"
1010

1111
[dependencies]
12+
either = "1.13.0"

heed-traits/src/lib.rs

+21-7
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111

1212
use std::cmp::{Ord, Ordering};
1313
use std::error::Error as StdError;
14+
use std::io;
15+
16+
use either::Either;
1417

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

32-
/// Encode the given item as bytes and write it into the writer. This function by default
33-
/// forwards to `bytes_encode`.
34-
fn bytes_encode_into_writer(
35+
/// Encode the given item as bytes and write it into the writer. Returns the amount of bytes
36+
/// that were written. This function by default forwards to
37+
/// [`bytes_encode`][BytesEncode::bytes_encode].
38+
///
39+
/// # Errors
40+
///
41+
/// [`Either`] is used to handle the 2 different errors this function can return.
42+
/// [`Either::Left`] is used for errors from [`bytes_encode`][BytesEncode::bytes_encode] and
43+
/// [`Either::Right`] is used for errors from the writer (I/O errors).
44+
fn bytes_encode_into_writer<W: io::Write>(
3545
item: &'a Self::EItem,
36-
writer: &mut Vec<u8>,
37-
) -> Result<(), Self::Error> {
38-
writer.extend_from_slice(Self::bytes_encode(item)?.as_ref());
39-
Ok(())
46+
writer: &mut W,
47+
) -> Result<usize, Either<Self::Error, io::Error>> {
48+
let bytes = Self::bytes_encode(item).map_err(Either::Left)?;
49+
let bytes = bytes.as_ref();
50+
51+
writer.write_all(bytes).map_err(Either::Right)?;
52+
53+
Ok(bytes.len())
4054
}
4155
}
4256

0 commit comments

Comments
 (0)