query_params_serialize/lib.rs
1#[macro_use]
2extern crate failure;
3extern crate bytes;
4extern crate serde;
5
6mod errors;
7
8pub use errors::{Error, Result};
9
10use std::fmt::Write;
11
12use bytes::{Buf, BytesMut};
13use serde::{ser, Serialize};
14
15pub struct Serializer {
16 // This string starts empty and JSON is appended as values are serialized.
17 output: BytesMut,
18}
19
20// By convention, the public API of a Serde serializer is one or more `to_abc`
21// functions such as `to_string`, `to_bytes`, or `to_writer` depending on what
22// Rust types the serializer is able to produce as output.
23//
24// This basic serializer supports only `to_string`.
25pub fn to_string<T>(value: &T) -> Result<String>
26where
27 T: Serialize,
28{
29 let mut serializer = Serializer {
30 output: BytesMut::with_capacity(128),
31 };
32 value.serialize(&mut serializer)?;
33 let output = unsafe { std::str::from_utf8_unchecked(serializer.output.bytes()) };
34 // Ok(match output.strip_suffix('&') {
35 // Some(output) => output.to_owned(),
36 // None => output.to_owned(),
37 // })
38 Ok(output.to_owned())
39}
40
41impl<'a> ser::Serializer for &'a mut Serializer {
42 // The output type produced by this `Serializer` during successful
43 // serialization. Most serializers that produce text or binary output should
44 // set `Ok = ()` and serialize into an `io::Write` or buffer contained
45 // within the `Serializer` instance, as happens here. Serializers that build
46 // in-memory data structures may be simplified by using `Ok` to propagate
47 // the data structure around.
48 type Ok = ();
49
50 // The error type when some error occurs during serialization.
51 type Error = Error;
52
53 // Associated types for keeping track of additional state while serializing
54 // compound data structures like sequences and maps. In this case no
55 // additional state is required beyond what is already stored in the
56 // Serializer struct.
57 type SerializeSeq = Self;
58 type SerializeTuple = Self;
59 type SerializeTupleStruct = Self;
60 type SerializeTupleVariant = Self;
61 type SerializeMap = Self;
62 type SerializeStruct = Self;
63 type SerializeStructVariant = Self;
64
65 // Here we go with the simple methods. The following 12 methods receive one
66 // of the primitive types of the data model and map it to JSON by appending
67 // into the output string.
68 fn serialize_bool(self, v: bool) -> Result<()> {
69 self.output.write_str(if v { "true" } else { "false" })?;
70 Ok(())
71 }
72
73 // JSON does not distinguish between different sizes of integers, so all
74 // signed integers will be serialized the same and all unsigned integers
75 // will be serialized the same. Other formats, especially compact binary
76 // formats, may need independent logic for the different sizes.
77 fn serialize_i8(self, v: i8) -> Result<()> {
78 self.serialize_i64(i64::from(v))
79 }
80
81 fn serialize_i16(self, v: i16) -> Result<()> {
82 self.serialize_i64(i64::from(v))
83 }
84
85 fn serialize_i32(self, v: i32) -> Result<()> {
86 self.serialize_i64(i64::from(v))
87 }
88
89 // Not particularly efficient but this is example code anyway. A more
90 // performant approach would be to use the `itoa` crate.
91 fn serialize_i64(self, v: i64) -> Result<()> {
92 write!(self.output, "{}", v)?;
93 Ok(())
94 }
95
96 fn serialize_u8(self, v: u8) -> Result<()> {
97 write!(self.output, "{}", v)?;
98 Ok(())
99 }
100
101 fn serialize_u16(self, v: u16) -> Result<()> {
102 write!(self.output, "{}", v)?;
103 Ok(())
104 }
105
106 fn serialize_u32(self, v: u32) -> Result<()> {
107 write!(self.output, "{}", v)?;
108 Ok(())
109 }
110
111 fn serialize_u64(self, v: u64) -> Result<()> {
112 write!(self.output, "{}", v)?;
113 Ok(())
114 }
115
116 fn serialize_f32(self, v: f32) -> Result<()> {
117 write!(self.output, "{:.8}", v)?;
118 Ok(())
119 }
120
121 fn serialize_f64(self, v: f64) -> Result<()> {
122 write!(self.output, "{:.8}", v)?;
123 Ok(())
124 }
125
126 // Serialize a char as a single-character string. Other formats may
127 // represent this differently.
128 fn serialize_char(self, v: char) -> Result<()> {
129 self.output.write_char(v)?;
130 Ok(())
131 }
132
133 // This only works for strings that don't require escape sequences but you
134 // get the idea. For example it would emit invalid JSON if the input string
135 // contains a '"' character.
136 fn serialize_str(self, v: &str) -> Result<()> {
137 self.output.write_str(v)?;
138 Ok(())
139 }
140
141 // Serialize a byte array as an array of bytes. Could also use a base64
142 // string here. Binary formats will typically represent byte arrays more
143 // compactly.
144 fn serialize_bytes(self, v: &[u8]) -> Result<()> {
145 use serde::ser::SerializeSeq;
146 let mut seq = self.serialize_seq(Some(v.len()))?;
147 for byte in v {
148 seq.serialize_element(byte)?;
149 }
150 seq.end()
151 }
152
153 // An absent optional is represented as the JSON `null`.
154 fn serialize_none(self) -> Result<()> {
155 self.serialize_unit()
156 }
157
158 // A present optional is represented as just the contained value. Note that
159 // this is a lossy representation. For example the values `Some(())` and
160 // `None` both serialize as just `null`. Unfortunately this is typically
161 // what people expect when working with JSON. Other formats are encouraged
162 // to behave more intelligently if possible.
163 fn serialize_some<T>(self, value: &T) -> Result<()>
164 where
165 T: ?Sized + Serialize,
166 {
167 value.serialize(self)
168 }
169
170 // In Serde, unit means an anonymous value containing no data. Map this to
171 // JSON as `null`.
172 fn serialize_unit(self) -> Result<()> {
173 // self.output.write_str("null")?;
174 Ok(())
175 }
176
177 // Unit struct means a named value containing no data. Again, since there is
178 // no data, map this to JSON as `null`. There is no need to serialize the
179 // name in most formats.
180 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
181 // self.serialize_unit()
182 Ok(())
183 }
184
185 // When serializing a unit variant (or any other kind of variant), formats
186 // can choose whether to keep track of it by index or by name. Binary
187 // formats typically use the index of the variant and human-readable formats
188 // typically use the name.
189 fn serialize_unit_variant(
190 self,
191 _name: &'static str,
192 _variant_index: u32,
193 variant: &'static str,
194 ) -> Result<()> {
195 self.serialize_str(variant)
196 }
197
198 // As is done here, serializers are encouraged to treat newtype structs as
199 // insignificant wrappers around the data they contain.
200 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
201 where
202 T: ?Sized + Serialize,
203 {
204 value.serialize(self)
205 }
206
207 // Note that newtype variant (and all of the other variant serialization
208 // methods) refer exclusively to the "externally tagged" enum
209 // representation.
210 //
211 // Serialize this to JSON in externally tagged form as `{ NAME: VALUE }`.
212 fn serialize_newtype_variant<T>(
213 self,
214 _name: &'static str,
215 _variant_index: u32,
216 variant: &'static str,
217 value: &T,
218 ) -> Result<()>
219 where
220 T: ?Sized + Serialize,
221 {
222 variant.serialize(&mut *self)?;
223 self.output.write_str("=")?;
224 value.serialize(&mut *self)?;
225 Ok(())
226 }
227
228 // Now we get to the serialization of compound types.
229 //
230 // The start of the sequence, each value, and the end are three separate
231 // method calls. This one is responsible only for serializing the start,
232 // which in JSON is `[`.
233 //
234 // The length of the sequence may or may not be known ahead of time. This
235 // doesn't make a difference in JSON because the length is not represented
236 // explicitly in the serialized form. Some serializers may only be able to
237 // support sequences for which the length is known up front.
238 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
239 Ok(self)
240 }
241
242 // Tuples look just like sequences in JSON. Some formats may be able to
243 // represent tuples more efficiently by omitting the length, since tuple
244 // means that the corresponding `Deserialize implementation will know the
245 // length without needing to look at the serialized data.
246 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
247 self.serialize_seq(Some(len))
248 }
249
250 // Tuple structs look just like sequences in JSON.
251 fn serialize_tuple_struct(
252 self,
253 _name: &'static str,
254 len: usize,
255 ) -> Result<Self::SerializeTupleStruct> {
256 self.serialize_seq(Some(len))
257 }
258
259 // Tuple variants are represented in JSON as `{ NAME: [DATA...] }`. Again
260 // this method is only responsible for the externally tagged representation.
261 fn serialize_tuple_variant(
262 self,
263 _name: &'static str,
264 _variant_index: u32,
265 variant: &'static str,
266 _len: usize,
267 ) -> Result<Self::SerializeTupleVariant> {
268 variant.serialize(&mut *self)?;
269 self.output.write_str("=")?;
270 Ok(self)
271 }
272
273 // Maps are represented in JSON as `{ K: V, K: V, ... }`.
274 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
275 Ok(self)
276 }
277
278 // Structs look just like maps in JSON. In particular, JSON requires that we
279 // serialize the field names of the struct. Other formats may be able to
280 // omit the field names when serializing structs because the corresponding
281 // Deserialize implementation is required to know what the keys are without
282 // looking at the serialized data.
283 fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
284 self.serialize_map(Some(len))
285 }
286
287 // Struct variants are represented in JSON as `{ NAME: { K: V, ... } }`.
288 // This is the externally tagged representation.
289 fn serialize_struct_variant(
290 self,
291 _name: &'static str,
292 _variant_index: u32,
293 variant: &'static str,
294 _len: usize,
295 ) -> Result<Self::SerializeStructVariant> {
296 variant.serialize(&mut *self)?;
297 Ok(self)
298 }
299}
300
301// The following 7 impls deal with the serialization of compound types like
302// sequences and maps. Serialization of such types is begun by a Serializer
303// method and followed by zero or more calls to serialize individual elements of
304// the compound type and one call to end the compound type.
305//
306// This impl is SerializeSeq so these methods are called after `serialize_seq`
307// is called on the Serializer.
308impl<'a> ser::SerializeSeq for &'a mut Serializer {
309 // Must match the `Ok` type of the serializer.
310 type Ok = ();
311 // Must match the `Error` type of the serializer.
312 type Error = Error;
313
314 // Serialize a single element of the sequence.
315 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
316 where
317 T: ?Sized + Serialize,
318 {
319 value.serialize(&mut **self)?;
320 self.output.write_str(",")?;
321 Ok(())
322 }
323
324 // Close the sequence.
325 fn end(self) -> Result<()> {
326 if self.output.ends_with(&[',' as u8]) {
327 let _ = self.output.split_off(self.output.len() - 1);
328 }
329 Ok(())
330 }
331}
332
333// Same thing but for tuples.
334impl<'a> ser::SerializeTuple for &'a mut Serializer {
335 type Ok = ();
336 type Error = Error;
337
338 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
339 where
340 T: ?Sized + Serialize,
341 {
342 value.serialize(&mut **self)?;
343 self.output.write_str(",")?;
344 Ok(())
345 }
346
347 fn end(self) -> Result<()> {
348 if self.output.ends_with(&[',' as u8]) {
349 let _ = self.output.split_off(self.output.len() - 1);
350 }
351 Ok(())
352 }
353}
354
355// Same thing but for tuple structs.
356impl<'a> ser::SerializeTupleStruct for &'a mut Serializer {
357 type Ok = ();
358 type Error = Error;
359
360 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
361 where
362 T: ?Sized + Serialize,
363 {
364 value.serialize(&mut **self)?;
365 self.output.write_str(",")?;
366 Ok(())
367 }
368
369 fn end(self) -> Result<()> {
370 if self.output.ends_with(&[',' as u8]) {
371 let _ = self.output.split_off(self.output.len() - 1);
372 }
373 Ok(())
374 }
375}
376
377// Tuple variants are a little different. Refer back to the
378// `serialize_tuple_variant` method above:
379//
380// self.output.write_str("{")?;
381// variant.serialize(&mut *self)?;
382// self.output.write_str(":[")?;
383//
384// So the `end` method in this impl is responsible for closing both the `]` and
385// the `}`.
386impl<'a> ser::SerializeTupleVariant for &'a mut Serializer {
387 type Ok = ();
388 type Error = Error;
389
390 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
391 where
392 T: ?Sized + Serialize,
393 {
394 value.serialize(&mut **self)?;
395 self.output.write_str(",")?;
396 Ok(())
397 }
398
399 fn end(self) -> Result<()> {
400 if self.output.ends_with(&[',' as u8]) {
401 let _ = self.output.split_off(self.output.len() - 1);
402 }
403 Ok(())
404 }
405}
406
407// Some `Serialize` types are not able to hold a key and value in memory at the
408// same time so `SerializeMap` implementations are required to support
409// `serialize_key` and `serialize_value` individually.
410//
411// There is a third optional method on the `SerializeMap` trait. The
412// `serialize_entry` method allows serializers to optimize for the case where
413// key and value are both available simultaneously. In JSON it doesn't make a
414// difference so the default behavior for `serialize_entry` is fine.
415impl<'a> ser::SerializeMap for &'a mut Serializer {
416 type Ok = ();
417 type Error = Error;
418
419 // The Serde data model allows map keys to be any serializable type. JSON
420 // only allows string keys so the implementation below will produce invalid
421 // JSON if the key serializes as something other than a string.
422 //
423 // A real JSON serializer would need to validate that map keys are strings.
424 // This can be done by using a different Serializer to serialize the key
425 // (instead of `&mut **self`) and having that other serializer only
426 // implement `serialize_str` and return an error on any other data type.
427 fn serialize_key<T>(&mut self, key: &T) -> Result<()>
428 where
429 T: ?Sized + Serialize,
430 {
431 self.output.write_str(",")?;
432 key.serialize(&mut **self)
433 }
434
435 // It doesn't make a difference whether the colon is printed at the end of
436 // `serialize_key` or at the beginning of `serialize_value`. In this case
437 // the code is a bit simpler having it here.
438 fn serialize_value<T>(&mut self, value: &T) -> Result<()>
439 where
440 T: ?Sized + Serialize,
441 {
442 self.output.write_str("=")?;
443 value.serialize(&mut **self)
444 }
445
446 fn end(self) -> Result<()> {
447 Ok(())
448 }
449}
450
451// Structs are like maps in which the keys are constrained to be compile-time
452// constant strings.
453impl<'a> ser::SerializeStruct for &'a mut Serializer {
454 type Ok = ();
455 type Error = Error;
456
457 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
458 where
459 T: ?Sized + Serialize,
460 {
461 key.serialize(&mut **self)?;
462 self.output.write_str("=")?;
463 value.serialize(&mut **self)?;
464 self.output.write_str("&")?;
465 Ok(())
466 }
467
468 fn end(self) -> Result<()> {
469 if self.output.ends_with(&['&' as u8]) {
470 let _ = self.output.split_off(self.output.len() - 1);
471 }
472 Ok(())
473 }
474}
475
476// Similar to `SerializeTupleVariant`, here the `end` method is responsible for
477// closing both of the curly braces opened by `serialize_struct_variant`.
478impl<'a> ser::SerializeStructVariant for &'a mut Serializer {
479 type Ok = ();
480 type Error = Error;
481
482 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
483 where
484 T: ?Sized + Serialize,
485 {
486 key.serialize(&mut **self)?;
487 self.output.write_str("=")?;
488 value.serialize(&mut **self)
489 }
490
491 fn end(self) -> Result<()> {
492 Ok(())
493 }
494}
495
496////////////////////////////////////////////////////////////////////////////////