1use serde::ser::{self, Serialize};
2use std::fmt::Display;
3use std::io::Write;
4use std::{f32, f64, io};
5
6use crate::error::{Error, Result};
7
8pub fn to_string<T>(value: &T) -> Result<String>
10where
11 T: Serialize,
12{
13 let mut serializer = Serializer::new(Vec::<u8>::new());
14 value.serialize(&mut serializer)?;
15 let output = String::from_utf8(serializer.take_output())?;
16 Ok(output)
17}
18
19pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
21where
22 W: io::Write,
23 T: ?Sized + Serialize,
24{
25 let mut ser = Serializer::new(writer);
26 value.serialize(&mut ser)
27}
28
29struct Serializer<W> {
30 output: InnerWriter<W>,
31 }
33
34impl<W> Serializer<W> {
35 fn new(writer: W) -> Self {
36 Self {
37 output: InnerWriter {
38 writer,
39 last_byte: 0,
40 },
41 }
42 }
43
44 fn take_output(self) -> W {
45 self.output.writer
46 }
47}
48
49struct InnerWriter<W> {
50 writer: W,
51 last_byte: u8,
52}
53
54impl<W> InnerWriter<W> {
55 fn ends_with(&self, c: char) -> bool {
56 self.last_byte == (c as u8)
57 }
58}
59
60impl<W: io::Write> io::Write for InnerWriter<W> {
61 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
62 let written = self.writer.write(buf)?;
63 if written > 0 {
64 self.last_byte = buf[written - 1];
65 }
66 Ok(written)
67 }
68
69 fn flush(&mut self) -> io::Result<()> {
70 self.writer.flush()
71 }
72}
73
74impl<W: io::Write> Serializer<W> {
75 fn write_display<T>(&mut self, v: &T) -> Result<()>
76 where
77 T: Display,
78 {
79 write!(&mut self.output, "{}", v)?;
80 Ok(())
81 }
82}
83
84impl<W: io::Write> ser::Serializer for &mut Serializer<W> {
85 type Ok = ();
86 type Error = Error;
87
88 type SerializeSeq = Self;
89 type SerializeTuple = Self;
90 type SerializeTupleStruct = Self;
91 type SerializeTupleVariant = Self;
92 type SerializeMap = Self;
93 type SerializeStruct = Self;
94 type SerializeStructVariant = Self;
95
96 fn serialize_bool(self, v: bool) -> Result<()> {
97 self.write_display(&v)
98 }
99
100 fn serialize_i8(self, v: i8) -> Result<()> {
101 self.write_display(&v)
102 }
103
104 fn serialize_i16(self, v: i16) -> Result<()> {
105 self.write_display(&v)
106 }
107
108 fn serialize_i32(self, v: i32) -> Result<()> {
109 self.write_display(&v)
110 }
111
112 fn serialize_i64(self, v: i64) -> Result<()> {
113 self.write_display(&v)
114 }
115
116 fn serialize_u8(self, v: u8) -> Result<()> {
117 self.write_display(&v)
118 }
119
120 fn serialize_u16(self, v: u16) -> Result<()> {
121 self.write_display(&v)
122 }
123
124 fn serialize_u32(self, v: u32) -> Result<()> {
125 self.write_display(&v)
126 }
127
128 fn serialize_u64(self, v: u64) -> Result<()> {
129 self.write_display(&v)
130 }
131
132 fn serialize_f32(self, v: f32) -> Result<()> {
133 if v == f32::INFINITY {
134 self.output.write_all(b"Infinity")?;
135 } else if v == f32::NEG_INFINITY {
136 self.output.write_all(b"-Infinity")?;
137 } else if v.is_nan() {
138 self.output.write_all(b"NaN")?;
139 } else {
140 self.write_display(&v)?;
141 }
142 Ok(())
143 }
144
145 fn serialize_f64(self, v: f64) -> Result<()> {
146 if v == f64::INFINITY {
147 self.output.write_all(b"Infinity")?;
148 } else if v == f64::NEG_INFINITY {
149 self.output.write_all(b"-Infinity")?;
150 } else if v.is_nan() {
151 self.output.write_all(b"NaN")?;
152 } else {
153 self.write_display(&v)?;
154 }
155 Ok(())
156 }
157
158 fn serialize_char(self, v: char) -> Result<()> {
159 let mut buf = [0; 4];
161 self.serialize_str(v.encode_utf8(&mut buf))
162 }
163
164 fn serialize_str(self, v: &str) -> Result<()> {
165 write!(&mut self.output, "\"{}\"", escape(v))?;
166 Ok(())
167 }
168
169 fn serialize_bytes(self, _v: &[u8]) -> Result<()> {
170 unimplemented!() }
172
173 fn serialize_none(self) -> Result<()> {
174 self.serialize_unit()
175 }
176
177 fn serialize_some<T>(self, value: &T) -> Result<()>
178 where
179 T: ?Sized + Serialize,
180 {
181 value.serialize(self)
182 }
183
184 fn serialize_unit(self) -> Result<()> {
185 self.output.write_all(b"null")?;
186 Ok(())
187 }
188
189 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
190 self.serialize_unit()
191 }
192
193 fn serialize_unit_variant(
194 self,
195 _name: &'static str,
196 _variant_index: u32,
197 variant: &'static str,
198 ) -> Result<()> {
199 self.serialize_str(variant)
200 }
201
202 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
203 where
204 T: ?Sized + Serialize,
205 {
206 value.serialize(self)
207 }
208
209 fn serialize_newtype_variant<T>(
210 self,
211 _name: &'static str,
212 _variant_index: u32,
213 variant: &'static str,
214 value: &T,
215 ) -> Result<()>
216 where
217 T: ?Sized + Serialize,
218 {
219 self.output.write_all(b"{")?;
220 variant.serialize(&mut *self)?; self.output.write_all(b":")?;
222 value.serialize(&mut *self)?;
223 self.output.write_all(b"}")?;
224 Ok(())
225 }
226
227 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
228 self.output.write_all(b"[")?;
229 Ok(self)
230 }
231
232 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
233 self.serialize_seq(Some(len))
234 }
235
236 fn serialize_tuple_struct(
237 self,
238 _name: &'static str,
239 len: usize,
240 ) -> Result<Self::SerializeTupleStruct> {
241 self.serialize_seq(Some(len))
242 }
243
244 fn serialize_tuple_variant(
245 self,
246 _name: &'static str,
247 _variant_index: u32,
248 variant: &'static str,
249 _len: usize,
250 ) -> Result<Self::SerializeTupleVariant> {
251 self.output.write_all(b"{")?;
252 variant.serialize(&mut *self)?;
253 self.output.write_all(b":[")?;
254 Ok(self)
255 }
256
257 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
258 self.output.write_all(b"{")?;
259 Ok(self)
260 }
261
262 fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
263 self.serialize_map(Some(len))
264 }
265
266 fn serialize_struct_variant(
267 self,
268 _name: &'static str,
269 _variant_index: u32,
270 variant: &'static str,
271 _len: usize,
272 ) -> Result<Self::SerializeStructVariant> {
273 self.output.write_all(b"{")?;
274 variant.serialize(&mut *self)?;
275 self.output.write_all(b":{")?;
276 Ok(self)
277 }
278}
279
280impl<W: io::Write> ser::SerializeSeq for &mut Serializer<W> {
281 type Ok = ();
282 type Error = Error;
283
284 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
285 where
286 T: ?Sized + Serialize,
287 {
288 if !self.output.ends_with('[') {
289 self.output.write_all(b",")?;
290 }
291 value.serialize(&mut **self)
292 }
293
294 fn end(self) -> Result<()> {
295 self.output.write_all(b"]")?;
296 Ok(())
297 }
298}
299
300impl<W: io::Write> ser::SerializeTuple for &mut Serializer<W> {
301 type Ok = ();
302 type Error = Error;
303
304 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
305 where
306 T: ?Sized + Serialize,
307 {
308 ser::SerializeSeq::serialize_element(self, value)
309 }
310
311 fn end(self) -> Result<()> {
312 ser::SerializeSeq::end(self)
313 }
314}
315
316impl<W: io::Write> ser::SerializeTupleStruct for &mut Serializer<W> {
317 type Ok = ();
318 type Error = Error;
319
320 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
321 where
322 T: ?Sized + Serialize,
323 {
324 ser::SerializeSeq::serialize_element(self, value)
325 }
326
327 fn end(self) -> Result<()> {
328 ser::SerializeSeq::end(self)
329 }
330}
331
332impl<W: io::Write> ser::SerializeTupleVariant for &mut Serializer<W> {
333 type Ok = ();
334 type Error = Error;
335
336 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
337 where
338 T: ?Sized + Serialize,
339 {
340 ser::SerializeSeq::serialize_element(self, value)
341 }
342
343 fn end(self) -> Result<()> {
344 self.output.write_all(b"]}")?;
345 Ok(())
346 }
347}
348
349impl<W: io::Write> ser::SerializeMap for &mut Serializer<W> {
350 type Ok = ();
351 type Error = Error;
352
353 fn serialize_key<T>(&mut self, key: &T) -> Result<()>
354 where
355 T: ?Sized + Serialize,
356 {
357 if !self.output.ends_with('{') {
358 self.output.write_all(b",")?;
359 }
360 key.serialize(&mut **self)
361 }
362
363 fn serialize_value<T>(&mut self, value: &T) -> Result<()>
364 where
365 T: ?Sized + Serialize,
366 {
367 self.output.write_all(b":")?;
368 value.serialize(&mut **self)
369 }
370
371 fn end(self) -> Result<()> {
372 self.output.write_all(b"}")?;
373 Ok(())
374 }
375}
376
377impl<W: io::Write> ser::SerializeStruct for &mut Serializer<W> {
378 type Ok = ();
379 type Error = Error;
380
381 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
382 where
383 T: ?Sized + Serialize,
384 {
385 ser::SerializeMap::serialize_key(self, key)?;
386 ser::SerializeMap::serialize_value(self, value)
387 }
388
389 fn end(self) -> Result<()> {
390 ser::SerializeMap::end(self)
391 }
392}
393
394impl<W: io::Write> ser::SerializeStructVariant for &mut Serializer<W> {
395 type Ok = ();
396 type Error = Error;
397
398 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
399 where
400 T: ?Sized + Serialize,
401 {
402 ser::SerializeStruct::serialize_field(self, key, value)
403 }
404
405 fn end(self) -> Result<()> {
406 self.output.write_all(b"}}")?;
407 Ok(())
408 }
409}
410
411fn escape(v: &str) -> String {
412 v.chars()
413 .flat_map(|c| match c {
414 '"' => vec!['\\', c],
415 '\n' => vec!['\\', 'n'],
416 '\r' => vec!['\\', 'r'],
417 '\t' => vec!['\\', 't'],
418 '\\' => vec!['\\', '\\'],
419 '\u{0008}' => vec!['\\', 'b'],
420 '\u{000c}' => vec!['\\', 'f'],
421 c => vec![c],
422 })
423 .collect()
424}