musli_binary_common/
writer.rs1use core::fmt;
6
7use musli::error::Error;
8
9pub trait Writer {
11 type Error: Error;
13
14 fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
16
17 #[inline]
19 fn write_byte(&mut self, b: u8) -> Result<(), Self::Error> {
20 self.write_bytes(&[b])
21 }
22
23 #[inline]
25 fn write_array<const N: usize>(&mut self, array: [u8; N]) -> Result<(), Self::Error> {
26 self.write_bytes(&array)
27 }
28}
29
30impl<W> Writer for &mut W
31where
32 W: ?Sized + Writer,
33{
34 type Error = W::Error;
35
36 #[inline]
37 fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
38 (*self).write_bytes(bytes)
39 }
40
41 #[inline]
42 fn write_byte(&mut self, b: u8) -> Result<(), Self::Error> {
43 (*self).write_byte(b)
44 }
45
46 #[inline]
47 fn write_array<const N: usize>(&mut self, array: [u8; N]) -> Result<(), Self::Error> {
48 (*self).write_array(array)
49 }
50}
51
52decl_message_repr!(VecWriterErrorRepr, "failed to write to vector");
53
54#[derive(Debug)]
56pub struct VecWriterError(VecWriterErrorRepr);
57
58impl fmt::Display for VecWriterError {
59 #[inline]
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 self.0.fmt(f)
62 }
63}
64
65impl Error for VecWriterError {
66 #[inline]
67 fn custom<T>(message: T) -> Self
68 where
69 T: 'static + Send + Sync + fmt::Display + fmt::Debug,
70 {
71 Self(VecWriterErrorRepr::collect(message))
72 }
73
74 #[inline]
75 fn message<T>(message: T) -> Self
76 where
77 T: fmt::Display,
78 {
79 Self(VecWriterErrorRepr::collect(message))
80 }
81}
82
83#[cfg(feature = "std")]
84impl std::error::Error for VecWriterError {}
85
86#[cfg(feature = "std")]
87impl Writer for Vec<u8> {
88 type Error = VecWriterError;
89
90 #[inline]
91 fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
92 self.extend_from_slice(bytes);
93 Ok(())
94 }
95
96 #[inline]
97 fn write_byte(&mut self, b: u8) -> Result<(), Self::Error> {
98 self.push(b);
99 Ok(())
100 }
101
102 #[inline]
103 fn write_array<const N: usize>(&mut self, array: [u8; N]) -> Result<(), Self::Error> {
104 self.extend_from_slice(&array[..]);
105 Ok(())
106 }
107}