1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Generic serialization framework.
//! # For Developers who want to serialize objects
//! Implement the `Serialize` trait for the type of objects you want to serialize. Call methods of
//! the `serializer` object. For which methods to call and how to do so, look at the documentation
//! of the `Serializer` trait.
//!
//! # For Serialization Format Developers
//! Implement the `Serializer` trait for a structure that contains fields that enable it to write
//! the serialization result to your target. When a method's argument is an object of type
//! `Serialize`, you can either forward the serializer object (`self`) or create a new one,
//! depending on the quirks of your format.

#[cfg(feature = "std")]
use std::error;
#[cfg(not(feature = "std"))]
use error;

#[cfg(feature = "unstable")]
use core::cell::RefCell;

use core::fmt::Display;

pub mod impls;

///////////////////////////////////////////////////////////////////////////////

/// `Error` is a trait that allows a `Serialize` to generically create a
/// `Serializer` error.
pub trait Error: Sized + error::Error {
    /// Raised when there is a general error when serializing a type.
    fn custom<T: Display>(msg: T) -> Self;
}

///////////////////////////////////////////////////////////////////////////////

/// A trait that describes a type that can be serialized by a `Serializer`.
pub trait Serialize {
    /// Serializes this value into this serializer.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer;
}

///////////////////////////////////////////////////////////////////////////////

/// A trait that describes a type that can serialize a stream of values into the underlying format.
///
/// # For `Serialize` Developers
/// Non-aggregate types like integers and strings can be serialized directly by calling the
/// appropriate function. For Aggregate types there's an initial `serialize_T` method that yields
/// a State object that you should not interact with. For each part of the aggregate there's a
/// `serialize_T_elt` method that allows you to pass values or key/value pairs. The types of the
/// values or the keys may change between calls, but the serialization format may not necessarily
/// accept it. The `serialize_T_elt` method also takes a mutable reference to the state object.
/// Make sure that you always use the same state object and only the state object that was returned
/// by the `serialize_T` method. Finally, when your object is done, call the `serialize_T_end`
/// method and pass the state object by value
///
/// # For Serialization Format Developers
/// If your format has different situations where it accepts different types, create a
/// `Serializer` for each situation. You can create the sub-`Serializer` in one of the aggregate
/// `serialize_T` methods and return it as a state object. Remember to also set the corresponding
/// associated type `TState`. In the `serialize_T_elt` methods you will be given a mutable
/// reference to that state. You do not need to do any additional checks for the correctness of the
/// state object, as it is expected that the user will not modify it. Due to the generic nature
/// of the `Serialize` impls, modifying the object is impossible on stable Rust.
pub trait Serializer {
    /// Trickery to enforce correct use of the `Serialize` trait. Every
    /// `Serializer` should set `Ok = ()`.
    type Ok;

    /// The error type when some error occurs during serialization.
    type Error: Error;

    /// Type returned from `serialize_seq` and `serialize_seq_fixed_size` for
    /// serializing the content of the sequence.
    type SerializeSeq: SerializeSeq<Ok=Self::Ok, Error=Self::Error>;

    /// Type returned from `serialize_tuple` for serializing the content of the
    /// tuple.
    type SerializeTuple: SerializeTuple<Ok=Self::Ok, Error=Self::Error>;

    /// Type returned from `serialize_tuple_struct` for serializing the content
    /// of the tuple struct.
    type SerializeTupleStruct: SerializeTupleStruct<Ok=Self::Ok, Error=Self::Error>;

    /// Type returned from `serialize_tuple_variant` for serializing the content
    /// of the tuple variant.
    type SerializeTupleVariant: SerializeTupleVariant<Ok=Self::Ok, Error=Self::Error>;

    /// Type returned from `serialize_map` for serializing the content of the
    /// map.
    type SerializeMap: SerializeMap<Ok=Self::Ok, Error=Self::Error>;

    /// Type returned from `serialize_struct` for serializing the content of the
    /// struct.
    type SerializeStruct: SerializeStruct<Ok=Self::Ok, Error=Self::Error>;

    /// Type returned from `serialize_struct_variant` for serializing the
    /// content of the struct variant.
    type SerializeStructVariant: SerializeStructVariant<Ok=Self::Ok, Error=Self::Error>;

    /// Serializes a `bool` value.
    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;

    /// Serializes an `isize` value. If the format does not differentiate
    /// between `isize` and `i64`, a reasonable implementation would be to cast
    /// the value to `i64` and forward to `serialize_i64`.
    fn serialize_isize(self, v: isize) -> Result<Self::Ok, Self::Error>;

    /// Serializes an `i8` value. If the format does not differentiate between
    /// `i8` and `i64`, a reasonable implementation would be to cast the value
    /// to `i64` and forward to `serialize_i64`.
    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>;

    /// Serializes an `i16` value. If the format does not differentiate between
    /// `i16` and `i64`, a reasonable implementation would be to cast the value
    /// to `i64` and forward to `serialize_i64`.
    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>;

    /// Serializes an `i32` value. If the format does not differentiate between
    /// `i32` and `i64`, a reasonable implementation would be to cast the value
    /// to `i64` and forward to `serialize_i64`.
    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>;

    /// Serializes an `i64` value.
    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;

    /// Serializes a `usize` value. If the format does not differentiate between
    /// `usize` and `u64`, a reasonable implementation would be to cast the
    /// value to `u64` and forward to `serialize_u64`.
    fn serialize_usize(self, v: usize) -> Result<Self::Ok, Self::Error>;

    /// Serializes a `u8` value. If the format does not differentiate between
    /// `u8` and `u64`, a reasonable implementation would be to cast the value
    /// to `u64` and forward to `serialize_u64`.
    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>;

    /// Serializes a `u16` value. If the format does not differentiate between
    /// `u16` and `u64`, a reasonable implementation would be to cast the value
    /// to `u64` and forward to `serialize_u64`.
    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>;

    /// Serializes a `u32` value. If the format does not differentiate between
    /// `u32` and `u64`, a reasonable implementation would be to cast the value
    /// to `u64` and forward to `serialize_u64`.
    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>;

    /// `Serializes a `u64` value.
    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;

    /// Serializes an `f32` value. If the format does not differentiate between
    /// `f32` and `f64`, a reasonable implementation would be to cast the value
    /// to `f64` and forward to `serialize_f64`.
    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>;

    /// Serializes an `f64` value.
    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>;

    /// Serializes a character. If the format does not support characters,
    /// it is reasonable to serialize it as a single element `str` or a `u32`.
    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>;

    /// Serializes a `&str`.
    fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error>;

    /// Enables serializers to serialize byte slices more compactly or more
    /// efficiently than other types of slices. If no efficient implementation
    /// is available, a reasonable implementation would be to forward to
    /// `serialize_seq`. If forwarded, the implementation looks usually just like this:
    /// ```rust
    /// let mut seq = self.serialize_seq(Some(value.len()))?;
    /// for b in value {
    ///     seq.serialize_element(b)?;
    /// }
    /// seq.end()
    /// ```
    fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error>;

    /// Serializes a `()` value. It's reasonable to just not serialize anything.
    fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;

    /// Serializes a unit struct value. A reasonable implementation would be to
    /// forward to `serialize_unit`.
    fn serialize_unit_struct(
        self,
        name: &'static str,
    ) -> Result<Self::Ok, Self::Error>;

    /// Serializes a unit variant, otherwise known as a variant with no
    /// arguments. A reasonable implementation would be to forward to
    /// `serialize_unit`.
    fn serialize_unit_variant(
        self,
        name: &'static str,
        variant_index: usize,
        variant: &'static str,
    ) -> Result<Self::Ok, Self::Error>;

    /// Allows a tuple struct with a single element, also known as a newtype
    /// struct, to be more efficiently serialized than a tuple struct with
    /// multiple items. A reasonable implementation would be to forward to
    /// `serialize_tuple_struct` or to just serialize the inner value without wrapping.
    fn serialize_newtype_struct<T: ?Sized + Serialize>(
        self,
        name: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>;

    /// Allows a variant with a single item to be more efficiently serialized
    /// than a variant with multiple items. A reasonable implementation would be
    /// to forward to `serialize_tuple_variant`.
    fn serialize_newtype_variant<T: ?Sized + Serialize>(
        self,
        name: &'static str,
        variant_index: usize,
        variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>;

    /// Serializes a `None` value.
    fn serialize_none(self) -> Result<Self::Ok, Self::Error>;

    /// Serializes a `Some(...)` value.
    fn serialize_some<T: ?Sized + Serialize>(
        self,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>;

    /// Begins to serialize a sequence. This call must be followed by zero or
    /// more calls to `serialize_seq_elt`, then a call to `serialize_seq_end`.
    fn serialize_seq(
        self,
        len: Option<usize>,
    ) -> Result<Self::SerializeSeq, Self::Error>;

    /// Begins to serialize a sequence whose length will be known at
    /// deserialization time. This call must be followed by zero or more calls
    /// to `serialize_seq_elt`, then a call to `serialize_seq_end`. A reasonable
    /// implementation would be to forward to `serialize_seq`.
    fn serialize_seq_fixed_size(
        self,
        size: usize,
    ) -> Result<Self::SerializeSeq, Self::Error>;

    /// Begins to serialize a tuple. This call must be followed by zero or more
    /// calls to `serialize_tuple_elt`, then a call to `serialize_tuple_end`. A
    /// reasonable implementation would be to forward to `serialize_seq`.
    fn serialize_tuple(
        self,
        len: usize,
    ) -> Result<Self::SerializeTuple, Self::Error>;

    /// Begins to serialize a tuple struct. This call must be followed by zero
    /// or more calls to `serialize_tuple_struct_elt`, then a call to
    /// `serialize_tuple_struct_end`. A reasonable implementation would be to
    /// forward to `serialize_tuple`.
    fn serialize_tuple_struct(
        self,
        name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error>;

    /// Begins to serialize a tuple variant. This call must be followed by zero
    /// or more calls to `serialize_tuple_variant_elt`, then a call to
    /// `serialize_tuple_variant_end`. A reasonable implementation would be to
    /// forward to `serialize_tuple_struct`.
    fn serialize_tuple_variant(
        self,
        name: &'static str,
        variant_index: usize,
        variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error>;

    /// Begins to serialize a map. This call must be followed by zero or more
    /// calls to `serialize_map_key` and `serialize_map_value`, then a call to
    /// `serialize_map_end`.
    fn serialize_map(
        self,
        len: Option<usize>,
    ) -> Result<Self::SerializeMap, Self::Error>;

    /// Begins to serialize a struct. This call must be followed by zero or more
    /// calls to `serialize_struct_elt`, then a call to `serialize_struct_end`.
    fn serialize_struct(
        self,
        name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error>;

    /// Begins to serialize a struct variant. This call must be followed by zero
    /// or more calls to `serialize_struct_variant_elt`, then a call to
    /// `serialize_struct_variant_end`.
    fn serialize_struct_variant(
        self,
        name: &'static str,
        variant_index: usize,
        variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error>;
}

/// Returned from `Serializer::serialize_seq` and
/// `Serializer::serialize_seq_fixed_size`.
pub trait SerializeSeq {
    /// Trickery to enforce correct use of the `Serialize` trait. Every
    /// `SerializeSeq` should set `Ok = ()`.
    type Ok;

    /// The error type when some error occurs during serialization.
    type Error: Error;

    /// Serializes a sequence element.
    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;

    /// Finishes serializing a sequence.
    fn end(self) -> Result<Self::Ok, Self::Error>;
}

/// Returned from `Serializer::serialize_tuple`.
pub trait SerializeTuple {
    /// Trickery to enforce correct use of the `Serialize` trait. Every
    /// `SerializeTuple` should set `Ok = ()`.
    type Ok;

    /// The error type when some error occurs during serialization.
    type Error: Error;

    /// Serializes a tuple element.
    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;

    /// Finishes serializing a tuple.
    fn end(self) -> Result<Self::Ok, Self::Error>;
}

/// Returned from `Serializer::serialize_tuple_struct`.
pub trait SerializeTupleStruct {
    /// Trickery to enforce correct use of the `Serialize` trait. Every
    /// `SerializeTupleStruct` should set `Ok = ()`.
    type Ok;

    /// The error type when some error occurs during serialization.
    type Error: Error;

    /// Serializes a tuple struct element.
    fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;

    /// Finishes serializing a tuple struct.
    fn end(self) -> Result<Self::Ok, Self::Error>;
}

/// Returned from `Serializer::serialize_tuple_variant`.
pub trait SerializeTupleVariant {
    /// Trickery to enforce correct use of the `Serialize` trait. Every
    /// `SerializeTupleVariant` should set `Ok = ()`.
    type Ok;

    /// The error type when some error occurs during serialization.
    type Error: Error;

    /// Serializes a tuple variant element.
    fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;

    /// Finishes serializing a tuple variant.
    fn end(self) -> Result<Self::Ok, Self::Error>;
}

/// Returned from `Serializer::serialize_map`.
pub trait SerializeMap {
    /// Trickery to enforce correct use of the `Serialize` trait. Every
    /// `SerializeMap` should set `Ok = ()`.
    type Ok;

    /// The error type when some error occurs during serialization.
    type Error: Error;

    /// Serialize a map key.
    fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error>;

    /// Serialize a map value.
    fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;

    /// Finishes serializing a map.
    fn end(self) -> Result<Self::Ok, Self::Error>;
}

/// Returned from `Serializer::serialize_struct`.
pub trait SerializeStruct {
    /// Trickery to enforce correct use of the `Serialize` trait. Every
    /// `SerializeStruct` should set `Ok = ()`.
    type Ok;

    /// The error type when some error occurs during serialization.
    type Error: Error;

    /// Serializes a struct field.
    fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;

    /// Finishes serializing a struct.
    fn end(self) -> Result<Self::Ok, Self::Error>;
}

/// Returned from `Serializer::serialize_struct_variant`.
pub trait SerializeStructVariant {
    /// Trickery to enforce correct use of the `Serialize` trait. Every
    /// `SerializeStructVariant` should set `Ok = ()`.
    type Ok;

    /// The error type when some error occurs during serialization.
    type Error: Error;

    /// Serialize a struct variant element.
    fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;

    /// Finishes serializing a struct variant.
    fn end(self) -> Result<Self::Ok, Self::Error>;
}

/// A wrapper type for iterators that implements `Serialize` for iterators whose items implement
/// `Serialize`. Don't use multiple times. Create new versions of this with the `iterator` function
/// every time you want to serialize an iterator.
#[cfg(feature = "unstable")]
pub struct Iterator<I>(RefCell<Option<I>>)
    where <I as IntoIterator>::Item: Serialize,
          I: IntoIterator;

/// Creates a temporary type that can be passed to any function expecting a `Serialize` and will
/// serialize the given iterator as a sequence
#[cfg(feature = "unstable")]
pub fn iterator<I>(iter: I) -> Iterator<I>
    where <I as IntoIterator>::Item: Serialize,
          I: IntoIterator
{
    Iterator(RefCell::new(Some(iter)))
}