Optimize performance of slice writing

This commit is contained in:
Lena Hellström 2021-10-22 14:47:05 +02:00
parent 0be7e2f4f2
commit 539906f441
1 changed files with 10 additions and 8 deletions

View File

@ -26,33 +26,35 @@ pub trait Writer {
/// ``` /// ```
pub struct SliceWriter<'storage> { pub struct SliceWriter<'storage> {
slice: &'storage mut [u8], slice: &'storage mut [u8],
idx: usize, original_length: usize,
} }
impl<'storage> SliceWriter<'storage> { impl<'storage> SliceWriter<'storage> {
/// Create a new instance of `SliceWriter` with the given byte array. /// Create a new instance of `SliceWriter` with the given byte array.
pub fn new(bytes: &'storage mut [u8]) -> SliceWriter<'storage> { pub fn new(bytes: &'storage mut [u8]) -> SliceWriter<'storage> {
let original = bytes.len();
SliceWriter { SliceWriter {
slice: bytes, slice: bytes,
idx: 0, original_length: original,
} }
} }
/// Return the amount of bytes written so far. /// Return the amount of bytes written so far.
pub fn bytes_written(&self) -> usize { pub fn bytes_written(&self) -> usize {
self.idx self.original_length - self.slice.len()
} }
} }
impl<'storage> Writer for SliceWriter<'storage> { impl<'storage> Writer for SliceWriter<'storage> {
#[inline(always)]
fn write(&mut self, bytes: &[u8]) -> Result<(), EncodeError> { fn write(&mut self, bytes: &[u8]) -> Result<(), EncodeError> {
let remaining = &mut self.slice[self.idx..]; if bytes.len() > self.slice.len() {
if bytes.len() > remaining.len() {
return Err(EncodeError::UnexpectedEnd); return Err(EncodeError::UnexpectedEnd);
} }
self.idx += bytes.len(); let (a, b) = core::mem::replace(&mut self.slice, &mut []).split_at_mut(bytes.len());
let write_slice = &mut remaining[..bytes.len()]; a.copy_from_slice(&bytes[..]);
write_slice.copy_from_slice(bytes); self.slice = b;
Ok(()) Ok(())
} }
} }