bytekey_fix/
ser.rs

1use byteorder::{WriteBytesExt, BE};
2use serde::{self, Serialize};
3use std::error::Error as StdError;
4use std::fmt;
5use std::io::{self, Write};
6use std::mem::transmute;
7use std::{self, i16, i32, i64, i8};
8
9/// A serializer for a byte format that preserves lexicographic sort order.
10///
11/// The byte format is designed with a few goals:
12///
13/// * Order must be preserved
14/// * Serialized representations should be as compact as possible
15/// * Type information is *not* serialized with values
16///
17/// #### Supported Data Types
18///
19/// ##### Unsigned Integers
20///
21/// `u8`, `u16`, `u32`, and `u64` are serialized into 1, 2, 4, and 8 bytes of output, respectively.
22/// Order is preserved by encoding the bytes in big-endian (most-significant bytes first) format.
23/// `usize` is always serialized as if it were `u64`.
24///
25/// The `Serializer` also supports variable-length serialization of unsigned integers via the
26/// `serialize_var_u64` method. Smaller magnitude values (closer to 0) will encode into fewer
27/// bytes.
28///
29/// ##### Signed Integers
30///
31/// `i8`, `i16`, `i32`, and `i64` are encoded into 1, 2, 4, and 8 bytes of output, respectively.
32/// Order is preserved by taking the bitwise complement of the value, and encoding the resulting
33/// bytes in big-endian format. `isize` is always serialized as if it were `i64`.
34///
35/// The `Serializer` also supports variable-length serialization of signed integers via the
36/// `serialize_var_i64` method. Smaller magnitude values (closer to 0) will encode into fewer
37/// bytes.
38///
39/// ##### Floating Point Numbers
40///
41/// `f32` and `f64` are serialized into 4 and 8 bytes of output, respectively. Order is preserved
42/// by encoding the value, or the bitwise complement of the value if negative, into bytes in
43/// big-endian format. `NAN` values will sort after all other values. In general, it is unwise to
44/// use IEEE 754 floating point values in keys, because rounding errors are pervasive.  It is
45/// typically hard or impossible to use an approximate 'epsilon' approach when using keys for
46/// lookup.
47///
48/// ##### Characters
49///
50/// Characters are serialized into between 1 and 4 bytes of output. The resulting length is
51/// equivalent to the result of `char::len_utf8`.
52///
53/// ##### Booleans
54///
55/// Booleans are serialized into a single byte of output. `false` values will sort before `true`
56/// values.
57///
58/// ##### Options
59///
60/// An optional wrapper type adds a 1 byte overhead to the wrapped data type. `None` values will
61/// sort before `Some` values.
62///
63/// ##### Structs, Tuples and Fixed-Size Arrays
64///
65/// Structs and tuples are serialized by serializing their consituent fields in order with no
66/// prefix, suffix, or padding bytes.
67///
68/// ##### Enums
69///
70/// Enums are encoded with a `u32` variant index tag, plus the consituent fields in the case of an
71/// enum-struct.
72///
73/// ##### Sequences, Strings and Maps
74///
75/// Sequences are ordered from the most significant to the least. Strings are serialized into their
76/// natural UTF8 representation.
77///
78/// The ordering of sequential elements follows the `Ord` implementation of `slice`, that is, from
79/// left to write when viewing a `Vec` printed via the `{:?}` formatter.
80///
81/// The caveat with these types is that their length must be known before deserialization. This is
82/// because the length is *not* serialized prior to the elements in order to preserve ordering and
83/// there is no trivial way to tokenise between sequential elements that 1. does not corrupt
84/// ordering and 2. may not confuse tokenisation with following elements of a different type during
85/// tuple or struct deserialization. Thus, when deserializing sequences, strings and maps, the
86/// process will only be considered complete once the inner `reader` produces an EOF character.
87#[derive(Debug)]
88pub struct Serializer<W>
89    where
90        W: Write,
91{
92    writer: W,
93}
94
95/// Errors that might occur while serializing.
96#[derive(Debug)]
97pub enum Error {
98    /// Errors that might occur during serialization.
99    ///
100    /// E.g. the `Serialize` impl for `Mutex<T>` might return an error because the mutex is
101    /// poisoned.
102    Message(String),
103    Io(io::Error),
104}
105
106/// Shorthand for `Result<T, bytekey::ser::Error>`.
107pub type Result<T> = std::result::Result<T, Error>;
108
109/// Serialize data into a vector of `u8` bytes.
110///
111/// #### Usage
112///
113/// ```
114/// # use bytekey::serialize;
115/// assert_eq!(vec!(0x00, 0x00, 0x00, 0x2A), serialize(&42u32).unwrap());
116/// assert_eq!(vec!(0x66, 0x69, 0x7A, 0x7A, 0x62, 0x75, 0x7A, 0x7A, 0x00), serialize(&"fizzbuzz").unwrap());
117/// assert_eq!(vec!(0x2A, 0x66, 0x69, 0x7A, 0x7A, 0x00), serialize(&(42u8, "fizz")).unwrap());
118/// ```
119pub fn serialize<T>(v: &T) -> Result<Vec<u8>>
120    where
121        T: Serialize,
122{
123    let mut bytes = vec![];
124    {
125        let mut buffered = io::BufWriter::new(&mut bytes);
126        serialize_into(&mut buffered, v)?;
127    }
128    Ok(bytes)
129}
130
131/// Serialize data into the given vector of `u8` bytes.
132///
133/// #### Usage
134///
135/// ```
136/// # use bytekey::serialize_into;
137/// let mut bytes = vec![];
138/// bytekey::serialize_into(&mut bytes, &5u8).unwrap();
139/// assert_eq!(vec![5u8], bytes.clone());
140/// bytekey::serialize_into(&mut bytes, &10u8).unwrap();
141/// assert_eq!(vec![5u8, 10], bytes.clone());
142/// ```
143pub fn serialize_into<W, T>(writer: W, value: &T) -> Result<()>
144    where
145        W: Write,
146        T: Serialize,
147{
148    let mut serializer = Serializer::new(writer);
149    value.serialize(&mut serializer)
150}
151
152impl<W> Serializer<W>
153    where
154        W: Write,
155{
156    /// Creates a new ordered bytes encoder whose output will be written to the provided writer.
157    pub fn new(writer: W) -> Serializer<W> {
158        Serializer { writer: writer }
159    }
160
161    /// Encode a `u64` into a variable number of bytes.
162    ///
163    /// The variable-length encoding scheme uses between 1 and 9 bytes depending on the value.
164    /// Smaller magnitude (closer to 0) `u64`s will encode to fewer bytes.
165    ///
166    /// ##### Encoding
167    ///
168    /// The encoding uses the first 4 bits to store the number of trailing bytes, between 0 and 8.
169    /// Subsequent bits are the input value in big-endian format with leading 0 bytes removed.
170    ///
171    /// ##### Encoded Size
172    ///
173    /// <table>
174    ///     <tr>
175    ///         <th>range</th>
176    ///         <th>size (bytes)</th>
177    ///     </tr>
178    ///     <tr>
179    ///         <td>[0, 2<sup>4</sup>)</td>
180    ///         <td>1</td>
181    ///     </tr>
182    ///     <tr>
183    ///         <td>[2<sup>4</sup>, 2<sup>12</sup>)</td>
184    ///         <td>2</td>
185    ///     </tr>
186    ///     <tr>
187    ///         <td>[2<sup>12</sup>, 2<sup>20</sup>)</td>
188    ///         <td>3</td>
189    ///     </tr>
190    ///     <tr>
191    ///         <td>[2<sup>20</sup>, 2<sup>28</sup>)</td>
192    ///         <td>4</td>
193    ///     </tr>
194    ///     <tr>
195    ///         <td>[2<sup>28</sup>, 2<sup>36</sup>)</td>
196    ///         <td>5</td>
197    ///     </tr>
198    ///     <tr>
199    ///         <td>[2<sup>36</sup>, 2<sup>44</sup>)</td>
200    ///         <td>6</td>
201    ///     </tr>
202    ///     <tr>
203    ///         <td>[2<sup>44</sup>, 2<sup>52</sup>)</td>
204    ///         <td>7</td>
205    ///     </tr>
206    ///     <tr>
207    ///         <td>[2<sup>52</sup>, 2<sup>60</sup>)</td>
208    ///         <td>8</td>
209    ///     </tr>
210    ///     <tr>
211    ///         <td>[2<sup>60</sup>, 2<sup>64</sup>)</td>
212    ///         <td>9</td>
213    ///     </tr>
214    /// </table>
215    pub fn serialize_var_u64(&mut self, val: u64) -> Result<()> {
216        if val < 1 << 4 {
217            self.writer.write_u8(val as u8)
218        } else if val < 1 << 12 {
219            self.writer.write_u16::<BE>((val as u16) | 1 << 12)
220        } else if val < 1 << 20 {
221            self.writer.write_u8(((val >> 16) as u8) | 2 << 4)?;
222            self.writer.write_u16::<BE>(val as u16)
223        } else if val < 1 << 28 {
224            self.writer.write_u32::<BE>((val as u32) | 3 << 28)
225        } else if val < 1 << 36 {
226            self.writer.write_u8(((val >> 32) as u8) | 4 << 4)?;
227            self.writer.write_u32::<BE>(val as u32)
228        } else if val < 1 << 44 {
229            self.writer
230                .write_u16::<BE>(((val >> 32) as u16) | 5 << 12)?;
231            self.writer.write_u32::<BE>(val as u32)
232        } else if val < 1 << 52 {
233            self.writer.write_u8(((val >> 48) as u8) | 6 << 4)?;
234            self.writer.write_u16::<BE>((val >> 32) as u16)?;
235            self.writer.write_u32::<BE>(val as u32)
236        } else if val < 1 << 60 {
237            self.writer.write_u64::<BE>((val as u64) | 7 << 60)
238        } else {
239            self.writer.write_u8(8 << 4)?;
240            self.writer.write_u64::<BE>(val)
241        }
242            .map_err(From::from)
243    }
244
245    /// Encode an `i64` into a variable number of bytes.
246    ///
247    /// The variable-length encoding scheme uses between 1 and 9 bytes depending on the value.
248    /// Smaller magnitude (closer to 0) `i64`s will encode to fewer bytes.
249    ///
250    /// ##### Encoding
251    ///
252    /// The encoding uses the first bit to encode the sign: `0` for negative values and `1` for
253    /// positive values. The following 4 bits store the number of trailing bytes, between 0 and 8.
254    /// Subsequent bits are the absolute value of the input value in big-endian format with leading
255    /// 0 bytes removed. If the original value was negative, than 1 is subtracted from the absolute
256    /// value before encoding. Finally, if the value is negative, all bits except the sign bit are
257    /// flipped (1s become 0s and 0s become 1s).
258    ///
259    /// ##### Encoded Size
260    ///
261    /// <table>
262    ///     <tr>
263    ///         <th>negative range</th>
264    ///         <th>positive range</th>
265    ///         <th>size (bytes)</th>
266    ///     </tr>
267    ///     <tr>
268    ///         <td>[-2<sup>3</sup>, 0)</td>
269    ///         <td>[0, 2<sup>3</sup>)</td>
270    ///         <td>1</td>
271    ///     </tr>
272    ///     <tr>
273    ///         <td>[-2<sup>11</sup>, -2<sup>3</sup>)</td>
274    ///         <td>[2<sup>3</sup>, 2<sup>11</sup>)</td>
275    ///         <td>2</td>
276    ///     </tr>
277    ///     <tr>
278    ///         <td>[-2<sup>19</sup>, -2<sup>11</sup>)</td>
279    ///         <td>[2<sup>11</sup>, 2<sup>19</sup>)</td>
280    ///         <td>3</td>
281    ///     </tr>
282    ///     <tr>
283    ///         <td>[-2<sup>27</sup>, -2<sup>19</sup>)</td>
284    ///         <td>[2<sup>19</sup>, 2<sup>27</sup>)</td>
285    ///         <td>4</td>
286    ///     </tr>
287    ///     <tr>
288    ///         <td>[-2<sup>35</sup>, -2<sup>27</sup>)</td>
289    ///         <td>[2<sup>27</sup>, 2<sup>35</sup>)</td>
290    ///         <td>5</td>
291    ///     </tr>
292    ///     <tr>
293    ///         <td>[-2<sup>43</sup>, -2<sup>35</sup>)</td>
294    ///         <td>[2<sup>35</sup>, 2<sup>43</sup>)</td>
295    ///         <td>6</td>
296    ///     </tr>
297    ///     <tr>
298    ///         <td>[-2<sup>51</sup>, -2<sup>43</sup>)</td>
299    ///         <td>[2<sup>43</sup>, 2<sup>51</sup>)</td>
300    ///         <td>7</td>
301    ///     </tr>
302    ///     <tr>
303    ///         <td>[-2<sup>59</sup>, -2<sup>51</sup>)</td>
304    ///         <td>[2<sup>51</sup>, 2<sup>59</sup>)</td>
305    ///         <td>8</td>
306    ///     </tr>
307    ///     <tr>
308    ///         <td>[-2<sup>63</sup>, -2<sup>59</sup>)</td>
309    ///         <td>[2<sup>59</sup>, 2<sup>63</sup>)</td>
310    ///         <td>9</td>
311    ///     </tr>
312    /// </table>
313    pub fn serialize_var_i64(&mut self, v: i64) -> Result<()> {
314        // The mask is 0 for positive input and u64::MAX for negative input
315        let mask = (v >> 63) as u64;
316        let val = v.abs() as u64 - (1 & mask);
317        if val < 1 << 3 {
318            let masked = (val | (0x10 << 3)) ^ mask;
319            self.writer.write_u8(masked as u8)
320        } else if val < 1 << 11 {
321            let masked = (val | (0x11 << 11)) ^ mask;
322            self.writer.write_u16::<BE>(masked as u16)
323        } else if val < 1 << 19 {
324            let masked = (val | (0x12 << 19)) ^ mask;
325            self.writer.write_u8((masked >> 16) as u8)?;
326            self.writer.write_u16::<BE>(masked as u16)
327        } else if val < 1 << 27 {
328            let masked = (val | (0x13 << 27)) ^ mask;
329            self.writer.write_u32::<BE>(masked as u32)
330        } else if val < 1 << 35 {
331            let masked = (val | (0x14 << 35)) ^ mask;
332            self.writer.write_u8((masked >> 32) as u8)?;
333            self.writer.write_u32::<BE>(masked as u32)
334        } else if val < 1 << 43 {
335            let masked = (val | (0x15 << 43)) ^ mask;
336            self.writer.write_u16::<BE>((masked >> 32) as u16)?;
337            self.writer.write_u32::<BE>(masked as u32)
338        } else if val < 1 << 51 {
339            let masked = (val | (0x16 << 51)) ^ mask;
340            self.writer.write_u8((masked >> 48) as u8)?;
341            self.writer.write_u16::<BE>((masked >> 32) as u16)?;
342            self.writer.write_u32::<BE>(masked as u32)
343        } else if val < 1 << 59 {
344            let masked = (val | (0x17 << 59)) ^ mask;
345            self.writer.write_u64::<BE>(masked as u64)
346        } else {
347            self.writer.write_u8((0x18 << 3) ^ mask as u8)?;
348            self.writer.write_u64::<BE>(val ^ mask)
349        }
350            .map_err(From::from)
351    }
352}
353
354impl<'a, W> serde::Serializer for &'a mut Serializer<W>
355    where
356        W: Write,
357{
358    type Ok = ();
359    type Error = Error;
360    type SerializeSeq = Self;
361    type SerializeTuple = Self;
362    type SerializeTupleStruct = Self;
363    type SerializeTupleVariant = Self;
364    type SerializeMap = Self;
365    type SerializeStruct = Self;
366    type SerializeStructVariant = Self;
367
368    fn serialize_bool(self, v: bool) -> Result<()> {
369        let b = if v { 1 } else { 0 };
370        self.writer.write_u8(b)?;
371        Ok(())
372    }
373
374    fn serialize_i8(self, v: i8) -> Result<()> {
375        self.writer.write_i8(v ^ i8::MIN)?;
376        Ok(())
377    }
378
379    fn serialize_i16(self, v: i16) -> Result<()> {
380        self.writer.write_i16::<BE>(v ^ i16::MIN)?;
381        Ok(())
382    }
383
384    fn serialize_i32(self, v: i32) -> Result<()> {
385        self.writer.write_i32::<BE>(v ^ i32::MIN)?;
386        Ok(())
387    }
388
389    fn serialize_i64(self, v: i64) -> Result<()> {
390        self.writer.write_i64::<BE>(v ^ i64::MIN)?;
391        Ok(())
392    }
393
394    fn serialize_u8(self, v: u8) -> Result<()> {
395        self.writer.write_u8(v)?;
396        Ok(())
397    }
398
399    fn serialize_u16(self, v: u16) -> Result<()> {
400        self.writer.write_u16::<BE>(v)?;
401        Ok(())
402    }
403
404    fn serialize_u32(self, v: u32) -> Result<()> {
405        self.writer.write_u32::<BE>(v)?;
406        Ok(())
407    }
408
409    fn serialize_u64(self, v: u64) -> Result<()> {
410        self.writer.write_u64::<BE>(v)?;
411        Ok(())
412    }
413
414    /// Encode an `f32` into sortable bytes.
415    ///
416    /// `NaN`s will sort greater than positive infinity. -0.0 will sort directly before +0.0.
417    ///
418    /// See [Hacker's Delight 2nd Edition](http://www.hackersdelight.org/) Section 17-3.
419    fn serialize_f32(self, v: f32) -> Result<()> {
420        let val = unsafe { transmute::<f32, i32>(v) };
421        let t = (val >> 31) | i32::MIN;
422        self.writer.write_i32::<BE>(val ^ t)?;
423        Ok(())
424    }
425
426    /// Encode an `f64` into sortable bytes.
427    ///
428    /// `NaN`s will sort greater than positive infinity. -0.0 will sort directly before +0.0.
429    ///
430    /// See [Hacker's Delight 2nd Edition](http://www.hackersdelight.org/) Section 17-3.
431    fn serialize_f64(self, v: f64) -> Result<()> {
432        let val = unsafe { transmute::<f64, i64>(v) };
433        let t = (val >> 63) | i64::MIN;
434        self.writer.write_i64::<BE>(val ^ t)?;
435        Ok(())
436    }
437
438    fn serialize_char(self, v: char) -> Result<()> {
439        let mut buf = [0u8; 4];
440        let n = v.encode_utf8(&mut buf).len();
441        self.writer.write_all(&buf[..n])?;
442        Ok(())
443    }
444
445    fn serialize_str(self, v: &str) -> Result<()> {
446        self.writer.write_all(v.as_bytes())?;
447        self.writer.write_u8(0xFFu8)?;
448        Ok(())
449    }
450
451    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
452        self.writer.write_all(v)?;
453        Ok(())
454    }
455
456    fn serialize_none(self) -> Result<()> {
457        self.writer.write_u8(0)?;
458        Ok(())
459    }
460
461    fn serialize_some<T>(self, v: &T) -> Result<()>
462        where
463            T: ?Sized + Serialize,
464    {
465        self.writer.write_u8(1)?;
466        v.serialize(self)
467    }
468
469    fn serialize_unit(self) -> Result<()> {
470        self.writer.write_all(&[])?;
471        Ok(())
472    }
473
474    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
475        self.serialize_unit()
476    }
477
478    fn serialize_unit_variant(
479        self,
480        _name: &'static str,
481        variant_index: u32,
482        _variant: &'static str,
483    ) -> Result<()> {
484        self.serialize_u32(variant_index)
485    }
486
487    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
488        where
489            T: ?Sized + Serialize,
490    {
491        value.serialize(self)
492    }
493
494    fn serialize_newtype_variant<T>(
495        self,
496        _name: &'static str,
497        variant_index: u32,
498        _variant: &'static str,
499        value: &T,
500    ) -> Result<()>
501        where
502            T: ?Sized + Serialize,
503    {
504        self.writer.write_u32::<BE>(variant_index)?;
505        value.serialize(self)
506    }
507
508    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
509        Ok(self)
510    }
511
512    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
513        Ok(self)
514    }
515
516    fn serialize_tuple_struct(
517        self,
518        _name: &'static str,
519        _len: usize,
520    ) -> Result<Self::SerializeTupleStruct> {
521        Ok(self)
522    }
523
524    fn serialize_tuple_variant(
525        self,
526        _name: &'static str,
527        variant_index: u32,
528        _variant: &'static str,
529        _len: usize,
530    ) -> Result<Self::SerializeTupleVariant> {
531        self.writer.write_u32::<BE>(variant_index)?;
532        Ok(self)
533    }
534
535    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeStruct> {
536        Ok(self)
537    }
538
539    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
540        Ok(self)
541    }
542
543    fn serialize_struct_variant(
544        self,
545        _name: &'static str,
546        variant_index: u32,
547        _variant: &'static str,
548        _len: usize,
549    ) -> Result<Self::SerializeStructVariant> {
550        self.writer.write_u32::<BE>(variant_index)?;
551        Ok(self)
552    }
553}
554
555// Compound Implementations.
556
557impl<'a, W> serde::ser::SerializeSeq for &'a mut Serializer<W>
558    where
559        W: Write,
560{
561    type Ok = ();
562    type Error = Error;
563
564    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
565        where
566            T: ?Sized + Serialize,
567    {
568        value.serialize(&mut **self)
569    }
570
571    fn end(self) -> Result<()> {
572        Ok(())
573    }
574}
575
576impl<'a, W> serde::ser::SerializeTuple for &'a mut Serializer<W>
577    where
578        W: Write,
579{
580    type Ok = ();
581    type Error = Error;
582
583    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
584        where
585            T: ?Sized + Serialize,
586    {
587        value.serialize(&mut **self)
588    }
589
590    fn end(self) -> Result<()> {
591        Ok(())
592    }
593}
594
595impl<'a, W> serde::ser::SerializeTupleStruct for &'a mut Serializer<W>
596    where
597        W: Write,
598{
599    type Ok = ();
600    type Error = Error;
601
602    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
603        where
604            T: ?Sized + Serialize,
605    {
606        value.serialize(&mut **self)
607    }
608
609    fn end(self) -> Result<()> {
610        Ok(())
611    }
612}
613
614impl<'a, W> serde::ser::SerializeTupleVariant for &'a mut Serializer<W>
615    where
616        W: Write,
617{
618    type Ok = ();
619    type Error = Error;
620
621    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
622        where
623            T: ?Sized + Serialize,
624    {
625        value.serialize(&mut **self)
626    }
627
628    fn end(self) -> Result<()> {
629        Ok(())
630    }
631}
632
633impl<'a, W> serde::ser::SerializeMap for &'a mut Serializer<W>
634    where
635        W: Write,
636{
637    type Ok = ();
638    type Error = Error;
639
640    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
641        where
642            T: ?Sized + Serialize,
643    {
644        key.serialize(&mut **self)
645    }
646
647    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
648        where
649            T: ?Sized + Serialize,
650    {
651        value.serialize(&mut **self)
652    }
653
654    fn end(self) -> Result<()> {
655        Ok(())
656    }
657}
658
659impl<'a, W> serde::ser::SerializeStruct for &'a mut Serializer<W>
660    where
661        W: Write,
662{
663    type Ok = ();
664    type Error = Error;
665
666    fn serialize_field<T>(&mut self, _key: &'static str, value: &T) -> Result<()>
667        where
668            T: ?Sized + Serialize,
669    {
670        value.serialize(&mut **self)
671    }
672
673    fn end(self) -> Result<()> {
674        Ok(())
675    }
676}
677
678impl<'a, W> serde::ser::SerializeStructVariant for &'a mut Serializer<W>
679    where
680        W: Write,
681{
682    type Ok = ();
683    type Error = Error;
684
685    fn serialize_field<T>(&mut self, _key: &'static str, value: &T) -> Result<()>
686        where
687            T: ?Sized + Serialize,
688    {
689        value.serialize(&mut **self)
690    }
691
692    fn end(self) -> Result<()> {
693        Ok(())
694    }
695}
696
697// Error implementation.
698
699impl From<io::Error> for Error {
700    fn from(error: io::Error) -> Error {
701        Error::Io(error)
702    }
703}
704
705#[allow(deprecated)]
706impl fmt::Display for Error {
707    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
708        write!(f, "{}", match *self {
709            Error::Message(ref msg) => msg,
710            Error::Io(ref err) => err.description(),
711        })
712    }
713}
714
715impl StdError for Error {
716    fn source(&self) -> Option<&(dyn StdError + 'static)> {
717        match *self {
718            Error::Message(ref _msg) => None,
719            Error::Io(ref err) => err.source(),
720        }
721    }
722}
723
724impl serde::ser::Error for Error {
725    fn custom<T: fmt::Display>(msg: T) -> Self {
726        Error::Message(msg.to_string())
727    }
728}