| 1 |
//! This module contains writer-based structs and traits. |
| 2 |
//! |
| 3 |
//! Because `std::io::Write` is only limited to `std` and not `core`, we provide our own [Writer]. |
| 4 |
|
| 5 |
use crate::error::EncodeError; |
| 6 |
|
| 7 |
/// Trait that indicates that a struct can be used as a destination to encode data too. This is used by [Encode] |
| 8 |
/// |
| 9 |
/// [Encode]: ../trait.Encode.html |
| 10 |
pub trait Writer { |
| 11 |
/// Write `bytes` to the underlying writer. Exactly `bytes.len()` bytes must be written, or else an error should be returned. |
| 12 |
fn write(&mut self, bytes: &[u8]) -> Result<(), EncodeError>; |
| 13 |
} |
| 14 |
|
| 15 |
impl<T: Writer> Writer for &mut T { |
| 16 |
#[inline] |
| 17 |
fn write(&mut self, bytes: &[u8]) -> Result<(), EncodeError> { |
| 18 |
(**self).write(bytes) |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
/// A helper struct that implements `Writer` for a `&[u8]` slice. |
| 23 |
/// |
| 24 |
/// ``` |
| 25 |
/// use bincode::enc::write::{Writer, SliceWriter}; |
| 26 |
/// |
| 27 |
/// let destination = &mut [0u8; 100]; |
| 28 |
/// let mut writer = SliceWriter::new(destination); |
| 29 |
/// writer.write(&[1, 2, 3, 4, 5]).unwrap(); |
| 30 |
/// |
| 31 |
/// assert_eq!(writer.bytes_written(), 5); |
| 32 |
/// assert_eq!(destination[0..6], [1, 2, 3, 4, 5, 0]); |
| 33 |
/// ``` |
| 34 |
pub struct SliceWriter<'storage> { |
| 35 |
slice: &'storage mut [u8], |
| 36 |
original_length: usize, |
| 37 |
} |
| 38 |
|
| 39 |
impl<'storage> SliceWriter<'storage> { |
| 40 |
/// Create a new instance of `SliceWriter` with the given byte array. |
| 41 |
pub fn new(bytes: &'storage mut [u8]) -> SliceWriter<'storage> { |
| 42 |
let original = bytes.len(); |
| 43 |
SliceWriter { |
| 44 |
slice: bytes, |
| 45 |
original_length: original, |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
/// Return the amount of bytes written so far. |
| 50 |
pub fn bytes_written(&self) -> usize { |
| 51 |
self.original_length - self.slice.len() |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
impl Writer for SliceWriter<'_> { |
| 56 |
#[inline(always)] |
| 57 |
fn write(&mut self, bytes: &[u8]) -> Result<(), EncodeError> { |
| 58 |
if bytes.len() > self.slice.len() { |
| 59 |
return Err(EncodeError::UnexpectedEnd); |
| 60 |
} |
| 61 |
let (a, b) = core::mem::take(&mut self.slice).split_at_mut(bytes.len()); |
| 62 |
a.copy_from_slice(bytes); |
| 63 |
self.slice = b; |
| 64 |
|
| 65 |
Ok(()) |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
/// A writer that counts how many bytes were written. This is useful for e.g. pre-allocating buffers bfeore writing to them. |
| 70 |
#[derive(Default)] |
| 71 |
pub struct SizeWriter { |
| 72 |
/// the amount of bytes that were written so far |
| 73 |
pub bytes_written: usize, |
| 74 |
} |
| 75 |
impl Writer for SizeWriter { |
| 76 |
#[inline(always)] |
| 77 |
fn write(&mut self, bytes: &[u8]) -> Result<(), EncodeError> { |
| 78 |
self.bytes_written += bytes.len(); |
| 79 |
|
| 80 |
Ok(()) |
| 81 |
} |
| 82 |
} |