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