Skip to main content

reifydb_core/util/encoding/keycode/
deserialize.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_type::{
5	Result,
6	error::{Error, TypeError},
7};
8use serde::de::{
9	DeserializeSeed, Deserializer as SerdeDeserializer, EnumAccess, IntoDeserializer, SeqAccess, VariantAccess,
10	Visitor,
11};
12
13use super::{decode_i64_varint, decode_u64_varint};
14
15pub(crate) struct Deserializer<'de> {
16	pub(crate) input: &'de [u8],
17}
18
19impl<'de> Deserializer<'de> {
20	pub fn from_bytes(input: &'de [u8]) -> Self {
21		Deserializer {
22			input,
23		}
24	}
25
26	fn take_bytes(&mut self, len: usize) -> Result<&[u8]> {
27		if self.input.len() < len {
28			return Err(Error::from(TypeError::SerdeKeycode {
29				message: format!("insufficient bytes, expected {len} bytes for {:x?}", self.input),
30			}));
31		}
32		let bytes = &self.input[..len];
33		self.input = &self.input[len..];
34		Ok(bytes)
35	}
36
37	fn decode_next_bytes(&mut self) -> Result<Vec<u8>> {
38		let mut decoded = Vec::new();
39		let mut iter = self.input.iter().enumerate();
40		let taken = loop {
41			match iter.next() {
42				Some((_, 0xff)) => match iter.next() {
43					Some((i, 0xff)) => break i + 1,
44					Some((_, 0x00)) => decoded.push(0xff),
45					_ => {
46						return Err(Error::from(TypeError::SerdeKeycode {
47							message: "invalid escape sequence".to_string(),
48						}));
49					}
50				},
51				Some((_, b)) => decoded.push(*b),
52				None => {
53					return Err(Error::from(TypeError::SerdeKeycode {
54						message: "unexpected end of input".to_string(),
55					}));
56				}
57			}
58		};
59		self.input = &self.input[taken..];
60		Ok(decoded)
61	}
62}
63
64impl<'de> SerdeDeserializer<'de> for &mut Deserializer<'de> {
65	type Error = Error;
66
67	fn deserialize_any<V: Visitor<'de>>(self, _: V) -> Result<V::Value> {
68		panic!("must provide type, Keycode is not self-describing")
69	}
70
71	fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
72		visitor.visit_bool(match self.take_bytes(1)?[0] {
73			0x01 => false,
74			0x00 => true,
75			b => {
76				return Err(Error::from(TypeError::SerdeKeycode {
77					message: format!("invalid boolean value {b}"),
78				}));
79			}
80		})
81	}
82
83	fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
84		let mut byte = self.take_bytes(1)?[0];
85		byte = !byte;
86		byte ^= 1 << 7;
87		visitor.visit_i8(byte as i8)
88	}
89
90	fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
91		let mut bytes = self.take_bytes(2)?.to_vec();
92		for b in &mut bytes {
93			*b = !*b;
94		}
95		bytes[0] ^= 1 << 7;
96		visitor.visit_i16(i16::from_be_bytes(bytes.as_slice().try_into()?))
97	}
98
99	fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
100		let mut bytes = self.take_bytes(4)?.to_vec();
101		for b in &mut bytes {
102			*b = !*b;
103		}
104		bytes[0] ^= 1 << 7;
105		visitor.visit_i32(i32::from_be_bytes(bytes.as_slice().try_into()?))
106	}
107
108	fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
109		let i = decode_i64_varint(&mut self.input)?;
110		visitor.visit_i64(i)
111	}
112
113	fn deserialize_i128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
114		let mut bytes = self.take_bytes(16)?.to_vec();
115		for b in &mut bytes {
116			*b = !*b;
117		}
118		bytes[0] ^= 1 << 7;
119		visitor.visit_i128(i128::from_be_bytes(bytes.as_slice().try_into()?))
120	}
121
122	fn deserialize_u8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
123		let byte = !self.take_bytes(1)?[0];
124		visitor.visit_u8(byte)
125	}
126
127	fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
128		let mut bytes = self.take_bytes(2)?.to_vec();
129		for b in &mut bytes {
130			*b = !*b;
131		}
132		visitor.visit_u16(u16::from_be_bytes(bytes.as_slice().try_into()?))
133	}
134
135	fn deserialize_u32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
136		let u = decode_u64_varint(&mut self.input)?;
137		visitor.visit_u32(u as u32)
138	}
139
140	fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
141		let u = decode_u64_varint(&mut self.input)?;
142		visitor.visit_u64(u)
143	}
144
145	fn deserialize_u128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
146		let mut bytes = self.take_bytes(16)?.to_vec();
147		for b in &mut bytes {
148			*b = !*b;
149		}
150		visitor.visit_u128(u128::from_be_bytes(bytes.as_slice().try_into()?))
151	}
152
153	fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
154		let mut bytes = self.take_bytes(4)?.to_vec();
155		for b in &mut bytes {
156			*b = !*b;
157		}
158		match bytes[0] >> 7 {
159			0 => bytes.iter_mut().for_each(|b| *b = !*b),
160			1 => bytes[0] ^= 1 << 7,
161			_ => panic!("bits can only be 0 or 1"),
162		}
163		visitor.visit_f32(f32::from_be_bytes(bytes.as_slice().try_into()?))
164	}
165
166	fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
167		let mut bytes = self.take_bytes(8)?.to_vec();
168		for b in &mut bytes {
169			*b = !*b;
170		}
171		match bytes[0] >> 7 {
172			0 => bytes.iter_mut().for_each(|b| *b = !*b),
173			1 => bytes[0] ^= 1 << 7,
174			_ => panic!("bits can only be 0 or 1"),
175		}
176		visitor.visit_f64(f64::from_be_bytes(bytes.as_slice().try_into()?))
177	}
178
179	fn deserialize_char<V: Visitor<'de>>(self, _: V) -> Result<V::Value> {
180		unimplemented!()
181	}
182
183	fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
184		let bytes = self.decode_next_bytes()?;
185		visitor.visit_str(&String::from_utf8(bytes)?)
186	}
187
188	fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
189		let bytes = self.decode_next_bytes()?;
190		visitor.visit_string(String::from_utf8(bytes)?)
191	}
192
193	fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
194		let bytes = self.decode_next_bytes()?;
195		visitor.visit_bytes(&bytes)
196	}
197
198	fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
199		let bytes = self.decode_next_bytes()?;
200		visitor.visit_byte_buf(bytes)
201	}
202
203	fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
204		match self.take_bytes(1)?[0] {
205			0x00 => visitor.visit_none(),
206			0x01 => visitor.visit_some(self),
207			b => Err(Error::from(TypeError::SerdeKeycode {
208				message: format!("invalid option marker byte 0x{:02x}", b),
209			})),
210		}
211	}
212
213	fn deserialize_unit<V: Visitor<'de>>(self, _: V) -> Result<V::Value> {
214		unimplemented!()
215	}
216
217	fn deserialize_unit_struct<V: Visitor<'de>>(self, _: &'static str, _: V) -> Result<V::Value> {
218		unimplemented!()
219	}
220
221	fn deserialize_newtype_struct<V: Visitor<'de>>(self, _: &'static str, _: V) -> Result<V::Value> {
222		unimplemented!()
223	}
224
225	fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
226		visitor.visit_seq(self)
227	}
228
229	fn deserialize_tuple<V: Visitor<'de>>(self, _: usize, visitor: V) -> Result<V::Value> {
230		visitor.visit_seq(self)
231	}
232
233	fn deserialize_tuple_struct<V: Visitor<'de>>(self, _: &'static str, _: usize, _: V) -> Result<V::Value> {
234		unimplemented!()
235	}
236
237	fn deserialize_map<V: Visitor<'de>>(self, _: V) -> Result<V::Value> {
238		unimplemented!()
239	}
240
241	fn deserialize_struct<V: Visitor<'de>>(
242		self,
243		_: &'static str,
244		_: &'static [&'static str],
245		_: V,
246	) -> Result<V::Value> {
247		unimplemented!()
248	}
249
250	fn deserialize_enum<V: Visitor<'de>>(
251		self,
252		_: &'static str,
253		_: &'static [&'static str],
254		visitor: V,
255	) -> Result<V::Value> {
256		visitor.visit_enum(self)
257	}
258
259	fn deserialize_identifier<V: Visitor<'de>>(self, _: V) -> Result<V::Value> {
260		unimplemented!()
261	}
262
263	fn deserialize_ignored_any<V: Visitor<'de>>(self, _: V) -> Result<V::Value> {
264		unimplemented!()
265	}
266}
267
268impl<'de> SeqAccess<'de> for Deserializer<'de> {
269	type Error = Error;
270
271	fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Value>> {
272		if self.input.is_empty() {
273			return Ok(None);
274		}
275		seed.deserialize(self).map(Some)
276	}
277}
278
279impl<'de> EnumAccess<'de> for &mut Deserializer<'de> {
280	type Error = Error;
281	type Variant = Self;
282
283	fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self::Variant)> {
284		let index = self.take_bytes(1)?[0] as u32;
285		let value: Result<_> = seed.deserialize(index.into_deserializer());
286		Ok((value?, self))
287	}
288}
289
290impl<'de> VariantAccess<'de> for &mut Deserializer<'de> {
291	type Error = Error;
292
293	fn unit_variant(self) -> Result<()> {
294		Ok(())
295	}
296
297	fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value> {
298		seed.deserialize(&mut *self)
299	}
300
301	fn tuple_variant<V: Visitor<'de>>(self, _: usize, visitor: V) -> Result<V::Value> {
302		visitor.visit_seq(self)
303	}
304
305	fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value> {
306		self.tuple_variant(fields.len(), visitor)
307	}
308}