cbor/
encoder.rs

1// This Source Code Form is subject to the terms of
2// the Mozilla Public License, v. 2.0. If a copy of
3// the MPL was not distributed with this file, You
4// can obtain one at http://mozilla.org/MPL/2.0/.
5
6//! CBOR ([RFC 7049](http://tools.ietf.org/html/rfc7049))
7//! encoder implementation.
8//!
9//! This module provides an `Encoder` to directly encode Rust types into
10//! CBOR, and a `GenericEncoder` which encodes a `Value` into CBOR.
11//!
12//! # Example 1: Direct encoding
13//!
14//! ```
15//! extern crate cbor;
16//! extern crate rustc_serialize;
17//!
18//! use cbor::Encoder;
19//! use rustc_serialize::hex::FromHex;
20//! use std::io::Cursor;
21//!
22//! fn main() {
23//!     let mut e = Encoder::new(Cursor::new(Vec::new()));
24//!     e.u16(1000).unwrap();
25//!     assert_eq!("1903e8".from_hex().unwrap(), e.into_writer().into_inner())
26//! }
27//! ```
28//!
29//! # Example 2: Direct encoding (indefinite string)
30//!
31//! ```
32//! extern crate cbor;
33//! extern crate rustc_serialize;
34//!
35//! use cbor::Encoder;
36//! use rustc_serialize::hex::FromHex;
37//! use std::io::Cursor;
38//!
39//! fn main() {
40//!     let mut e = Encoder::new(Cursor::new(Vec::new()));
41//!     e.text_iter(vec!["strea", "ming"].into_iter()).unwrap();
42//!     let output = "7f657374726561646d696e67ff".from_hex().unwrap();
43//!     assert_eq!(output, e.into_writer().into_inner())
44//! }
45//! ```
46//!
47//! # Example 3: Direct encoding (nested array)
48//!
49//! ```
50//! extern crate cbor;
51//! extern crate rustc_serialize;
52//!
53//! use cbor::Encoder;
54//! use rustc_serialize::hex::FromHex;
55//! use std::io::Cursor;
56//!
57//! fn main() {
58//!     let mut e = Encoder::new(Cursor::new(Vec::new()));
59//!     e.array(3)
60//!      .and(e.u8(1))
61//!      .and(e.array(2)).and(e.u8(2)).and(e.u8(3))
62//!      .and(e.array(2)).and(e.u8(4)).and(e.u8(5))
63//!      .unwrap();
64//!     let output = "8301820203820405".from_hex().unwrap();
65//!     assert_eq!(output, e.into_writer().into_inner())
66//! }
67//! ```
68
69
70use byteorder::{BigEndian, WriteBytesExt};
71use std::io;
72use std::error::Error;
73use std::fmt;
74use crate::types::{Tag, Type};
75use crate::value::{Bytes, Int, Key, Simple, Text, Value};
76
77// Encoder Error Type ///////////////////////////////////////////////////////
78
79pub type EncodeResult = Result<(), EncodeError>;
80
81#[derive(Debug)]
82pub enum EncodeError {
83    /// Some I/O error
84    IoError(io::Error),
85    /// The end of file has been encountered unexpectedly
86    UnexpectedEOF,
87    /// The provided `Simple` value is neither unassigned nor reserved
88    InvalidSimpleValue(Simple),
89    /// Certain values (e.g. `Value::Break`) are not legal to encode as
90    /// independent units. Attempting to do so will trigger this error.
91    InvalidValue(Value),
92    /// Some other error.
93    Other(Box<dyn Error + Send + Sync>)
94}
95
96impl fmt::Display for EncodeError {
97    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
98        match *self {
99            EncodeError::IoError(ref e)            => write!(f, "EncodeError: I/O error: {}", *e),
100            EncodeError::UnexpectedEOF             => write!(f, "EncodeError: unexpected end-of-file"),
101            EncodeError::InvalidValue(ref v)       => write!(f, "EncodeError: invalid value {:?}", v),
102            EncodeError::InvalidSimpleValue(ref s) => write!(f, "EncodeError: invalid simple value {:?}", s),
103            EncodeError::Other(ref e)              => write!(f, "EncodeError: other error: {}", e)
104        }
105    }
106}
107
108impl Error for EncodeError {
109    fn description(&self) -> &str {
110        match *self {
111            EncodeError::IoError(_)            => "i/o error",
112            EncodeError::UnexpectedEOF         => "unexpected eof",
113            EncodeError::InvalidValue(_)       => "invalid value",
114            EncodeError::InvalidSimpleValue(_) => "invalid simple value",
115            EncodeError::Other(_)              => "other error"
116        }
117    }
118
119    fn cause(&self) -> Option<&dyn Error> {
120        match *self {
121            EncodeError::IoError(ref e) => Some(e),
122            EncodeError::Other(ref e)   => Some(&**e),
123            _                           => None
124        }
125    }
126}
127
128impl From<io::Error> for EncodeError {
129    fn from(e: io::Error) -> EncodeError {
130        EncodeError::IoError(e)
131    }
132}
133
134// Encoder //////////////////////////////////////////////////////////////////
135
136/// The actual encoder type definition
137pub struct Encoder<W> {
138    writer: W
139}
140
141impl<W: WriteBytesExt> Encoder<W> {
142    pub fn new(w: W) -> Encoder<W> {
143        Encoder { writer: w }
144    }
145
146    pub fn into_writer(self) -> W {
147        self.writer
148    }
149
150    pub fn writer(&mut self) -> &mut W {
151        &mut self.writer
152    }
153
154    pub fn u8(&mut self, x: u8) -> EncodeResult {
155        let ref mut w = self.writer;
156        match x {
157            0..=23 => w.write_u8(x).map_err(From::from),
158            _      => w.write_u8(24).and(w.write_u8(x)).map_err(From::from)
159        }
160    }
161
162    pub fn u16(&mut self, x: u16) -> EncodeResult {
163        let ref mut w = self.writer;
164        match x {
165            0..=23    => w.write_u8(x as u8).map_err(From::from),
166            24..=0xFF => w.write_u8(24).and(w.write_u8(x as u8)).map_err(From::from),
167            _         => w.write_u8(25).and(w.write_u16::<BigEndian>(x)).map_err(From::from)
168        }
169    }
170
171    pub fn u32(&mut self, x: u32) -> EncodeResult {
172        let ref mut w = self.writer;
173        match x {
174            0..=23         => w.write_u8(x as u8).map_err(From::from),
175            24..=0xFF      => w.write_u8(24).and(w.write_u8(x as u8)).map_err(From::from),
176            0x100..=0xFFFF => w.write_u8(25).and(w.write_u16::<BigEndian>(x as u16)).map_err(From::from),
177            _              => w.write_u8(26).and(w.write_u32::<BigEndian>(x)).map_err(From::from)
178        }
179    }
180
181    pub fn u64(&mut self, x: u64) -> EncodeResult {
182        let ref mut w = self.writer;
183        match x {
184            0..=23                => w.write_u8(x as u8).map_err(From::from),
185            24..=0xFF             => w.write_u8(24).and(w.write_u8(x as u8)).map_err(From::from),
186            0x100..=0xFFFF        => w.write_u8(25).and(w.write_u16::<BigEndian>(x as u16)).map_err(From::from),
187            0x100000..=0xFFFFFFFF => w.write_u8(26).and(w.write_u32::<BigEndian>(x as u32)).map_err(From::from),
188            _                     => w.write_u8(27).and(w.write_u64::<BigEndian>(x)).map_err(From::from)
189        }
190    }
191
192    pub fn i8(&mut self, x: i8) -> EncodeResult {
193        if x >= 0 {
194            self.u8(x as u8)
195        } else {
196            let ref mut w = self.writer;
197            match (-1 - x) as u8 {
198                n @ 0..=23 => w.write_u8(0b001_00000 | n).map_err(From::from),
199                n          => w.write_u8(0b001_00000 | 24).and(w.write_u8(n)).map_err(From::from)
200            }
201        }
202    }
203
204    pub fn i16(&mut self, x: i16) -> EncodeResult {
205        if x >= 0 {
206            self.u16(x as u16)
207        } else {
208            let ref mut w = self.writer;
209            match (-1 - x) as u16 {
210                n @ 0..=23    => w.write_u8(0b001_00000 | n as u8).map_err(From::from),
211                n @ 24..=0xFF => w.write_u8(0b001_00000 | 24).and(w.write_u8(n as u8)).map_err(From::from),
212                n             => w.write_u8(0b001_00000 | 25).and(w.write_u16::<BigEndian>(n)).map_err(From::from)
213            }
214        }
215    }
216
217    pub fn i32(&mut self, x: i32) -> EncodeResult {
218        if x >= 0 {
219            self.u32(x as u32)
220        } else {
221            let ref mut w = self.writer;
222            match (-1 - x) as u32 {
223                n @ 0..=23         => w.write_u8(0b001_00000 | n as u8).map_err(From::from),
224                n @ 24..=0xFF      => w.write_u8(0b001_00000 | 24).and(w.write_u8(n as u8)).map_err(From::from),
225                n @ 0x100..=0xFFFF => w.write_u8(0b001_00000 | 25).and(w.write_u16::<BigEndian>(n as u16)).map_err(From::from),
226                n                  => w.write_u8(0b001_00000 | 26).and(w.write_u32::<BigEndian>(n)).map_err(From::from)
227            }
228        }
229    }
230
231    pub fn i64(&mut self, x: i64) -> EncodeResult {
232        if x >= 0 {
233            self.u64(x as u64)
234        } else {
235            let ref mut w = self.writer;
236            match (-1 - x) as u64 {
237                n @ 0..=23                => w.write_u8(0b001_00000 | n as u8).map_err(From::from),
238                n @ 24..=0xFF             => w.write_u8(0b001_00000 | 24).and(w.write_u8(n as u8)).map_err(From::from),
239                n @ 0x100..=0xFFFF        => w.write_u8(0b001_00000 | 25).and(w.write_u16::<BigEndian>(n as u16)).map_err(From::from),
240                n @ 0x100000..=0xFFFFFFFF => w.write_u8(0b001_00000 | 26).and(w.write_u32::<BigEndian>(n as u32)).map_err(From::from),
241                n                         => w.write_u8(0b001_00000 | 27).and(w.write_u64::<BigEndian>(n)).map_err(From::from)
242            }
243        }
244    }
245
246    pub fn int(&mut self, x: Int) -> EncodeResult {
247        match x {
248            Int::Pos(v) => self.u64(v),
249            Int::Neg(v) => {
250                let ref mut w = self.writer;
251                match v {
252                    n @ 0..=23                => w.write_u8(0b001_00000 | n as u8).map_err(From::from),
253                    n @ 24..=0xFF             => w.write_u8(0b001_00000 | 24).and(w.write_u8(n as u8)).map_err(From::from),
254                    n @ 0x100..=0xFFFF        => w.write_u8(0b001_00000 | 25).and(w.write_u16::<BigEndian>(n as u16)).map_err(From::from),
255                    n @ 0x100000..=0xFFFFFFFF => w.write_u8(0b001_00000 | 26).and(w.write_u32::<BigEndian>(n as u32)).map_err(From::from),
256                    n                         => w.write_u8(0b001_00000 | 27).and(w.write_u64::<BigEndian>(n)).map_err(From::from)
257                }
258            }
259        }
260    }
261
262    pub fn f32(&mut self, x: f32) -> EncodeResult {
263        self.writer.write_u8(0b111_00000 | 26)
264            .and(self.writer.write_f32::<BigEndian>(x))
265            .map_err(From::from)
266    }
267
268    pub fn f64(&mut self, x: f64) -> EncodeResult {
269        self.writer.write_u8(0b111_00000 | 27)
270            .and(self.writer.write_f64::<BigEndian>(x))
271            .map_err(From::from)
272    }
273
274    pub fn bool(&mut self, x: bool) -> EncodeResult {
275        self.writer.write_u8(0b111_00000 | if x {21} else {20}).map_err(From::from)
276    }
277
278    pub fn simple(&mut self, x: Simple) -> EncodeResult {
279        let ref mut w = self.writer;
280        match x {
281            Simple::Unassigned(n) => match n {
282                0..=19 | 28..=30 => w.write_u8(0b111_00000 | n).map_err(From::from),
283                32..=255         => w.write_u8(0b111_00000 | 24).and(w.write_u8(n)).map_err(From::from),
284                _                => Err(EncodeError::InvalidSimpleValue(x))
285            },
286            Simple::Reserved(n) => match n {
287                0..=31 => w.write_u8(0b111_00000 | 24).and(w.write_u8(n)).map_err(From::from),
288                _      => Err(EncodeError::InvalidSimpleValue(x))
289            }
290        }
291    }
292
293    pub fn bytes(&mut self, x: &[u8]) -> EncodeResult {
294        self.type_len(Type::Bytes, x.len() as u64)
295            .and(self.writer.write_all(x).map_err(From::from))
296    }
297
298    /// Indefinite byte string encoding. (RFC 7049 section 2.2.2)
299    pub fn bytes_iter<'r, I: Iterator<Item=&'r [u8]>>(&mut self, iter: I) -> EncodeResult {
300        self.writer.write_u8(0b010_11111)?;
301        for x in iter {
302            self.bytes(x)?
303        }
304        self.writer.write_u8(0b111_11111).map_err(From::from)
305    }
306
307    pub fn text(&mut self, x: &str) -> EncodeResult {
308        self.type_len(Type::Text, x.len() as u64)
309            .and(self.writer.write_all(x.as_bytes()).map_err(From::from))
310    }
311
312    /// Indefinite string encoding. (RFC 7049 section 2.2.2)
313    pub fn text_iter<'r, I: Iterator<Item=&'r str>>(&mut self, iter: I) -> EncodeResult {
314        self.writer.write_u8(0b011_11111)?;
315        for x in iter {
316            self.text(x)?
317        }
318        self.writer.write_u8(0b111_11111).map_err(From::from)
319    }
320
321    pub fn null(&mut self) -> EncodeResult {
322        self.writer.write_u8(0b111_00000 | 22).map_err(From::from)
323    }
324
325    pub fn undefined(&mut self) -> EncodeResult {
326        self.writer.write_u8(0b111_00000 | 23).map_err(From::from)
327    }
328
329    pub fn tag(&mut self, x: Tag) -> EncodeResult {
330        self.type_len(Type::Tagged, x.to())
331    }
332
333    pub fn array(&mut self, len: usize) -> EncodeResult {
334        self.type_len(Type::Array, len as u64)
335    }
336
337    /// Indefinite array encoding. (RFC 7049 section 2.2.1)
338    pub fn array_begin(&mut self) -> EncodeResult {
339        self.writer.write_u8(0b100_11111).map_err(From::from)
340    }
341
342    /// End of indefinite array encoding. (RFC 7049 section 2.2.1)
343    pub fn array_end(&mut self) -> EncodeResult {
344        self.writer.write_u8(0b111_11111).map_err(From::from)
345    }
346
347    pub fn object(&mut self, len: usize) -> EncodeResult {
348        self.type_len(Type::Object, len as u64)
349    }
350
351    /// Indefinite object encoding. (RFC 7049 section 2.2.1)
352    pub fn object_begin(&mut self) -> EncodeResult {
353        self.writer.write_u8(0b101_11111).map_err(From::from)
354    }
355
356    /// End of indefinite object encoding. (RFC 7049 section 2.2.1)
357    pub fn object_end(&mut self) -> EncodeResult {
358        self.writer.write_u8(0b111_11111).map_err(From::from)
359    }
360
361    fn type_len(&mut self, t: Type, x: u64) -> EncodeResult {
362        let ref mut w = self.writer;
363        match x {
364            0..=23                => w.write_u8(t.major() << 5 | x as u8).map_err(From::from),
365            24..=0xFF             => w.write_u8(t.major() << 5 | 24).and(w.write_u8(x as u8)).map_err(From::from),
366            0x100..=0xFFFF        => w.write_u8(t.major() << 5 | 25).and(w.write_u16::<BigEndian>(x as u16)).map_err(From::from),
367            0x100000..=0xFFFFFFFF => w.write_u8(t.major() << 5 | 26).and(w.write_u32::<BigEndian>(x as u32)).map_err(From::from),
368            _                     => w.write_u8(t.major() << 5 | 27).and(w.write_u64::<BigEndian>(x)).map_err(From::from)
369        }
370    }
371}
372
373// Generic Encoder //////////////////////////////////////////////////////////
374
375/// A generic encoder encodes a `Value`.
376pub struct GenericEncoder<W> {
377    encoder: Encoder<W>
378}
379
380impl<W: WriteBytesExt> GenericEncoder<W> {
381    pub fn new(w: W) -> GenericEncoder<W> {
382        GenericEncoder { encoder: Encoder::new(w) }
383    }
384
385    pub fn from_encoder(e: Encoder<W>) -> GenericEncoder<W> {
386        GenericEncoder { encoder: e }
387    }
388
389    pub fn into_inner(self) -> Encoder<W> {
390        self.encoder
391    }
392
393    pub fn borrow_mut(&mut self) -> &mut Encoder<W> {
394        &mut self.encoder
395    }
396
397    pub fn value(&mut self, x: &Value) -> EncodeResult {
398        match *x {
399            Value::Array(ref vv) => {
400                self.encoder.array(vv.len())?;
401                for v in vv {
402                    self.value(v)?
403                }
404                Ok(())
405            }
406            Value::Bytes(Bytes::Bytes(ref bb))  => self.encoder.bytes(&bb[..]),
407            Value::Bytes(Bytes::Chunks(ref bb)) => self.encoder.bytes_iter(bb.iter().map(|v| &v[..])),
408            Value::Text(Text::Text(ref txt))    => self.encoder.text(txt),
409            Value::Text(Text::Chunks(ref txt))  => self.encoder.text_iter(txt.iter().map(|v| &v[..])),
410            Value::Map(ref m) => {
411                self.encoder.object(m.len())?;
412                for (k, v) in m {
413                    self.key(k).and(self.value(v))?
414                }
415                Ok(())
416            }
417            Value::Tagged(t, ref val) => {
418                self.encoder.tag(t)?;
419                self.value(&*val)
420            }
421            Value::Undefined => self.encoder.undefined(),
422            Value::Null      => self.encoder.null(),
423            Value::Simple(s) => self.encoder.simple(s),
424            Value::Bool(b)   => self.encoder.bool(b),
425            Value::U8(n)     => self.encoder.u8(n),
426            Value::U16(n)    => self.encoder.u16(n),
427            Value::U32(n)    => self.encoder.u32(n),
428            Value::U64(n)    => self.encoder.u64(n),
429            Value::F32(n)    => self.encoder.f32(n),
430            Value::F64(n)    => self.encoder.f64(n),
431            Value::I8(n)     => self.encoder.i8(n),
432            Value::I16(n)    => self.encoder.i16(n),
433            Value::I32(n)    => self.encoder.i32(n),
434            Value::I64(n)    => self.encoder.i64(n),
435            Value::Int(n)    => self.encoder.int(n),
436            Value::Break     => Err(EncodeError::InvalidValue(Value::Break))
437        }
438    }
439
440    fn key(&mut self, x: &Key) -> EncodeResult {
441        match *x {
442            Key::Bool(b) => self.encoder.bool(b),
443            Key::Int(n)  => self.encoder.int(n),
444            Key::Bytes(Bytes::Bytes(ref bb))  => self.encoder.bytes(&bb[..]),
445            Key::Bytes(Bytes::Chunks(ref bb)) => self.encoder.bytes_iter(bb.iter().map(|v| &v[..])),
446            Key::Text(Text::Text(ref txt))    => self.encoder.text(txt),
447            Key::Text(Text::Chunks(ref txt))  => self.encoder.text_iter(txt.iter().map(|v| &v[..]))
448        }
449    }
450}
451
452// Tests ////////////////////////////////////////////////////////////////////
453
454#[cfg(test)]
455mod tests {
456    use rustc_serialize::hex::FromHex;
457    use std::{f32, f64};
458    use std::io::Cursor;
459    use super::*;
460    use crate::types::Tag;
461    use crate::value::Simple;
462
463    #[test]
464    fn unsigned() {
465        encoded("00", |mut e| e.u8(0));
466        encoded("01", |mut e| e.u8(1));
467        encoded("0a", |mut e| e.u8(10));
468        encoded("17", |mut e| e.u8(23));
469        encoded("1818", |mut e| e.u8(24));
470        encoded("1819", |mut e| e.u8(25));
471        encoded("1864", |mut e| e.u8(100));
472        encoded("1903e8", |mut e| e.u16(1000));
473        encoded("1a000f4240", |mut e| e.u32(1000000));
474        encoded("1b000000e8d4a51000", |mut e| e.u64(1000000000000));
475        encoded("1bffffffffffffffff", |mut e| e.u64(18446744073709551615))
476    }
477
478    #[test]
479    fn signed() {
480        encoded("20", |mut e| e.i8(-1));
481        encoded("29", |mut e| e.i8(-10));
482        encoded("3863", |mut e| e.i8(-100));
483        encoded("3901f3", |mut e| e.i16(-500));
484        encoded("3903e7", |mut e| e.i16(-1000));
485        encoded("3a00053d89", |mut e| e.i32(-343434));
486        encoded("3b000000058879da85", |mut e| e.i64(-23764523654))
487    }
488
489    #[test]
490    fn bool() {
491        encoded("f4", |mut e| e.bool(false));
492        encoded("f5", |mut e| e.bool(true))
493    }
494
495    #[test]
496    fn simple() {
497        encoded("f0", |mut e| e.simple(Simple::Unassigned(16)));
498        encoded("f818", |mut e| e.simple(Simple::Reserved(24)));
499        encoded("f8ff", |mut e| e.simple(Simple::Unassigned(255)))
500    }
501
502    #[test]
503    fn float() {
504        encoded("fa47c35000", |mut e| e.f32(100000.0));
505        encoded("fa7f7fffff", |mut e| e.f32(3.4028234663852886e+38));
506        encoded("fbc010666666666666", |mut e| e.f64(-4.1));
507
508        encoded("fa7f800000", |mut e| e.f32(f32::INFINITY));
509        encoded("faff800000", |mut e| e.f32(-f32::INFINITY));
510        encoded("fa7fc00000", |mut e| e.f32(f32::NAN));
511
512        encoded("fb7ff0000000000000", |mut e| e.f64(f64::INFINITY));
513        encoded("fbfff0000000000000", |mut e| e.f64(-f64::INFINITY));
514        encoded("fb7ff8000000000000", |mut e| e.f64(f64::NAN));
515    }
516
517    #[test]
518    fn bytes() {
519        encoded("4401020304", |mut e| e.bytes(&vec![1,2,3,4][..]));
520    }
521
522    #[test]
523    fn text() {
524        encoded("62c3bc", |mut e| e.text("\u{00fc}"));
525        encoded("781f64667364667364660d0a7364660d0a68656c6c6f0d0a736466736673646673", |mut e| {
526            e.text("dfsdfsdf\r\nsdf\r\nhello\r\nsdfsfsdfs")
527        });
528    }
529
530    #[test]
531    fn indefinite_text() {
532        encoded("7f657374726561646d696e67ff", |mut e| {
533            e.text_iter(vec!["strea", "ming"].into_iter())
534        })
535    }
536
537    #[test]
538    fn indefinite_bytes() {
539        encoded("5f457374726561446d696e67ff", |mut e| {
540            e.bytes_iter(vec!["strea".as_bytes(), "ming".as_bytes()].into_iter())
541        })
542    }
543
544    #[test]
545    fn option() {
546        encoded("f6", |mut e| e.null())
547    }
548
549    #[test]
550    fn tagged() {
551        encoded("c11a514b67b0", |mut e| {
552            e.tag(Tag::Timestamp)?;
553            e.u32(1363896240)
554        })
555    }
556
557    #[test]
558    fn array() {
559        encoded("83010203", |mut e| {
560            e.array(3)?;
561            e.u32(1)?;
562            e.u32(2)?;
563            e.u32(3)
564        });
565        encoded("8301820203820405", |mut e| {
566            e.array(3)
567             .and(e.u8(1))
568             .and(e.array(2))
569                .and(e.u8(2))
570                .and(e.u8(3))
571             .and(e.array(2))
572                .and(e.u8(4))
573                .and(e.u8(5))
574        })
575    }
576
577    #[test]
578    fn indefinite_array() {
579        encoded("9f018202039f0405ffff", |mut e| {
580            e.array_begin()
581             .and(e.u8(1))
582             .and(e.array(2))
583                .and(e.u8(2))
584                .and(e.u8(3))
585             .and(e.array_begin())
586                .and(e.u8(4))
587                .and(e.u8(5))
588                .and(e.array_end())
589            .and(e.array_end())
590        });
591        encoded("9f01820203820405ff", |mut e| {
592            e.array_begin()
593             .and(e.u8(1))
594             .and(e.array(2))
595                .and(e.u8(2))
596                .and(e.u8(3))
597             .and(e.array(2))
598                .and(e.u8(4))
599                .and(e.u8(5))
600            .and(e.array_end())
601        });
602        encoded("83018202039f0405ff", |mut e| {
603            e.array(3)
604             .and(e.u8(1))
605             .and(e.array(2))
606                .and(e.u8(2))
607                .and(e.u8(3))
608             .and(e.array_begin())
609                .and(e.u8(4))
610                .and(e.u8(5))
611                .and(e.array_end())
612        });
613        encoded("83019f0203ff820405", |mut e| {
614            e.array(3)
615             .and(e.u8(1))
616             .and(e.array_begin())
617                .and(e.u8(2))
618                .and(e.u8(3))
619                .and(e.array_end())
620             .and(e.array(2))
621                .and(e.u8(4))
622                .and(e.u8(5))
623        })
624    }
625
626    #[test]
627    fn object() {
628        encoded("a26161016162820203", |mut e| {
629            e.object(2)?;
630            e.text("a").and(e.u8(1))?;
631            e.text("b").and(e.array(2)).and(e.u8(2)).and(e.u8(3))
632        })
633    }
634
635    #[test]
636    fn indefinite_object() {
637        encoded("bf6346756ef563416d7421ff", |mut e| {
638            e.object_begin()
639             .and(e.text("Fun"))
640             .and(e.bool(true))
641             .and(e.text("Amt"))
642             .and(e.i8(-2))
643             .and(e.object_end())
644        })
645    }
646
647    fn encoded<F>(expected: &str, mut f: F)
648    where F: FnMut(Encoder<Cursor<&mut [u8]>>) -> EncodeResult
649    {
650        let mut buffer = vec![0u8; 128];
651        assert!(f(Encoder::new(Cursor::new(&mut buffer[..]))).is_ok());
652        assert_eq!(&expected.from_hex().unwrap()[..], &buffer[0 .. expected.len() / 2])
653    }
654}