rustybit_serde_bencode/
ser.rs

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