11
11
12
12
use std:: cmp:: { Ord , Ordering } ;
13
13
use std:: error:: Error as StdError ;
14
+ use std:: io;
15
+
16
+ use either:: Either ;
14
17
15
18
/// A boxed `Send + Sync + 'static` error.
16
19
pub type BoxedError = Box < dyn StdError + Send + Sync + ' static > ;
@@ -29,14 +32,25 @@ pub trait BytesEncode<'a> {
29
32
/// Encode the given item as bytes.
30
33
fn bytes_encode ( item : & ' a Self :: EItem ) -> Result < Self :: ReturnBytes , Self :: Error > ;
31
34
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 > (
35
45
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 ( ) )
40
54
}
41
55
}
42
56
0 commit comments