1use core::fmt::Display;
2
3use rust_decimal::Decimal;
4use rust_decimal::prelude::FromPrimitive;
5use serde::Deserialize;
6use serde::ser::{Impossible, Serialize};
7
8use crate::error::Error;
9use crate::value::Value;
10use crate::{Array, Bytes, Datetime, Duration, Number, Object, RecordId, SerializationError, Uuid};
11
12pub struct Serializer;
13
14impl serde::ser::Error for Error {
15 fn custom<T>(msg: T) -> Self
16 where
17 T: Display,
18 {
19 Self::serialization(msg.to_string(), SerializationError::Serialization)
20 }
21}
22
23type Result<T> = core::result::Result<T, Error>;
24
25impl serde::Serializer for Serializer {
26 type Ok = Value;
27 type Error = Error;
28
29 type SerializeSeq = SerializeVec;
30 type SerializeTuple = SerializeVec;
31 type SerializeTupleStruct = SerializeVec;
32 type SerializeTupleVariant = SerializeTupleVariant;
33 type SerializeMap = SerializeMap;
34 type SerializeStruct = SerializeMap;
35 type SerializeStructVariant = SerializeStructVariant;
36
37 #[inline]
38 fn serialize_bool(self, value: bool) -> Result<Value> {
39 Ok(Value::Bool(value))
40 }
41
42 #[inline]
43 fn serialize_i8(self, value: i8) -> Result<Value> {
44 self.serialize_i64(value as i64)
45 }
46
47 #[inline]
48 fn serialize_i16(self, value: i16) -> Result<Value> {
49 self.serialize_i64(value as i64)
50 }
51
52 #[inline]
53 fn serialize_i32(self, value: i32) -> Result<Value> {
54 self.serialize_i64(value as i64)
55 }
56
57 fn serialize_i64(self, value: i64) -> Result<Value> {
58 Ok(Value::Number(value.into()))
59 }
60
61 fn serialize_i128(self, value: i128) -> Result<Value> {
62 if let Ok(value) = i64::try_from(value) {
63 Ok(Value::Number(Number::Int(value)))
64 } else if let Some(decimal) = Decimal::from_i128(value) {
65 Ok(Value::Number(Number::Decimal(decimal)))
66 } else {
67 Err(Error::serialization("number out of range".into(), None))
68 }
69 }
70
71 #[inline]
72 fn serialize_u8(self, value: u8) -> Result<Value> {
73 self.serialize_i64(value as i64)
74 }
75
76 #[inline]
77 fn serialize_u16(self, value: u16) -> Result<Value> {
78 self.serialize_i64(value as i64)
79 }
80
81 #[inline]
82 fn serialize_u32(self, value: u32) -> Result<Value> {
83 self.serialize_i64(value as i64)
84 }
85
86 #[inline]
87 fn serialize_u64(self, value: u64) -> Result<Value> {
88 match i64::try_from(value) {
89 Ok(value) => self.serialize_i64(value),
90 _ => Ok(Value::Number(Number::Decimal(
91 Decimal::from_u64(value).expect("from_u64 will ALWAYS return some"),
92 ))),
93 }
94 }
95
96 fn serialize_u128(self, value: u128) -> Result<Value> {
97 if let Ok(value) = i64::try_from(value) {
98 Ok(Value::Number(Number::Int(value)))
99 } else if let Some(decimal) = Decimal::from_u128(value) {
100 Ok(Value::Number(Number::Decimal(decimal)))
101 } else {
102 Err(Error::serialization("number out of range".into(), None))
103 }
104 }
105
106 #[inline]
107 fn serialize_f32(self, float: f32) -> Result<Value> {
108 Ok(Value::Number(Number::from_float(float as f64)))
109 }
110
111 #[inline]
112 fn serialize_f64(self, float: f64) -> Result<Value> {
113 Ok(Value::Number(Number::from_float(float)))
114 }
115
116 #[inline]
117 fn serialize_char(self, value: char) -> Result<Value> {
118 Ok(Value::String(value.into()))
119 }
120
121 #[inline]
122 fn serialize_str(self, value: &str) -> Result<Value> {
123 Ok(Value::String(value.to_owned()))
124 }
125
126 fn serialize_bytes(self, value: &[u8]) -> Result<Value> {
127 Ok(Value::Bytes(Bytes(::bytes::Bytes::copy_from_slice(value))))
128 }
129
130 #[inline]
131 fn serialize_unit(self) -> Result<Value> {
132 Ok(Value::Null)
133 }
134
135 #[inline]
136 fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
137 self.serialize_unit()
138 }
139
140 #[inline]
141 fn serialize_unit_variant(
142 self,
143 _name: &'static str,
144 _variant_index: u32,
145 variant: &'static str,
146 ) -> Result<Value> {
147 self.serialize_str(variant)
148 }
149
150 #[inline]
151 fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<Value>
152 where
153 T: ?Sized + Serialize,
154 {
155 let serialized = value.serialize(self)?;
156 match name {
157 "Datetime" => {
158 let datetime =
159 chrono::DateTime::<chrono::Utc>::deserialize(serialized).map_err(|err| {
160 Error::serialization(err.to_string(), SerializationError::Deserialization)
161 })?;
162 Ok(Value::Datetime(Datetime::from(datetime)))
163 }
164 "Uuid" => {
165 let uuid = uuid::Uuid::deserialize(serialized).map_err(|err| {
166 Error::serialization(err.to_string(), SerializationError::Deserialization)
167 })?;
168 Ok(Value::Uuid(Uuid::from(uuid)))
169 }
170 "Duration" => {
171 let duration = std::time::Duration::deserialize(serialized).map_err(|err| {
172 Error::serialization(err.to_string(), SerializationError::Deserialization)
173 })?;
174 Ok(Value::Duration(Duration::from(duration)))
175 }
176 _ => Ok(serialized),
177 }
178 }
179
180 fn serialize_newtype_variant<T>(
181 self,
182 _name: &'static str,
183 _variant_index: u32,
184 variant: &'static str,
185 value: &T,
186 ) -> Result<Value>
187 where
188 T: ?Sized + Serialize,
189 {
190 let mut values = Object::new();
191 values.insert(String::from(variant), value.serialize(Self)?);
192 Ok(Value::Object(values))
193 }
194
195 #[inline]
196 fn serialize_none(self) -> Result<Value> {
197 Ok(Value::None)
198 }
199
200 #[inline]
201 fn serialize_some<T>(self, value: &T) -> Result<Value>
202 where
203 T: ?Sized + Serialize,
204 {
205 value.serialize(self)
206 }
207
208 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
209 Ok(SerializeVec {
210 vec: Array::with_capacity(len.unwrap_or(0)),
211 })
212 }
213
214 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
215 self.serialize_seq(Some(len))
216 }
217
218 fn serialize_tuple_struct(
219 self,
220 _name: &'static str,
221 len: usize,
222 ) -> Result<Self::SerializeTupleStruct> {
223 self.serialize_seq(Some(len))
224 }
225
226 fn serialize_tuple_variant(
227 self,
228 _name: &'static str,
229 _variant_index: u32,
230 variant: &'static str,
231 len: usize,
232 ) -> Result<Self::SerializeTupleVariant> {
233 Ok(SerializeTupleVariant {
234 name: String::from(variant),
235 vec: Array::with_capacity(len),
236 })
237 }
238
239 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
240 Ok(SerializeMap {
241 map: Object::new(),
242 next_key: None,
243 record_id_struct: false,
244 })
245 }
246
247 fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
248 let mut map = self.serialize_map(Some(len))?;
249 if name == "RecordId" {
250 map.record_id_struct = true;
251 }
252 Ok(map)
253 }
254
255 fn serialize_struct_variant(
256 self,
257 _name: &'static str,
258 _variant_index: u32,
259 variant: &'static str,
260 _len: usize,
261 ) -> Result<Self::SerializeStructVariant> {
262 Ok(SerializeStructVariant {
263 name: String::from(variant),
264 map: Object::new(),
265 })
266 }
267
268 fn collect_str<T>(self, value: &T) -> Result<Value>
269 where
270 T: ?Sized + Display,
271 {
272 Ok(Value::String(value.to_string()))
273 }
274}
275
276pub struct SerializeVec {
277 vec: Array,
278}
279
280pub struct SerializeTupleVariant {
281 name: String,
282 vec: Array,
283}
284
285pub struct SerializeMap {
286 map: Object,
287 next_key: Option<String>,
288 record_id_struct: bool,
289}
290
291pub struct SerializeStructVariant {
292 name: String,
293 map: Object,
294}
295
296impl serde::ser::SerializeSeq for SerializeVec {
297 type Ok = Value;
298 type Error = Error;
299
300 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
301 where
302 T: ?Sized + Serialize,
303 {
304 self.vec.push(value.serialize(Serializer)?);
305 Ok(())
306 }
307
308 fn end(self) -> Result<Value> {
309 Ok(Value::Array(self.vec))
310 }
311}
312
313impl serde::ser::SerializeTuple for SerializeVec {
314 type Ok = Value;
315 type Error = Error;
316
317 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
318 where
319 T: ?Sized + Serialize,
320 {
321 serde::ser::SerializeSeq::serialize_element(self, value)
322 }
323
324 fn end(self) -> Result<Value> {
325 serde::ser::SerializeSeq::end(self)
326 }
327}
328
329impl serde::ser::SerializeTupleStruct for SerializeVec {
330 type Ok = Value;
331 type Error = Error;
332
333 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
334 where
335 T: ?Sized + Serialize,
336 {
337 serde::ser::SerializeSeq::serialize_element(self, value)
338 }
339
340 fn end(self) -> Result<Value> {
341 serde::ser::SerializeSeq::end(self)
342 }
343}
344
345impl serde::ser::SerializeTupleVariant for SerializeTupleVariant {
346 type Ok = Value;
347 type Error = Error;
348
349 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
350 where
351 T: ?Sized + Serialize,
352 {
353 self.vec.push(value.serialize(Serializer)?);
354 Ok(())
355 }
356
357 fn end(self) -> Result<Value> {
358 let mut object = Object::new();
359
360 object.insert(self.name, Value::Array(self.vec));
361
362 Ok(Value::Object(object))
363 }
364}
365
366impl serde::ser::SerializeMap for SerializeMap {
367 type Ok = Value;
368 type Error = Error;
369
370 fn serialize_key<T>(&mut self, key: &T) -> Result<()>
371 where
372 T: ?Sized + Serialize,
373 {
374 self.next_key = Some(key.serialize(MapKeySerializer)?);
375 Ok(())
376 }
377
378 fn serialize_value<T>(&mut self, value: &T) -> Result<()>
379 where
380 T: ?Sized + Serialize,
381 {
382 let key = self.next_key.take();
383 let key = key.expect("serialize_value called before serialize_key");
386 self.map.insert(key, value.serialize(Serializer)?);
387 Ok(())
388 }
389
390 fn end(self) -> Result<Value> {
391 if self.record_id_struct {
392 let record_id = RecordId::deserialize(Value::Object(self.map)).map_err(|err| {
393 Error::serialization(err.to_string(), SerializationError::Deserialization)
394 })?;
395 return Ok(Value::RecordId(record_id));
396 }
397 Ok(Value::Object(self.map))
398 }
399}
400
401struct MapKeySerializer;
402
403fn key_must_be_a_string() -> Error {
404 Error::serialization("key must be a string".into(), SerializationError::Serialization)
405}
406
407fn float_key_must_be_finite() -> Error {
408 Error::serialization("float key must be finite".into(), SerializationError::Serialization)
409}
410
411impl serde::Serializer for MapKeySerializer {
412 type Ok = String;
413 type Error = Error;
414
415 type SerializeSeq = Impossible<String, Error>;
416 type SerializeTuple = Impossible<String, Error>;
417 type SerializeTupleStruct = Impossible<String, Error>;
418 type SerializeTupleVariant = Impossible<String, Error>;
419 type SerializeMap = Impossible<String, Error>;
420 type SerializeStruct = Impossible<String, Error>;
421 type SerializeStructVariant = Impossible<String, Error>;
422
423 #[inline]
424 fn serialize_unit_variant(
425 self,
426 _name: &'static str,
427 _variant_index: u32,
428 variant: &'static str,
429 ) -> Result<String> {
430 Ok(variant.to_owned())
431 }
432
433 #[inline]
434 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<String>
435 where
436 T: ?Sized + Serialize,
437 {
438 value.serialize(self)
439 }
440
441 fn serialize_bool(self, value: bool) -> Result<String> {
442 Ok(if value {
443 "true"
444 } else {
445 "false"
446 }
447 .to_owned())
448 }
449
450 fn serialize_i8(self, value: i8) -> Result<String> {
451 Ok(value.to_string())
452 }
453
454 fn serialize_i16(self, value: i16) -> Result<String> {
455 Ok(value.to_string())
456 }
457
458 fn serialize_i32(self, value: i32) -> Result<String> {
459 Ok(value.to_string())
460 }
461
462 fn serialize_i64(self, value: i64) -> Result<String> {
463 Ok(value.to_string())
464 }
465
466 fn serialize_i128(self, value: i128) -> Result<String> {
467 Ok(value.to_string())
468 }
469
470 fn serialize_u8(self, value: u8) -> Result<String> {
471 Ok(value.to_string())
472 }
473
474 fn serialize_u16(self, value: u16) -> Result<String> {
475 Ok(value.to_string())
476 }
477
478 fn serialize_u32(self, value: u32) -> Result<String> {
479 Ok(value.to_string())
480 }
481
482 fn serialize_u64(self, value: u64) -> Result<String> {
483 Ok(value.to_string())
484 }
485
486 fn serialize_u128(self, value: u128) -> Result<String> {
487 Ok(value.to_string())
488 }
489
490 fn serialize_f32(self, value: f32) -> Result<String> {
491 if value.is_finite() {
492 Ok(value.to_string())
493 } else {
494 Err(float_key_must_be_finite())
495 }
496 }
497
498 fn serialize_f64(self, value: f64) -> Result<String> {
499 if value.is_finite() {
500 Ok(value.to_string())
501 } else {
502 Err(float_key_must_be_finite())
503 }
504 }
505
506 #[inline]
507 fn serialize_char(self, value: char) -> Result<String> {
508 Ok({
509 let mut s = String::new();
510 s.push(value);
511 s
512 })
513 }
514
515 #[inline]
516 fn serialize_str(self, value: &str) -> Result<String> {
517 Ok(value.to_owned())
518 }
519
520 fn serialize_bytes(self, _value: &[u8]) -> Result<String> {
521 Err(key_must_be_a_string())
522 }
523
524 fn serialize_unit(self) -> Result<String> {
525 Err(key_must_be_a_string())
526 }
527
528 fn serialize_unit_struct(self, _name: &'static str) -> Result<String> {
529 Err(key_must_be_a_string())
530 }
531
532 fn serialize_newtype_variant<T>(
533 self,
534 _name: &'static str,
535 _variant_index: u32,
536 _variant: &'static str,
537 _value: &T,
538 ) -> Result<String>
539 where
540 T: ?Sized + Serialize,
541 {
542 Err(key_must_be_a_string())
543 }
544
545 fn serialize_none(self) -> Result<String> {
546 Err(key_must_be_a_string())
547 }
548
549 fn serialize_some<T>(self, _value: &T) -> Result<String>
550 where
551 T: ?Sized + Serialize,
552 {
553 Err(key_must_be_a_string())
554 }
555
556 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
557 Err(key_must_be_a_string())
558 }
559
560 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
561 Err(key_must_be_a_string())
562 }
563
564 fn serialize_tuple_struct(
565 self,
566 _name: &'static str,
567 _len: usize,
568 ) -> Result<Self::SerializeTupleStruct> {
569 Err(key_must_be_a_string())
570 }
571
572 fn serialize_tuple_variant(
573 self,
574 _name: &'static str,
575 _variant_index: u32,
576 _variant: &'static str,
577 _len: usize,
578 ) -> Result<Self::SerializeTupleVariant> {
579 Err(key_must_be_a_string())
580 }
581
582 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
583 Err(key_must_be_a_string())
584 }
585
586 fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
587 Err(key_must_be_a_string())
588 }
589
590 fn serialize_struct_variant(
591 self,
592 _name: &'static str,
593 _variant_index: u32,
594 _variant: &'static str,
595 _len: usize,
596 ) -> Result<Self::SerializeStructVariant> {
597 Err(key_must_be_a_string())
598 }
599
600 fn collect_str<T>(self, value: &T) -> Result<String>
601 where
602 T: ?Sized + Display,
603 {
604 Ok(value.to_string())
605 }
606}
607
608impl serde::ser::SerializeStruct for SerializeMap {
609 type Ok = Value;
610 type Error = Error;
611
612 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
613 where
614 T: ?Sized + Serialize,
615 {
616 serde::ser::SerializeMap::serialize_entry(self, key, value)
617 }
618
619 fn end(self) -> Result<Value> {
620 serde::ser::SerializeMap::end(self)
621 }
622}
623
624impl serde::ser::SerializeStructVariant for SerializeStructVariant {
625 type Ok = Value;
626 type Error = Error;
627
628 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
629 where
630 T: ?Sized + Serialize,
631 {
632 self.map.insert(String::from(key), value.serialize(Serializer)?);
633 Ok(())
634 }
635
636 fn end(self) -> Result<Value> {
637 let mut object = Object::new();
638
639 object.insert(self.name, Value::Object(self.map));
640
641 Ok(Value::Object(object))
642 }
643}