|
| 1 | +use crate::BaseEncoder; |
| 2 | +use crate::ByteEncoder; |
| 3 | +use std::io::Write; |
| 4 | + |
| 5 | +/// An encoder that adapts [`std::io::Write`] to the [`BaseEncoder`] and [`ByteEncoder`] traits. |
| 6 | +/// |
| 7 | +/// This encoder allows you to write encoded data directly to any type that implements |
| 8 | +/// [`std::io::Write`], such as a file or network stream. |
| 9 | +/// |
| 10 | +/// # Example |
| 11 | +/// |
| 12 | +/// ``` |
| 13 | +/// use encode::Encodable; |
| 14 | +/// use encode::encoders::IoEncoder; |
| 15 | +/// |
| 16 | +/// let mut encoder = IoEncoder(std::io::stdout().lock()); |
| 17 | +/// (b"hello, world!", 0u8).encode(&mut encoder).unwrap(); |
| 18 | +/// ``` |
| 19 | +#[repr(transparent)] |
| 20 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)] |
| 21 | +pub struct IoEncoder<W>(pub W); |
| 22 | + |
| 23 | +impl<W> core::convert::AsRef<W> for IoEncoder<W> { |
| 24 | + #[inline] |
| 25 | + fn as_ref(&self) -> &W { |
| 26 | + &self.0 |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +impl<W> core::convert::AsMut<W> for IoEncoder<W> { |
| 31 | + #[inline] |
| 32 | + fn as_mut(&mut self) -> &mut W { |
| 33 | + &mut self.0 |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +impl<W> core::borrow::Borrow<W> for IoEncoder<W> { |
| 38 | + #[inline] |
| 39 | + fn borrow(&self) -> &W { |
| 40 | + &self.0 |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl<W> core::borrow::BorrowMut<W> for IoEncoder<W> { |
| 45 | + #[inline] |
| 46 | + fn borrow_mut(&mut self) -> &mut W { |
| 47 | + &mut self.0 |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl<W> core::ops::Deref for IoEncoder<W> { |
| 52 | + type Target = W; |
| 53 | + |
| 54 | + #[inline] |
| 55 | + fn deref(&self) -> &Self::Target { |
| 56 | + &self.0 |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +impl<W> core::ops::DerefMut for IoEncoder<W> { |
| 61 | + #[inline] |
| 62 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 63 | + &mut self.0 |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl<W> BaseEncoder for IoEncoder<W> |
| 68 | +where |
| 69 | + W: Write, |
| 70 | +{ |
| 71 | + type Error = std::io::Error; |
| 72 | +} |
| 73 | + |
| 74 | +impl<W> ByteEncoder for IoEncoder<W> |
| 75 | +where |
| 76 | + W: Write, |
| 77 | +{ |
| 78 | + #[inline] |
| 79 | + fn put_slice(&mut self, slice: &[u8]) -> Result<(), Self::Error> { |
| 80 | + self.0.write_all(slice) |
| 81 | + } |
| 82 | + |
| 83 | + #[inline] |
| 84 | + fn put_byte(&mut self, byte: u8) -> Result<(), Self::Error> { |
| 85 | + self.0.write_all(&[byte] as &[u8]) |
| 86 | + } |
| 87 | +} |
0 commit comments