Skip to main content

tuwunel_database/
ser.rs

1use std::{io::Write, mem::replace};
2
3use serde::{Deserialize, Serialize, ser};
4use tuwunel_core::{Error, Result, debug::type_name, err, result::DebugInspect, unhandled};
5
6#[inline]
7pub fn serialize_to_vec<T: Serialize>(val: T) -> Result<Vec<u8>> {
8	serialize_to::<Vec<u8>, T>(val)
9}
10
11#[inline]
12pub fn serialize_to<B, T>(val: T) -> Result<B>
13where
14	B: Default + Write + AsRef<[u8]>,
15	T: Serialize,
16{
17	let mut buf = B::default();
18	serialize(&mut buf, val)?;
19
20	Ok(buf)
21}
22
23/// Serialize T into Writer W
24#[inline]
25#[cfg_attr(unabridged, tracing::instrument(level = "trace", skip_all))]
26pub fn serialize<'a, W, T>(out: &'a mut W, val: T) -> Result<&'a [u8]>
27where
28	W: Write + AsRef<[u8]> + 'a,
29	T: Serialize,
30{
31	let mut serializer = Serializer { out, depth: 0, sep: false, fin: false };
32
33	val.serialize(&mut serializer)
34		.map_err(|error| err!(SerdeSer("{error}")))
35		.debug_inspect(|()| {
36			debug_assert_eq!(
37				serializer.depth, 0,
38				"Serialization completed at non-zero recursion level"
39			);
40		})?;
41
42	Ok((*out).as_ref())
43}
44
45pub(crate) struct Serializer<'a, W: Write> {
46	out: &'a mut W,
47	depth: u32,
48	sep: bool,
49	fin: bool,
50}
51
52/// Newtype for JSON serialization.
53#[derive(Debug, Deserialize, Serialize)]
54pub struct Json<T>(pub T);
55
56/// Newtype for CBOR serialization.
57#[derive(Debug, Deserialize, Serialize)]
58pub struct Cbor<T>(pub T);
59
60/// Directive to force separator serialization specifically for prefix keying
61/// use. This is a quirk of the database schema and prefix iterations.
62#[derive(Debug, Serialize)]
63pub struct Interfix;
64
65/// Directive to force separator serialization. Separators are usually
66/// serialized automatically.
67#[derive(Debug, Serialize)]
68pub struct Separator;
69
70/// Record separator; an intentionally invalid-utf8 byte.
71pub const SEP: u8 = b'\xFF';
72
73impl<W: Write> Serializer<'_, W> {
74	const SEP: &'static [u8] = &[SEP];
75
76	fn tuple_start(&mut self) {
77		debug_assert!(!self.sep, "Tuple start with separator set");
78		self.sequence_start();
79	}
80
81	fn tuple_end(&mut self) -> Result {
82		self.sequence_end()?;
83		Ok(())
84	}
85
86	fn sequence_start(&mut self) {
87		debug_assert!(!self.is_finalized(), "Sequence start with finalization set");
88		cfg!(debug_assertions).then(|| self.depth = self.depth.saturating_add(1));
89		self.sep = false;
90	}
91
92	fn sequence_end(&mut self) -> Result {
93		cfg!(debug_assertions).then(|| self.depth = self.depth.saturating_sub(1));
94		self.sep = false;
95		Ok(())
96	}
97
98	fn record_start(&mut self) -> Result {
99		debug_assert!(!self.is_finalized(), "Starting a record after serialization finalized");
100		replace(&mut self.sep, true)
101			.then(|| self.separator())
102			.unwrap_or(Ok(()))
103	}
104
105	fn separator(&mut self) -> Result {
106		debug_assert!(!self.is_finalized(), "Writing a separator after serialization finalized");
107		self.out.write_all(Self::SEP).map_err(Into::into)
108	}
109
110	fn write(&mut self, buf: &[u8]) -> Result { self.out.write_all(buf).map_err(Into::into) }
111
112	fn set_finalized(&mut self) {
113		debug_assert!(!self.is_finalized(), "Finalization already set");
114		cfg!(debug_assertions).then(|| self.fin = true);
115	}
116
117	fn is_finalized(&self) -> bool { self.fin }
118}
119
120impl<W: Write> ser::Serializer for &mut Serializer<'_, W> {
121	type Error = Error;
122	type Ok = ();
123	type SerializeMap = Self;
124	type SerializeSeq = Self;
125	type SerializeStruct = Self;
126	type SerializeStructVariant = Self;
127	type SerializeTuple = Self;
128	type SerializeTupleStruct = Self;
129	type SerializeTupleVariant = Self;
130
131	fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
132		self.sequence_start();
133		Ok(self)
134	}
135
136	fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
137		self.tuple_start();
138		Ok(self)
139	}
140
141	fn serialize_tuple_struct(
142		self,
143		_name: &'static str,
144		_len: usize,
145	) -> Result<Self::SerializeTupleStruct> {
146		self.tuple_start();
147		Ok(self)
148	}
149
150	fn serialize_tuple_variant(
151		self,
152		_name: &'static str,
153		_idx: u32,
154		_var: &'static str,
155		_len: usize,
156	) -> Result<Self::SerializeTupleVariant> {
157		unhandled!("serialize Tuple Variant not implemented")
158	}
159
160	fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
161		unhandled!(
162			"serialize Map not implemented; did you mean to use database::Json() around your \
163			 serde_json::Value?"
164		)
165	}
166
167	fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
168		unhandled!(
169			"serialize Struct not implemented at this time; did you mean to use \
170			 database::Json() around your struct?"
171		)
172	}
173
174	fn serialize_struct_variant(
175		self,
176		_name: &'static str,
177		_idx: u32,
178		_var: &'static str,
179		_len: usize,
180	) -> Result<Self::SerializeStructVariant> {
181		unhandled!("serialize Struct Variant not implemented")
182	}
183
184	fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<Self::Ok>
185	where
186		T: Serialize + ?Sized,
187	{
188		debug_assert!(
189			name != "Json" || type_name::<T>() != "alloc::boxed::Box<serde_json::raw::RawValue>",
190			"serializing a Json(RawValue); you can skip serialization instead"
191		);
192
193		match name {
194			| "Json" => serde_json::to_writer(&mut self.out, value).map_err(Into::into),
195			| "Cbor" => {
196				use minicbor::encode::write::Writer;
197				use minicbor_serde::Serializer;
198
199				value
200					.serialize(&mut Serializer::new(&mut Writer::new(&mut self.out)))
201					.map_err(|e| Self::Error::SerdeSer(e.to_string().into()))
202			},
203			| _ => unhandled!("Unrecognized serialization Newtype {name:?}"),
204		}
205	}
206
207	fn serialize_newtype_variant<T: Serialize + ?Sized>(
208		self,
209		_name: &'static str,
210		_idx: u32,
211		_var: &'static str,
212		_value: &T,
213	) -> Result<Self::Ok> {
214		unhandled!("serialize Newtype Variant not implemented")
215	}
216
217	fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok> {
218		match name {
219			| "Interfix" => {
220				self.set_finalized();
221			},
222			| "Separator" => {
223				self.separator()?;
224			},
225			| _ => unhandled!("Unrecognized serialization directive: {name:?}"),
226		}
227
228		Ok(())
229	}
230
231	fn serialize_unit_variant(
232		self,
233		_name: &'static str,
234		_idx: u32,
235		_var: &'static str,
236	) -> Result<Self::Ok> {
237		unhandled!("serialize Unit Variant not implemented")
238	}
239
240	fn serialize_some<T: Serialize + ?Sized>(self, val: &T) -> Result<Self::Ok> {
241		val.serialize(self)
242	}
243
244	fn serialize_none(self) -> Result<Self::Ok> { Ok(()) }
245
246	fn serialize_char(self, v: char) -> Result<Self::Ok> {
247		let mut buf: [u8; 4] = [0; 4];
248		self.serialize_str(v.encode_utf8(&mut buf))
249	}
250
251	fn serialize_str(self, v: &str) -> Result<Self::Ok> {
252		debug_assert!(
253			self.depth > 0,
254			"serializing string at the top-level; you can skip serialization instead"
255		);
256
257		self.serialize_bytes(v.as_bytes())
258	}
259
260	fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok> {
261		debug_assert!(
262			self.depth > 0,
263			"serializing byte array at the top-level; you can skip serialization instead"
264		);
265
266		self.write(v).inspect(|()| self.sep = true)
267	}
268
269	fn serialize_f64(self, _v: f64) -> Result<Self::Ok> {
270		unhandled!("serialize f64 not implemented")
271	}
272
273	fn serialize_f32(self, _v: f32) -> Result<Self::Ok> {
274		unhandled!("serialize f32 not implemented")
275	}
276
277	fn serialize_i64(self, v: i64) -> Result<Self::Ok> {
278		self.write(&v.to_be_bytes())
279			.inspect(|()| self.sep = false)
280	}
281
282	fn serialize_i32(self, v: i32) -> Result<Self::Ok> {
283		self.write(&v.to_be_bytes())
284			.inspect(|()| self.sep = false)
285	}
286
287	fn serialize_i16(self, _v: i16) -> Result<Self::Ok> {
288		unhandled!("serialize i16 not implemented")
289	}
290
291	fn serialize_i8(self, _v: i8) -> Result<Self::Ok> {
292		unhandled!("serialize i8 not implemented")
293	}
294
295	fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
296		self.write(&v.to_be_bytes())
297			.inspect(|()| self.sep = false)
298	}
299
300	fn serialize_u32(self, v: u32) -> Result<Self::Ok> {
301		self.write(&v.to_be_bytes())
302			.inspect(|()| self.sep = false)
303	}
304
305	fn serialize_u16(self, _v: u16) -> Result<Self::Ok> {
306		unhandled!("serialize u16 not implemented")
307	}
308
309	fn serialize_u8(self, v: u8) -> Result<Self::Ok> {
310		self.write(&[v]).inspect(|()| self.sep = false)
311	}
312
313	fn serialize_bool(self, _v: bool) -> Result<Self::Ok> {
314		unhandled!("serialize bool not implemented")
315	}
316
317	fn serialize_unit(self) -> Result<Self::Ok> { unhandled!("serialize unit not implemented") }
318}
319
320impl<W: Write> ser::SerializeSeq for &mut Serializer<'_, W> {
321	type Error = Error;
322	type Ok = ();
323
324	fn serialize_element<T: Serialize + ?Sized>(&mut self, val: &T) -> Result<Self::Ok> {
325		self.record_start()?;
326		val.serialize(&mut **self)
327	}
328
329	fn end(self) -> Result<Self::Ok> { self.sequence_end() }
330}
331
332impl<W: Write> ser::SerializeTuple for &mut Serializer<'_, W> {
333	type Error = Error;
334	type Ok = ();
335
336	fn serialize_element<T: Serialize + ?Sized>(&mut self, val: &T) -> Result<Self::Ok> {
337		self.record_start()?;
338		val.serialize(&mut **self)
339			.inspect(|()| self.sep = true)
340	}
341
342	fn end(self) -> Result<Self::Ok> { self.tuple_end() }
343}
344
345impl<W: Write> ser::SerializeTupleStruct for &mut Serializer<'_, W> {
346	type Error = Error;
347	type Ok = ();
348
349	fn serialize_field<T: Serialize + ?Sized>(&mut self, val: &T) -> Result<Self::Ok> {
350		self.record_start()?;
351		val.serialize(&mut **self)
352			.inspect(|()| self.sep = true)
353	}
354
355	fn end(self) -> Result<Self::Ok> { self.tuple_end() }
356}
357
358impl<W: Write> ser::SerializeTupleVariant for &mut Serializer<'_, W> {
359	type Error = Error;
360	type Ok = ();
361
362	fn serialize_field<T: Serialize + ?Sized>(&mut self, val: &T) -> Result<Self::Ok> {
363		self.record_start()?;
364		val.serialize(&mut **self)
365			.inspect(|()| self.sep = true)
366	}
367
368	fn end(self) -> Result<Self::Ok> { self.tuple_end() }
369}
370
371impl<W: Write> ser::SerializeMap for &mut Serializer<'_, W> {
372	type Error = Error;
373	type Ok = ();
374
375	fn serialize_key<T: Serialize + ?Sized>(&mut self, _key: &T) -> Result<Self::Ok> {
376		unhandled!("serialize Map Key not implemented")
377	}
378
379	fn serialize_value<T: Serialize + ?Sized>(&mut self, _val: &T) -> Result<Self::Ok> {
380		unhandled!("serialize Map Val not implemented")
381	}
382
383	fn end(self) -> Result<Self::Ok> { unhandled!("serialize Map End not implemented") }
384}
385
386impl<W: Write> ser::SerializeStruct for &mut Serializer<'_, W> {
387	type Error = Error;
388	type Ok = ();
389
390	fn serialize_field<T: Serialize + ?Sized>(
391		&mut self,
392		_key: &'static str,
393		_val: &T,
394	) -> Result<Self::Ok> {
395		unhandled!("serialize Struct Field not implemented")
396	}
397
398	fn end(self) -> Result<Self::Ok> { unhandled!("serialize Struct End not implemented") }
399}
400
401impl<W: Write> ser::SerializeStructVariant for &mut Serializer<'_, W> {
402	type Error = Error;
403	type Ok = ();
404
405	fn serialize_field<T: Serialize + ?Sized>(
406		&mut self,
407		_key: &'static str,
408		_val: &T,
409	) -> Result<Self::Ok> {
410		unhandled!("serialize Struct Variant Field not implemented")
411	}
412
413	fn end(self) -> Result<Self::Ok> {
414		unhandled!("serialize Struct Variant End not implemented")
415	}
416}