1111
1212use std:: cmp:: { Ord , Ordering } ;
1313use std:: error:: Error as StdError ;
14+ use std:: io;
15+
16+ use either:: Either ;
1417
1518/// A boxed `Send + Sync + 'static` error.
1619pub 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