1use serde::{ser, Serialize};
2use crate::error::{Error, Result};
3use std::io::Write;
4
5pub struct Serializer<W> {
6 writer: W,
7 last_key: Option<String>,
8 indent: usize,
9 is_root: bool,
10 pretty_out: bool,
11}
12
13impl<W: Write> Serializer<W> {
14 pub fn new(writer: W) -> Self {
15 Serializer {
16 writer,
17 last_key: None,
18 indent: 0,
19 is_root: true,
20 pretty_out: false,
21 }
22 }
23
24 fn write_indent(&mut self) -> Result<()> {
25 for _ in 0..self.indent {
26 self.writer.write_all(b"\t")?;
27 }
28 Ok(())
29 }
30
31 fn write_key(&mut self) -> Result<()> {
32 if let Some(key) = self.last_key.clone() {
33 self.write_indent()?;
34 write!(self.writer, "\"{}\"", key)?;
35 self.writer.write_all(b" ")?;
36 }
37 Ok(())
38 }
39}
40
41pub fn to_string<T>(value: &T) -> Result<String>
42where
43 T: Serialize,
44{
45 let mut writer = Vec::new();
46 let mut serializer = Serializer::new(&mut writer);
47 value.serialize(&mut serializer)?;
48 Ok(String::from_utf8(writer).map_err(|e| Error::Message(e.to_string()))?)
49}
50
51impl<'a, W: Write> ser::Serializer for &'a mut Serializer<W> {
52 type Ok = ();
53 type Error = Error;
54
55 type SerializeSeq = SeqSerializer<'a, W>;
56 type SerializeTuple = ser::Impossible<(), Error>;
57 type SerializeTupleStruct = ser::Impossible<(), Error>;
58 type SerializeTupleVariant = ser::Impossible<(), Error>;
59 type SerializeMap = MapSerializer<'a, W>;
60 type SerializeStruct = StructSerializer<'a, W>;
61 type SerializeStructVariant = ser::Impossible<(), Error>;
62
63 fn serialize_bool(self, v: bool) -> Result<()> {
64 self.serialize_str(if v { "1" } else { "0" })
65 }
66
67 fn serialize_i8(self, v: i8) -> Result<()> {
68 self.serialize_str(&v.to_string())
69 }
70
71 fn serialize_i16(self, v: i16) -> Result<()> {
72 self.serialize_str(&v.to_string())
73 }
74
75 fn serialize_i32(self, v: i32) -> Result<()> {
76 self.serialize_str(&v.to_string())
77 }
78
79 fn serialize_i64(self, v: i64) -> Result<()> {
80 self.serialize_str(&v.to_string())
81 }
82
83 fn serialize_u8(self, v: u8) -> Result<()> {
84 self.serialize_str(&v.to_string())
85 }
86
87 fn serialize_u16(self, v: u16) -> Result<()> {
88 self.serialize_str(&v.to_string())
89 }
90
91 fn serialize_u32(self, v: u32) -> Result<()> {
92 self.serialize_str(&v.to_string())
93 }
94
95 fn serialize_u64(self, v: u64) -> Result<()> {
96 self.serialize_str(&v.to_string())
97 }
98
99 fn serialize_f32(self, v: f32) -> Result<()> {
100 self.serialize_str(&v.to_string())
101 }
102
103 fn serialize_f64(self, v: f64) -> Result<()> {
104 self.serialize_str(&v.to_string())
105 }
106
107 fn serialize_char(self, v: char) -> Result<()> {
108 self.serialize_str(&v.to_string())
109 }
110
111 fn serialize_str(self, v: &str) -> Result<()> {
112 self.write_key()?;
113 write!(self.writer, "\"{}\"", v)?;
114 self.writer.write_all(b"\n")?;
115 self.last_key = None;
116 Ok(())
117 }
118
119 fn serialize_bytes(self, _v: &[u8]) -> Result<()> {
120 Err(Error::Message("Bytes serialization not supported".into()))
121 }
122
123 fn serialize_none(self) -> Result<()> {
124 self.last_key = None;
125 Ok(())
126 }
127
128 fn serialize_some<T>(self, value: &T) -> Result<()>
129 where
130 T: ?Sized + Serialize,
131 {
132 value.serialize(self)
133 }
134
135 fn serialize_unit(self) -> Result<()> {
136 self.last_key = None;
137 Ok(())
138 }
139
140 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
141 self.serialize_unit()
142 }
143
144 fn serialize_unit_variant(
145 self,
146 _name: &'static str,
147 _variant_index: u32,
148 _variant: &'static str,
149 ) -> Result<()> {
150 Err(Error::Message("Unit variant serialization not supported".into()))
151 }
152
153 fn serialize_newtype_struct<T>(
154 self,
155 _name: &'static str,
156 value: &T,
157 ) -> Result<()>
158 where
159 T: ?Sized + Serialize,
160 {
161 value.serialize(self)
162 }
163
164 fn serialize_newtype_variant<T>(
165 self,
166 _name: &'static str,
167 _variant_index: u32,
168 _variant: &'static str,
169 _value: &T,
170 ) -> Result<()>
171 where
172 T: ?Sized + Serialize,
173 {
174 Err(Error::Message("Newtype variant serialization not supported".into()))
175 }
176
177 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
178 let key = self.last_key.take().ok_or(Error::ExpectedKey)?;
179 Ok(SeqSerializer {
180 serializer: self,
181 key,
182 })
183 }
184
185 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
186 Err(Error::Message("Tuple serialization not supported".into()))
187 }
188
189 fn serialize_tuple_struct(
190 self,
191 _name: &'static str,
192 _len: usize,
193 ) -> Result<Self::SerializeTupleStruct> {
194 Err(Error::Message("Tuple struct serialization not supported".into()))
195 }
196
197 fn serialize_tuple_variant(
198 self,
199 _name: &'static str,
200 _variant_index: u32,
201 _variant: &'static str,
202 _len: usize,
203 ) -> Result<Self::SerializeTupleVariant> {
204 Err(Error::Message("Tuple variant serialization not supported".into()))
205 }
206
207 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
208 if self.is_root {
209 self.is_root = false;
210 Ok(MapSerializer {
211 serializer: self,
212 is_root: true,
213 })
214 } else {
215 let key_clone = self.last_key.clone();
216 if let Some(key) = key_clone {
217 self.write_indent()?;
218 write!(self.writer, "{}", key)?;
219 self.writer.write_all(b"\n")?;
220 }
221 self.write_indent()?;
222 self.writer.write_all(b"{\n")?;
223 self.indent += 1;
224 self.last_key = None;
225
226 Ok(MapSerializer {
227 serializer: self,
228 is_root: false,
229 })
230 }
231 }
232
233 fn serialize_struct(
234 self,
235 _name: &'static str,
236 len: usize,
237 ) -> Result<Self::SerializeStruct> {
238 let map = self.serialize_map(Some(len))?;
239 Ok(StructSerializer { map })
240 }
241
242 fn serialize_struct_variant(
243 self,
244 _name: &'static str,
245 _variant_index: u32,
246 _variant: &'static str,
247 _len: usize,
248 ) -> Result<Self::SerializeStructVariant> {
249 Err(Error::Message("Struct variant serialization not supported".into()))
250 }
251}
252
253pub struct SeqSerializer<'a, W> {
254 serializer: &'a mut Serializer<W>,
255 key: String,
256}
257
258impl<'a, W: Write> ser::SerializeSeq for SeqSerializer<'a, W> {
259 type Ok = ();
260 type Error = Error;
261
262 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
263 where
264 T: ?Sized + Serialize,
265 {
266 self.serializer.last_key = Some(self.key.clone());
267 value.serialize(&mut *self.serializer)
268 }
269
270 fn end(self) -> Result<()> {
271 Ok(())
272 }
273}
274
275pub struct MapSerializer<'a, W> {
276 serializer: &'a mut Serializer<W>,
277 is_root: bool,
278}
279
280impl<'a, W: Write> ser::SerializeMap for MapSerializer<'a, W> {
281 type Ok = ();
282 type Error = Error;
283
284 fn serialize_key<T>(&mut self, key: &T) -> Result<()>
285 where
286 T: ?Sized + Serialize,
287 {
288 struct KeyCollector(String);
289 impl<'k> ser::Serializer for &'k mut KeyCollector {
290 type Ok = ();
291 type Error = Error;
292 type SerializeSeq = ser::Impossible<(), Error>;
293 type SerializeTuple = ser::Impossible<(), Error>;
294 type SerializeTupleStruct = ser::Impossible<(), Error>;
295 type SerializeTupleVariant = ser::Impossible<(), Error>;
296 type SerializeMap = ser::Impossible<(), Error>;
297 type SerializeStruct = ser::Impossible<(), Error>;
298 type SerializeStructVariant = ser::Impossible<(), Error>;
299
300 fn serialize_str(self, v: &str) -> Result<()> {
301 self.0 = v.to_string();
302 Ok(())
303 }
304 fn serialize_bool(self, v: bool) -> Result<()> { self.serialize_str(if v { "1" } else { "0" }) }
305 fn serialize_i8(self, v: i8) -> Result<()> { self.serialize_str(&v.to_string()) }
306 fn serialize_i16(self, v: i16) -> Result<()> { self.serialize_str(&v.to_string()) }
307 fn serialize_i32(self, v: i32) -> Result<()> { self.serialize_str(&v.to_string()) }
308 fn serialize_i64(self, v: i64) -> Result<()> { self.serialize_str(&v.to_string()) }
309 fn serialize_u8(self, v: u8) -> Result<()> { self.serialize_str(&v.to_string()) }
310 fn serialize_u16(self, v: u16) -> Result<()> { self.serialize_str(&v.to_string()) }
311 fn serialize_u32(self, v: u32) -> Result<()> { self.serialize_str(&v.to_string()) }
312 fn serialize_u64(self, v: u64) -> Result<()> { self.serialize_str(&v.to_string()) }
313 fn serialize_f32(self, v: f32) -> Result<()> { self.serialize_str(&v.to_string()) }
314 fn serialize_f64(self, v: f64) -> Result<()> { self.serialize_str(&v.to_string()) }
315 fn serialize_char(self, v: char) -> Result<()> { self.serialize_str(&v.to_string()) }
316 fn serialize_bytes(self, _v: &[u8]) -> Result<()> { Err(Error::ExpectedString) }
317 fn serialize_none(self) -> Result<()> { Err(Error::ExpectedString) }
318 fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<()> { value.serialize(self) }
319 fn serialize_unit(self) -> Result<()> { Err(Error::ExpectedString) }
320 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { Err(Error::ExpectedString) }
321 fn serialize_unit_variant(self, _name: &'static str, _idx: u32, _var: &'static str) -> Result<()> { Err(Error::ExpectedString) }
322 fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> Result<()> { value.serialize(self) }
323 fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _idx: u32, _var: &'static str, _val: &T) -> Result<()> { Err(Error::ExpectedString) }
324 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { Err(Error::ExpectedString) }
325 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { Err(Error::ExpectedString) }
326 fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> { Err(Error::ExpectedString) }
327 fn serialize_tuple_variant(self, _name: &'static str, _idx: u32, _var: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant> { Err(Error::ExpectedString) }
328 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { Err(Error::ExpectedString) }
329 fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { Err(Error::ExpectedString) }
330 fn serialize_struct_variant(self, _name: &'static str, _idx: u32, _var: &'static str, _len: usize) -> Result<Self::SerializeStructVariant> { Err(Error::ExpectedString) }
331 }
332
333 let mut collector = KeyCollector(String::new());
334 key.serialize(&mut collector)?;
335 self.serializer.last_key = Some(collector.0);
336 Ok(())
337 }
338
339 fn serialize_value<T>(&mut self, value: &T) -> Result<()>
340 where
341 T: ?Sized + Serialize,
342 {
343 value.serialize(&mut *self.serializer)
344 }
345
346 fn end(self) -> Result<()> {
347 if !self.is_root {
348 self.serializer.indent -= 1;
349 self.serializer.write_indent()?;
350 self.serializer.writer.write_all(b"}\n")?;
351 }
352 Ok(())
353 }
354}
355
356pub struct StructSerializer<'a, W> {
357 map: MapSerializer<'a, W>,
358}
359
360impl<'a, W: Write> ser::SerializeStruct for StructSerializer<'a, W> {
361 type Ok = ();
362 type Error = Error;
363
364 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
365 where
366 T: ?Sized + Serialize,
367 {
368 use ser::SerializeMap;
369 self.map.serialize_entry(key, value)
370 }
371
372 fn end(self) -> Result<()> {
373 use ser::SerializeMap;
374 self.map.end()
375 }
376}