1use super::{
2 read::{BorrowReader, Reader},
3 BorrowDecoder, Decoder,
4};
5use crate::{config::Config, error::DecodeError, utils::Sealed};
6
7pub struct DecoderImpl<R, C: Config, Context> {
26 reader: R,
27 config: C,
28 bytes_read: usize,
29 context: Context,
30}
31
32impl<R: Reader, C: Config, Context> DecoderImpl<R, C, Context> {
33 pub fn new(reader: R, config: C, context: Context) -> DecoderImpl<R, C, Context> {
35 DecoderImpl {
36 reader,
37 config,
38 bytes_read: 0,
39 context,
40 }
41 }
42}
43
44impl<R, C: Config, Context> Sealed for DecoderImpl<R, C, Context> {}
45
46impl<'de, R: BorrowReader<'de>, C: Config, Context> BorrowDecoder<'de>
47 for DecoderImpl<R, C, Context>
48{
49 type BR = R;
50
51 fn borrow_reader(&mut self) -> &mut Self::BR {
52 &mut self.reader
53 }
54}
55
56impl<R: Reader, C: Config, Context> Decoder for DecoderImpl<R, C, Context> {
57 type R = R;
58
59 type C = C;
60 type Context = Context;
61
62 fn reader(&mut self) -> &mut Self::R {
63 &mut self.reader
64 }
65
66 fn config(&self) -> &Self::C {
67 &self.config
68 }
69
70 #[inline]
71 fn claim_bytes_read(&mut self, n: usize) -> Result<(), DecodeError> {
72 if let Some(limit) = C::LIMIT {
74 self.bytes_read = self
76 .bytes_read
77 .checked_add(n)
78 .ok_or(DecodeError::LimitExceeded)?;
79 if self.bytes_read > limit {
80 Err(DecodeError::LimitExceeded)
81 } else {
82 Ok(())
83 }
84 } else {
85 Ok(())
86 }
87 }
88
89 #[inline]
90 fn unclaim_bytes_read(&mut self, n: usize) {
91 if C::LIMIT.is_some() {
93 self.bytes_read -= n;
95 }
96 }
97
98 fn context(&mut self) -> &mut Self::Context {
99 &mut self.context
100 }
101}
102
103pub struct WithContext<'a, D: ?Sized, C> {
104 pub(crate) decoder: &'a mut D,
105 pub(crate) context: C,
106}
107
108impl<C, D: Decoder + ?Sized> Sealed for WithContext<'_, D, C> {}
109
110impl<Context, D: Decoder + ?Sized> Decoder for WithContext<'_, D, Context> {
111 type R = D::R;
112
113 type C = D::C;
114
115 type Context = Context;
116
117 fn context(&mut self) -> &mut Self::Context {
118 &mut self.context
119 }
120
121 fn reader(&mut self) -> &mut Self::R {
122 self.decoder.reader()
123 }
124
125 fn config(&self) -> &Self::C {
126 self.decoder.config()
127 }
128
129 fn claim_bytes_read(&mut self, n: usize) -> Result<(), DecodeError> {
130 self.decoder.claim_bytes_read(n)
131 }
132
133 fn unclaim_bytes_read(&mut self, n: usize) {
134 self.decoder.unclaim_bytes_read(n)
135 }
136}
137
138impl<'de, C, D: BorrowDecoder<'de>> BorrowDecoder<'de> for WithContext<'_, D, C> {
139 type BR = D::BR;
140 fn borrow_reader(&mut self) -> &mut Self::BR {
141 self.decoder.borrow_reader()
142 }
143}