Skip to main content

reifydb_core/util/encoding/keycode/
deserialize.rs

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