use super::{BorrowDecoder, BorrowReader, Decoder, Reader};
use crate::{config::Config, error::Error, utils::Sealed};
pub struct DecoderImpl<R: Reader, C: Config, Ctx = ()> {
reader: R,
config: C,
context: Ctx,
bytes_claimed: usize,
}
impl<R: Reader, C: Config> DecoderImpl<R, C, ()> {
pub fn new(reader: R, config: C) -> Self {
Self {
reader,
config,
context: (),
bytes_claimed: 0,
}
}
}
impl<R: Reader, C: Config, Ctx> DecoderImpl<R, C, Ctx> {
pub fn with_context(reader: R, config: C, context: Ctx) -> Self {
Self {
reader,
config,
context,
bytes_claimed: 0,
}
}
#[inline]
pub fn into_reader(self) -> R {
self.reader
}
#[inline]
pub fn reader(&mut self) -> &mut R {
&mut self.reader
}
#[inline]
pub fn get_context(&self) -> &Ctx {
&self.context
}
#[inline]
pub fn get_context_mut(&mut self) -> &mut Ctx {
&mut self.context
}
}
impl<R: Reader, C: Config, Ctx> Decoder for DecoderImpl<R, C, Ctx> {
type R = R;
type C = C;
type Context = Ctx;
#[inline]
fn reader(&mut self) -> &mut Self::R {
&mut self.reader
}
#[inline]
fn config(&self) -> &Self::C {
&self.config
}
#[inline]
fn context(&mut self) -> &mut Self::Context {
&mut self.context
}
#[inline]
fn claim_bytes_read(&mut self, n: usize) -> Result<(), Error> {
if let Some(limit) = self.config.limit() {
let new_total = self.bytes_claimed.saturating_add(n);
if new_total > limit {
return Err(Error::LimitExceeded {
limit: limit as u64,
found: new_total as u64,
});
}
self.bytes_claimed = new_total;
}
Ok(())
}
#[inline]
fn unclaim_bytes_read(&mut self, n: usize) {
self.bytes_claimed = self.bytes_claimed.saturating_sub(n);
}
}
impl<R: Reader, C: Config, Ctx> Sealed for DecoderImpl<R, C, Ctx> {}
impl<'de, R, C: Config, Ctx> BorrowDecoder<'de> for DecoderImpl<R, C, Ctx>
where
R: BorrowReader<'de>,
{
type BR = R;
#[inline]
fn borrow_reader(&mut self) -> &mut Self::BR {
&mut self.reader
}
}