#[cfg(feature = "heapless")]
pub use hvec::*;
use crate::{Error, Result};
use core::ops::{Deref, DerefMut};
pub trait Storage: Deref<Target = [u8]> + DerefMut<Target = [u8]> {
type Output;
#[inline]
fn try_extend(&mut self, data: &[u8]) -> Result<()> {
data.iter().try_for_each(|d| self.try_push(*d))
}
fn try_push(&mut self, data: u8) -> Result<()>;
fn finalize(self) -> Self::Output;
}
pub struct Slice<'a> {
buf: &'a mut [u8],
index: usize,
}
impl<'a> Slice<'a> {
pub fn new(buf: &'a mut [u8]) -> Self {
Self { buf, index: 0 }
}
}
impl<'a> Storage for Slice<'a> {
type Output = &'a mut [u8];
#[inline(always)]
fn try_push(&mut self, b: u8) -> Result<()> {
*self
.buf
.get_mut(self.index)
.ok_or(Error::RequestBufferFull)? = b;
self.index += 1;
Ok(())
}
fn finalize(self) -> Self::Output {
&mut self.buf[..self.index]
}
}
impl Deref for Slice<'_> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.buf[..self.index]
}
}
impl DerefMut for Slice<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.buf[..self.index]
}
}
#[cfg(feature = "heapless")]
mod hvec {
use super::*;
use heapless::Vec;
#[derive(Default)]
pub struct HVec<const N: usize>(Vec<u8, N>);
impl<const N: usize> HVec<N> {
pub fn new() -> Self {
Self::default()
}
}
impl<const N: usize> Storage for HVec<N> {
type Output = Vec<u8, N>;
#[inline(always)]
fn try_extend(&mut self, data: &[u8]) -> Result<()> {
self.0
.extend_from_slice(data)
.map_err(|_| Error::RequestBufferFull)
}
#[inline(always)]
fn try_push(&mut self, data: u8) -> Result<()> {
self.0.push(data).map_err(|_| Error::RequestBufferFull)
}
fn finalize(self) -> Self::Output {
self.0
}
}
impl<const N: usize> Deref for HVec<N> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl<const N: usize> DerefMut for HVec<N> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.deref_mut()
}
}
}