1use std::borrow::Cow;
4use {
5 crate::Object,
6 serde::{
7 ser::{self, Serialize as _, SerializeMap as _},
8 serde_if_integer128,
9 },
10 std::fmt::Debug,
11 wyz::Pipe as _,
12};
13
14#[derive(Debug)]
15pub enum Never {}
16impl std::fmt::Display for Never {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 Debug::fmt(self, f)
19 }
20}
21impl std::error::Error for Never {}
22impl ser::Error for Never {
23 fn custom<T>(_msg: T) -> Self
24 where
25 T: std::fmt::Display,
26 {
27 unimplemented!()
28 }
29}
30
31pub struct Serializer;
32
33macro_rules! serialize {
34 ($($serialize_:ident($($ty:ty$( | $($expr:expr$(, $question_mark:tt)*);+$(;)?)?)?) => $variant:ident$(($const:expr))?),*$(,)?) => {
35 $(
36 fn $serialize_(self$(, v: $ty)?) -> Result<Self::Ok, Self::Error>
37 {
38 Ok(Object::$variant
39 $(({let _: $ty; v$($(.pipe($expr)$($question_mark)*)+)?.into()}))?
41 $(($const))?
42 )
43 }
44 )*
45 };
46}
47
48impl ser::Serializer for Serializer {
49 type Ok = Object<'static>;
50 type Error = Never;
51 type SerializeSeq = SerializeSeq;
52 type SerializeTuple = SerializeTuple;
53 type SerializeTupleStruct = SerializeTupleStruct;
54 type SerializeTupleVariant = SerializeTupleVariant;
55 type SerializeMap = SerializeMap;
56 type SerializeStruct = SerializeStruct;
57 type SerializeStructVariant = SerializeStructVariant;
58
59 serialize! {
60 serialize_bool(bool) => Bool,
61
62 serialize_i8(i8) => I8,
63 serialize_i16(i16) => I16,
64 serialize_i32(i32) => I32,
65 serialize_i64(i64) => I64,
66
67 serialize_u8(u8) => U8,
68 serialize_u16(u16) => U16,
69 serialize_u32(u32) => U32,
70 serialize_u64(u64) => U64,
71 }
72
73 serde_if_integer128!(serialize! {
74 serialize_i128(i128) => I128,
75 serialize_u128(u128) => U128,
76 });
77
78 serialize! {
79 serialize_f32(f32) => F32,
80 serialize_f64(f64) => F64,
81
82 serialize_char(char) => Char,
83 serialize_str(&str | str::to_string) => String,
84
85 serialize_bytes(&[u8] | <[u8]>::to_owned) => ByteArray,
86 serialize_none() => Option(None),
87 }
88
89 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
90 where
91 T: serde::Serialize,
92 {
93 Ok(Object::Option(Some(Box::new(value.serialize(Self)?))))
94 }
95
96 serialize! {
97 serialize_unit() => Unit,
98 }
99
100 fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
101 Ok(Object::UnitStruct { name: name.into() })
102 }
103
104 fn serialize_unit_variant(
105 self,
106 name: &'static str,
107 variant_index: u32,
108 variant: &'static str,
109 ) -> Result<Self::Ok, Self::Error> {
110 Ok(Object::UnitVariant {
111 name: name.into(),
112 variant: Object::DualVariantKey {
113 index: variant_index,
114 name: variant.into(),
115 }
116 .into(),
117 })
118 }
119
120 fn serialize_newtype_struct<T: ?Sized>(
121 self,
122 name: &'static str,
123 value: &T,
124 ) -> Result<Self::Ok, Self::Error>
125 where
126 T: serde::Serialize,
127 {
128 Ok(Object::NewtypeStruct {
129 name: name.into(),
130 value: value.serialize(Self)?.into(),
131 })
132 }
133
134 fn serialize_newtype_variant<T: ?Sized>(
135 self,
136 name: &'static str,
137 variant_index: u32,
138 variant: &'static str,
139 value: &T,
140 ) -> Result<Self::Ok, Self::Error>
141 where
142 T: serde::Serialize,
143 {
144 Ok(Object::NewtypeVariant {
145 name: name.into(),
146 variant: Object::DualVariantKey {
147 index: variant_index,
148 name: variant.into(),
149 }
150 .into(),
151 value: value.serialize(Self)?.into(),
152 })
153 }
154
155 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
156 Ok(SerializeSeq::new(len))
157 }
158
159 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
160 Ok(SerializeTuple::new(len))
161 }
162
163 fn serialize_tuple_struct(
164 self,
165 name: &'static str,
166 len: usize,
167 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
168 Ok(SerializeTupleStruct::new(name, len))
169 }
170
171 fn serialize_tuple_variant(
172 self,
173 name: &'static str,
174 variant_index: u32,
175 variant: &'static str,
176 len: usize,
177 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
178 Ok(SerializeTupleVariant::new(
179 name,
180 Object::DualVariantKey {
181 index: variant_index,
182 name: variant.into(),
183 },
184 len,
185 ))
186 }
187
188 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
189 Ok(SerializeMap::new(len))
190 }
191
192 fn serialize_struct(
193 self,
194 name: &'static str,
195 len: usize,
196 ) -> Result<Self::SerializeStruct, Self::Error> {
197 Ok(SerializeStruct::new(name, len))
198 }
199
200 fn serialize_struct_variant(
201 self,
202 name: &'static str,
203 variant_index: u32,
204 variant: &'static str,
205 len: usize,
206 ) -> Result<Self::SerializeStructVariant, Self::Error> {
207 Ok(SerializeStructVariant::new(
208 name,
209 Object::DualVariantKey {
210 index: variant_index,
211 name: variant.into(),
212 },
213 len,
214 ))
215 }
216
217 fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
218 where
219 I: IntoIterator,
220 I::Item: serde::Serialize,
221 {
222 Ok(Object::Seq(
223 iter.into_iter()
224 .map(|element| element.serialize(Self))
225 .collect::<Result<_, _>>()?,
226 ))
227 }
228
229 fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
230 where
231 K: serde::Serialize,
232 V: serde::Serialize,
233 I: IntoIterator<Item = (K, V)>,
234 {
235 let iter = iter.into_iter();
236 let mut serializer = self.serialize_map(Some(iter.size_hint().0))?;
237 for (key, value) in iter {
238 serializer.serialize_entry(&key, &value)?;
239 }
240 serializer.end()
241 }
242
243 fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
244 where
245 T: std::fmt::Display,
246 {
247 self.serialize_str(&value.to_string())
248 }
249
250 fn is_human_readable(&self) -> bool {
251 true
252 }
253}
254
255pub struct SerializeSeq(Vec<Object<'static>>);
256impl SerializeSeq {
257 fn new(len: Option<usize>) -> Self {
258 Self(Vec::with_capacity(len.unwrap_or_default()))
259 }
260}
261impl ser::SerializeSeq for SerializeSeq {
262 type Ok = Object<'static>;
263 type Error = Never;
264 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
265 where
266 T: serde::Serialize,
267 {
268 self.0.push(value.serialize(Serializer)?);
269 Ok(())
270 }
271 fn end(self) -> Result<Self::Ok, Self::Error> {
272 Ok(Object::Seq(self.0))
273 }
274}
275
276pub struct SerializeTuple(Vec<Object<'static>>);
277impl SerializeTuple {
278 fn new(len: usize) -> Self {
279 Self(Vec::with_capacity(len))
280 }
281}
282impl ser::SerializeTuple for SerializeTuple {
283 type Ok = Object<'static>;
284 type Error = Never;
285 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
286 where
287 T: serde::Serialize,
288 {
289 self.0.push(value.serialize(Serializer)?);
290 Ok(())
291 }
292 fn end(self) -> Result<Self::Ok, Self::Error> {
293 Ok(Object::Tuple(self.0))
294 }
295}
296
297pub struct SerializeMap {
298 map: Vec<(Object<'static>, Object<'static>)>,
299 key: Option<Object<'static>>,
300}
301impl SerializeMap {
302 fn new(len: Option<usize>) -> Self {
303 Self {
304 map: Vec::with_capacity(len.unwrap_or_default()),
305 key: None,
306 }
307 }
308}
309impl ser::SerializeMap for SerializeMap {
310 type Ok = Object<'static>;
311 type Error = Never;
312
313 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
314 where
315 T: serde::Serialize,
316 {
317 assert!(self.key.replace(key.serialize(Serializer)?).is_none());
318 Ok(())
319 }
320
321 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
322 where
323 T: serde::Serialize,
324 {
325 self.map
326 .push((self.key.take().unwrap(), value.serialize(Serializer)?));
327 Ok(())
328 }
329
330 fn end(self) -> Result<Self::Ok, Self::Error> {
331 assert!(self.key.is_none());
332 Ok(Object::Map(self.map))
333 }
334
335 fn serialize_entry<K: ?Sized, V: ?Sized>(
336 &mut self,
337 key: &K,
338 value: &V,
339 ) -> Result<(), Self::Error>
340 where
341 K: serde::Serialize,
342 V: serde::Serialize,
343 {
344 assert!(self.key.is_none());
345 self.map
346 .push((key.serialize(Serializer)?, value.serialize(Serializer)?));
347 Ok(())
348 }
349}
350
351pub struct SerializeTupleStruct {
352 name: &'static str,
353 fields: Vec<Object<'static>>,
354}
355impl SerializeTupleStruct {
356 fn new(name: &'static str, len: usize) -> Self {
357 Self {
358 name,
359 fields: Vec::with_capacity(len),
360 }
361 }
362}
363impl ser::SerializeTupleStruct for SerializeTupleStruct {
364 type Ok = Object<'static>;
365 type Error = Never;
366 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
367 where
368 T: serde::Serialize,
369 {
370 self.fields.push(value.serialize(Serializer)?);
371 Ok(())
372 }
373 fn end(self) -> Result<Self::Ok, Self::Error> {
374 Ok(Object::TupleStruct {
375 name: self.name.into(),
376 fields: self.fields,
377 })
378 }
379}
380
381pub struct SerializeTupleVariant {
382 name: &'static str,
383 variant: Object<'static>,
384 fields: Vec<Object<'static>>,
385}
386impl SerializeTupleVariant {
387 fn new(name: &'static str, variant: Object<'static>, len: usize) -> Self {
388 Self {
389 name,
390 variant,
391 fields: Vec::with_capacity(len),
392 }
393 }
394}
395impl ser::SerializeTupleVariant for SerializeTupleVariant {
396 type Ok = Object<'static>;
397 type Error = Never;
398 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
399 where
400 T: serde::Serialize,
401 {
402 self.fields.push(value.serialize(Serializer)?);
403 Ok(())
404 }
405 fn end(self) -> Result<Self::Ok, Self::Error> {
406 Ok(Object::TupleVariant {
407 name: self.name.into(),
408 variant: self.variant.into(),
409 fields: Object::Seq(self.fields).into(),
410 })
411 }
412}
413
414pub struct SerializeStruct {
415 name: &'static str,
416 fields: Vec<(Cow<'static, str>, Option<Object<'static>>)>,
417}
418impl SerializeStruct {
419 fn new(name: &'static str, len: usize) -> Self {
420 Self {
421 name,
422 fields: Vec::with_capacity(len),
423 }
424 }
425}
426impl ser::SerializeStruct for SerializeStruct {
427 type Ok = Object<'static>;
428 type Error = Never;
429
430 fn serialize_field<T: ?Sized>(
431 &mut self,
432 key: &'static str,
433 value: &T,
434 ) -> Result<(), Self::Error>
435 where
436 T: serde::Serialize,
437 {
438 self.fields
439 .push((key.into(), value.serialize(Serializer)?.into()));
440 Ok(())
441 }
442
443 fn end(self) -> Result<Self::Ok, Self::Error> {
444 Ok(Object::Struct {
445 name: self.name.into(),
446 fields: self.fields,
447 })
448 }
449
450 fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
451 self.fields.push((key.into(), None));
452 Ok(())
453 }
454}
455
456pub struct SerializeStructVariant {
457 name: &'static str,
458 variant: Object<'static>,
459 fields: Vec<(Object<'static>, Option<Object<'static>>)>,
460}
461impl SerializeStructVariant {
462 fn new(name: &'static str, variant: Object<'static>, len: usize) -> Self {
463 Self {
464 name,
465 variant,
466 fields: Vec::with_capacity(len),
467 }
468 }
469}
470impl ser::SerializeStructVariant for SerializeStructVariant {
471 type Ok = Object<'static>;
472 type Error = Never;
473
474 fn serialize_field<T: ?Sized>(
475 &mut self,
476 key: &'static str,
477 value: &T,
478 ) -> Result<(), Self::Error>
479 where
480 T: serde::Serialize,
481 {
482 self.fields.push((
483 key.serialize(Serializer)?,
484 value.serialize(Serializer)?.into(),
485 ));
486 Ok(())
487 }
488
489 fn end(self) -> Result<Self::Ok, Self::Error> {
490 Ok(Object::StructVariant {
491 name: self.name.into(),
492 variant: self.variant.into(),
493 fields: Object::FieldMap(self.fields).into(),
494 })
495 }
496
497 fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
498 self.fields.push((key.serialize(Serializer)?, None));
499 Ok(())
500 }
501}