1use crate::{Error, Reader, Result, compact::vlen};
4use serde::de::{self, Visitor};
5
6pub mod access;
7
8pub struct Deserializer<'de> {
10 pub(crate) input: &'de [u8],
11 pub(crate) index: usize,
12}
13
14impl<'de> Deserializer<'de> {
15 pub fn new(input: &'de [u8]) -> Self {
17 Self { input, index: 0 }
18 }
19
20 fn peek_byte(&self) -> Result<u8> {
21 self.input.get(self.index).copied().ok_or_else(|| {
22 anyhow::anyhow!("Failed to peek bytes, EOF: index: {}", self.index).into()
23 })
24 }
25
26 pub fn next_byte(&mut self) -> Result<u8> {
28 let byte = self.peek_byte()?;
29 self.index += 1;
30 Ok(byte)
31 }
32
33 pub fn next_bytes(&mut self, len: usize) -> Result<&'de [u8]> {
35 if self.index + len > self.input.len() {
36 return Err(anyhow::anyhow!(
37 "failed to get the next bytes: EOF: index: {}, len: {}, buffer length: {}",
38 self.index,
39 len,
40 self.input.len()
41 )
42 .into());
43 }
44 let bytes = &self.input[self.index..self.index + len];
45 self.index += len;
46 Ok(bytes)
47 }
48}
49
50impl<'de> de::Deserializer<'de> for &mut Deserializer<'de> {
51 type Error = Error;
52
53 fn is_human_readable(&self) -> bool {
54 false
55 }
56
57 fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
58 where
59 V: Visitor<'de>,
60 {
61 visitor.visit_bool(self.next_byte()? != 0)
62 }
63
64 fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
65 where
66 V: Visitor<'de>,
67 {
68 visitor.visit_i8(self.next_byte()? as i8)
69 }
70
71 fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
72 where
73 V: Visitor<'de>,
74 {
75 let value = self.next_byte()?;
76 visitor.visit_u8(value)
77 }
78
79 fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
80 where
81 V: Visitor<'de>,
82 {
83 let bytes = self.next_bytes(2)?;
84 visitor.visit_i16(i16::from_le_bytes(
85 bytes
86 .try_into()
87 .map_err(|_| anyhow::anyhow!("invalid i16"))?,
88 ))
89 }
90
91 fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
92 where
93 V: Visitor<'de>,
94 {
95 let bytes = self.next_bytes(2)?;
96 visitor.visit_u16(u16::from_le_bytes(
97 bytes
98 .try_into()
99 .map_err(|_| anyhow::anyhow!("invalid u16"))?,
100 ))
101 }
102
103 fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
104 where
105 V: Visitor<'de>,
106 {
107 let bytes = self.next_bytes(4)?;
108 visitor.visit_i32(i32::from_le_bytes(
109 bytes
110 .try_into()
111 .map_err(|_| anyhow::anyhow!("invalid i32"))?,
112 ))
113 }
114
115 fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
116 where
117 V: Visitor<'de>,
118 {
119 let bytes = self.next_bytes(4)?;
120 visitor.visit_u32(u32::from_le_bytes(
121 bytes
122 .try_into()
123 .map_err(|_| anyhow::anyhow!("invalid u32"))?,
124 ))
125 }
126
127 fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
128 where
129 V: Visitor<'de>,
130 {
131 let bytes = self.next_bytes(8)?;
132 visitor.visit_i64(i64::from_le_bytes(
133 bytes
134 .try_into()
135 .map_err(|_| anyhow::anyhow!("invalid i64"))?,
136 ))
137 }
138
139 fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
140 where
141 V: Visitor<'de>,
142 {
143 let bytes = self.next_bytes(8)?;
144 visitor.visit_u64(u64::from_le_bytes(
145 bytes
146 .try_into()
147 .map_err(|_| anyhow::anyhow!("invalid u64"))?,
148 ))
149 }
150
151 fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
152 where
153 V: Visitor<'de>,
154 {
155 let bytes = self.next_bytes(4)?;
156 visitor.visit_f32(f32::from_le_bytes(
157 bytes
158 .try_into()
159 .map_err(|_| anyhow::anyhow!("invalid f32"))?,
160 ))
161 }
162
163 fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>
164 where
165 V: Visitor<'de>,
166 {
167 let bytes = self.next_bytes(8)?;
168 visitor.visit_f64(f64::from_le_bytes(
169 bytes
170 .try_into()
171 .map_err(|_| anyhow::anyhow!("invalid f64"))?,
172 ))
173 }
174
175 fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
176 where
177 V: Visitor<'de>,
178 {
179 visitor.visit_char(self.next_byte()? as char)
180 }
181
182 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
183 where
184 V: Visitor<'de>,
185 {
186 let len = self
188 .read_var()
189 .ok_or_else(|| anyhow::anyhow!("EOF while reading string length"))?
190 as usize;
191 let bytes = self.next_bytes(len)?;
192 let s = core::str::from_utf8(bytes).map_err(|_| anyhow::anyhow!("invalid utf-8"))?;
193 visitor.visit_borrowed_str(s)
194 }
195
196 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
197 where
198 V: Visitor<'de>,
199 {
200 self.deserialize_str(visitor)
201 }
202
203 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
205 where
206 V: Visitor<'de>,
207 {
208 let length = self
209 .read_var()
210 .ok_or_else(|| anyhow::anyhow!("EOF while reading variable length"))?
211 as usize;
212 let bytes = self.next_bytes(length)?;
213 visitor.visit_borrowed_bytes(bytes)
214 }
215
216 fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
218 where
219 V: Visitor<'de>,
220 {
221 let prefix = self.peek_byte()?;
222 if prefix < 0x80 {
223 let data = self.next_byte()?;
224 visitor.visit_u64(data as u64)
225 } else {
226 let (value, length) = vlen::decode_from(&self.input[self.index..]);
227 self.index += length;
228 visitor.visit_u64(value)
229 }
230 }
231
232 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
233 where
234 V: Visitor<'de>,
235 {
236 match self.next_byte()? {
237 0 => visitor.visit_none(),
238 1 => visitor.visit_some(self),
239 _ => Err(anyhow::anyhow!("invalid option").into()),
240 }
241 }
242
243 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
244 where
245 V: Visitor<'de>,
246 {
247 visitor.visit_unit()
248 }
249
250 fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
251 where
252 V: Visitor<'de>,
253 {
254 self.deserialize_unit(visitor)
255 }
256
257 fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
258 where
259 V: Visitor<'de>,
260 {
261 visitor.visit_newtype_struct(self)
262 }
263
264 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
265 where
266 V: Visitor<'de>,
267 {
268 let len = self
269 .read_var()
270 .ok_or_else(|| anyhow::anyhow!("EOF while reading variable length"))?
271 as usize;
272 visitor.visit_seq(access::SeqAccess::new(self, len))
273 }
274
275 fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value>
276 where
277 V: Visitor<'de>,
278 {
279 visitor.visit_seq(access::SeqAccess::new(self, len))
280 }
281
282 fn deserialize_tuple_struct<V>(
283 self,
284 _name: &'static str,
285 len: usize,
286 visitor: V,
287 ) -> Result<V::Value>
288 where
289 V: Visitor<'de>,
290 {
291 visitor.visit_seq(access::SeqAccess::new(self, len))
292 }
293
294 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
295 where
296 V: Visitor<'de>,
297 {
298 let len = self
299 .read_var()
300 .ok_or_else(|| anyhow::anyhow!("EOF while reading variable length"))?
301 as usize;
302 visitor.visit_map(access::MapAccess::new(self, len))
303 }
304
305 fn deserialize_struct<V>(
306 self,
307 _name: &'static str,
308 _fields: &'static [&'static str],
309 visitor: V,
310 ) -> Result<V::Value>
311 where
312 V: Visitor<'de>,
313 {
314 visitor.visit_seq(access::SeqAccess::new(self, _fields.len()))
315 }
316
317 fn deserialize_enum<V>(
318 self,
319 _name: &'static str,
320 _variants: &'static [&'static str],
321 visitor: V,
322 ) -> Result<V::Value>
323 where
324 V: Visitor<'de>,
325 {
326 let variant = self.next_byte()?;
327 visitor.visit_enum(access::EnumAccess::new(self, variant))
328 }
329
330 fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value>
331 where
332 V: Visitor<'de>,
333 {
334 Err(anyhow::anyhow!("As bytecode format, identifier is not supported").into())
335 }
336
337 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
338 where
339 V: Visitor<'de>,
340 {
341 visitor.visit_seq(access::SeqAccess::new(self, 0))
342 }
343
344 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
345 where
346 V: Visitor<'de>,
347 {
348 self.deserialize_any(visitor)
349 }
350}
351
352impl Reader for Deserializer<'_> {
353 fn read_var(&mut self) -> Option<u32> {
354 if self.index >= self.input.len() {
355 return None;
356 }
357
358 let (value, length) = vlen::decode_from(&self.input[self.index..]);
359 self.index += length;
360 Some(value as u32)
361 }
362
363 fn read_u32(&mut self) -> Option<u32> {
364 let bytes = self.next_bytes(4).ok()?;
365 Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
366 }
367
368 fn read_u24(&mut self) -> Option<u32> {
369 let bytes = self.next_bytes(3).ok()?;
370 Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], 0]))
371 }
372
373 fn read_u16(&mut self) -> Option<u16> {
374 let bytes = self.next_bytes(2).ok()?;
375 Some(u16::from_le_bytes([bytes[0], bytes[1]]))
376 }
377
378 fn read_u8(&mut self) -> Option<u8> {
379 self.next_byte().ok()
380 }
381}