]> git.lizzy.rs Git - rust.git/blob - src/librbml/lib.rs
rollup merge of #20482: kmcallister/macro-reform
[rust.git] / src / librbml / lib.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Really Bad Markup Language (rbml) is a temporary measure until we migrate
12 //! the rust object metadata to a better serialization format. It is not
13 //! intended to be used by users.
14 //!
15 //! It is loosely based on the Extensible Binary Markup Language (ebml):
16 //!     http://www.matroska.org/technical/specs/rfc/index.html
17
18 #![crate_name = "rbml"]
19 #![experimental]
20 #![crate_type = "rlib"]
21 #![crate_type = "dylib"]
22 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
23        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
24        html_root_url = "http://doc.rust-lang.org/nightly/",
25        html_playground_url = "http://play.rust-lang.org/")]
26 #![allow(unknown_features)]
27 #![feature(macro_rules, phase, slicing_syntax, globs)]
28 #![feature(unboxed_closures, associated_types)]
29 #![allow(missing_docs)]
30
31 extern crate serialize;
32
33 #[cfg(stage0)]
34 #[phase(plugin, link)]
35 extern crate log;
36
37 #[cfg(not(stage0))]
38 #[macro_use]
39 extern crate log;
40
41 #[cfg(test)] extern crate test;
42
43 pub use self::EbmlEncoderTag::*;
44 pub use self::Error::*;
45
46 use std::str;
47
48 pub mod io;
49
50 /// Common data structures
51 #[derive(Clone, Copy)]
52 pub struct Doc<'a> {
53     pub data: &'a [u8],
54     pub start: uint,
55     pub end: uint,
56 }
57
58 impl<'doc> Doc<'doc> {
59     pub fn new(data: &'doc [u8]) -> Doc<'doc> {
60         Doc { data: data, start: 0u, end: data.len() }
61     }
62
63     pub fn get<'a>(&'a self, tag: uint) -> Doc<'a> {
64         reader::get_doc(*self, tag)
65     }
66
67     pub fn as_str_slice<'a>(&'a self) -> &'a str {
68         str::from_utf8(self.data[self.start..self.end]).unwrap()
69     }
70
71     pub fn as_str(&self) -> String {
72         self.as_str_slice().to_string()
73     }
74 }
75
76 pub struct TaggedDoc<'a> {
77     tag: uint,
78     pub doc: Doc<'a>,
79 }
80
81 #[derive(Copy, Show)]
82 pub enum EbmlEncoderTag {
83     EsUint,     // 0
84     EsU64,      // 1
85     EsU32,      // 2
86     EsU16,      // 3
87     EsU8,       // 4
88     EsInt,      // 5
89     EsI64,      // 6
90     EsI32,      // 7
91     EsI16,      // 8
92     EsI8,       // 9
93     EsBool,     // 10
94     EsChar,     // 11
95     EsStr,      // 12
96     EsF64,      // 13
97     EsF32,      // 14
98     EsFloat,    // 15
99     EsEnum,     // 16
100     EsEnumVid,  // 17
101     EsEnumBody, // 18
102     EsVec,      // 19
103     EsVecLen,   // 20
104     EsVecElt,   // 21
105     EsMap,      // 22
106     EsMapLen,   // 23
107     EsMapKey,   // 24
108     EsMapVal,   // 25
109
110     EsOpaque,
111
112     EsLabel, // Used only when debugging
113 }
114
115 #[derive(Show)]
116 pub enum Error {
117     IntTooBig(uint),
118     Expected(String),
119     IoError(std::io::IoError),
120     ApplicationError(String)
121 }
122 // --------------------------------------
123
124 pub mod reader {
125     use std::char;
126
127     use std::int;
128     use std::io::extensions::u64_from_be_bytes;
129     use std::mem::transmute;
130     use std::num::Int;
131     use std::option::Option;
132     use std::option::Option::{None, Some};
133
134     use serialize;
135
136     use super::{ ApplicationError, EsVec, EsMap, EsEnum, EsVecLen, EsVecElt,
137         EsMapLen, EsMapKey, EsEnumVid, EsU64, EsU32, EsU16, EsU8, EsInt, EsI64,
138         EsI32, EsI16, EsI8, EsBool, EsF64, EsF32, EsChar, EsStr, EsMapVal,
139         EsEnumBody, EsUint, EsOpaque, EsLabel, EbmlEncoderTag, Doc, TaggedDoc,
140         Error, IntTooBig, Expected };
141
142     pub type DecodeResult<T> = Result<T, Error>;
143     // rbml reading
144
145     macro_rules! try_or {
146         ($e:expr, $r:expr) => (
147             match $e {
148                 Ok(e) => e,
149                 Err(e) => {
150                     debug!("ignored error: {}", e);
151                     return $r
152                 }
153             }
154         )
155     }
156
157     #[derive(Copy)]
158     pub struct Res {
159         pub val: uint,
160         pub next: uint
161     }
162
163     #[inline(never)]
164     fn vuint_at_slow(data: &[u8], start: uint) -> DecodeResult<Res> {
165         let a = data[start];
166         if a & 0x80u8 != 0u8 {
167             return Ok(Res {val: (a & 0x7fu8) as uint, next: start + 1u});
168         }
169         if a & 0x40u8 != 0u8 {
170             return Ok(Res {val: ((a & 0x3fu8) as uint) << 8u |
171                         (data[start + 1u] as uint),
172                     next: start + 2u});
173         }
174         if a & 0x20u8 != 0u8 {
175             return Ok(Res {val: ((a & 0x1fu8) as uint) << 16u |
176                         (data[start + 1u] as uint) << 8u |
177                         (data[start + 2u] as uint),
178                     next: start + 3u});
179         }
180         if a & 0x10u8 != 0u8 {
181             return Ok(Res {val: ((a & 0x0fu8) as uint) << 24u |
182                         (data[start + 1u] as uint) << 16u |
183                         (data[start + 2u] as uint) << 8u |
184                         (data[start + 3u] as uint),
185                     next: start + 4u});
186         }
187         Err(IntTooBig(a as uint))
188     }
189
190     pub fn vuint_at(data: &[u8], start: uint) -> DecodeResult<Res> {
191         if data.len() - start < 4 {
192             return vuint_at_slow(data, start);
193         }
194
195         // Lookup table for parsing EBML Element IDs as per http://ebml.sourceforge.net/specs/
196         // The Element IDs are parsed by reading a big endian u32 positioned at data[start].
197         // Using the four most significant bits of the u32 we lookup in the table below how the
198         // element ID should be derived from it.
199         //
200         // The table stores tuples (shift, mask) where shift is the number the u32 should be right
201         // shifted with and mask is the value the right shifted value should be masked with.
202         // If for example the most significant bit is set this means it's a class A ID and the u32
203         // should be right shifted with 24 and masked with 0x7f. Therefore we store (24, 0x7f) at
204         // index 0x8 - 0xF (four bit numbers where the most significant bit is set).
205         //
206         // By storing the number of shifts and masks in a table instead of checking in order if
207         // the most significant bit is set, the second most significant bit is set etc. we can
208         // replace up to three "and+branch" with a single table lookup which gives us a measured
209         // speedup of around 2x on x86_64.
210         static SHIFT_MASK_TABLE: [(uint, u32); 16] = [
211             (0, 0x0), (0, 0x0fffffff),
212             (8, 0x1fffff), (8, 0x1fffff),
213             (16, 0x3fff), (16, 0x3fff), (16, 0x3fff), (16, 0x3fff),
214             (24, 0x7f), (24, 0x7f), (24, 0x7f), (24, 0x7f),
215             (24, 0x7f), (24, 0x7f), (24, 0x7f), (24, 0x7f)
216         ];
217
218         unsafe {
219             let ptr = data.as_ptr().offset(start as int) as *const u32;
220             let val = Int::from_be(*ptr);
221
222             let i = (val >> 28u) as uint;
223             let (shift, mask) = SHIFT_MASK_TABLE[i];
224             Ok(Res {
225                 val: ((val >> shift) & mask) as uint,
226                 next: start + (((32 - shift) >> 3) as uint)
227             })
228         }
229     }
230
231     pub fn doc_at<'a>(data: &'a [u8], start: uint) -> DecodeResult<TaggedDoc<'a>> {
232         let elt_tag = try!(vuint_at(data, start));
233         let elt_size = try!(vuint_at(data, elt_tag.next));
234         let end = elt_size.next + elt_size.val;
235         Ok(TaggedDoc {
236             tag: elt_tag.val,
237             doc: Doc { data: data, start: elt_size.next, end: end }
238         })
239     }
240
241     pub fn maybe_get_doc<'a>(d: Doc<'a>, tg: uint) -> Option<Doc<'a>> {
242         let mut pos = d.start;
243         while pos < d.end {
244             let elt_tag = try_or!(vuint_at(d.data, pos), None);
245             let elt_size = try_or!(vuint_at(d.data, elt_tag.next), None);
246             pos = elt_size.next + elt_size.val;
247             if elt_tag.val == tg {
248                 return Some(Doc { data: d.data, start: elt_size.next,
249                                   end: pos });
250             }
251         }
252         None
253     }
254
255     pub fn get_doc<'a>(d: Doc<'a>, tg: uint) -> Doc<'a> {
256         match maybe_get_doc(d, tg) {
257             Some(d) => d,
258             None => {
259                 error!("failed to find block with tag {}", tg);
260                 panic!();
261             }
262         }
263     }
264
265     pub fn docs<F>(d: Doc, mut it: F) -> bool where
266         F: FnMut(uint, Doc) -> bool,
267     {
268         let mut pos = d.start;
269         while pos < d.end {
270             let elt_tag = try_or!(vuint_at(d.data, pos), false);
271             let elt_size = try_or!(vuint_at(d.data, elt_tag.next), false);
272             pos = elt_size.next + elt_size.val;
273             let doc = Doc { data: d.data, start: elt_size.next, end: pos };
274             if !it(elt_tag.val, doc) {
275                 return false;
276             }
277         }
278         return true;
279     }
280
281     pub fn tagged_docs<F>(d: Doc, tg: uint, mut it: F) -> bool where
282         F: FnMut(Doc) -> bool,
283     {
284         let mut pos = d.start;
285         while pos < d.end {
286             let elt_tag = try_or!(vuint_at(d.data, pos), false);
287             let elt_size = try_or!(vuint_at(d.data, elt_tag.next), false);
288             pos = elt_size.next + elt_size.val;
289             if elt_tag.val == tg {
290                 let doc = Doc { data: d.data, start: elt_size.next,
291                                 end: pos };
292                 if !it(doc) {
293                     return false;
294                 }
295             }
296         }
297         return true;
298     }
299
300     pub fn with_doc_data<T, F>(d: Doc, f: F) -> T where
301         F: FnOnce(&[u8]) -> T,
302     {
303         f(d.data[d.start..d.end])
304     }
305
306
307     pub fn doc_as_u8(d: Doc) -> u8 {
308         assert_eq!(d.end, d.start + 1u);
309         d.data[d.start]
310     }
311
312     pub fn doc_as_u16(d: Doc) -> u16 {
313         assert_eq!(d.end, d.start + 2u);
314         u64_from_be_bytes(d.data, d.start, 2u) as u16
315     }
316
317     pub fn doc_as_u32(d: Doc) -> u32 {
318         assert_eq!(d.end, d.start + 4u);
319         u64_from_be_bytes(d.data, d.start, 4u) as u32
320     }
321
322     pub fn doc_as_u64(d: Doc) -> u64 {
323         assert_eq!(d.end, d.start + 8u);
324         u64_from_be_bytes(d.data, d.start, 8u)
325     }
326
327     pub fn doc_as_i8(d: Doc) -> i8 { doc_as_u8(d) as i8 }
328     pub fn doc_as_i16(d: Doc) -> i16 { doc_as_u16(d) as i16 }
329     pub fn doc_as_i32(d: Doc) -> i32 { doc_as_u32(d) as i32 }
330     pub fn doc_as_i64(d: Doc) -> i64 { doc_as_u64(d) as i64 }
331
332     pub struct Decoder<'a> {
333         parent: Doc<'a>,
334         pos: uint,
335     }
336
337     impl<'doc> Decoder<'doc> {
338         pub fn new(d: Doc<'doc>) -> Decoder<'doc> {
339             Decoder {
340                 parent: d,
341                 pos: d.start
342             }
343         }
344
345         fn _check_label(&mut self, lbl: &str) -> DecodeResult<()> {
346             if self.pos < self.parent.end {
347                 let TaggedDoc { tag: r_tag, doc: r_doc } =
348                     try!(doc_at(self.parent.data, self.pos));
349
350                 if r_tag == (EsLabel as uint) {
351                     self.pos = r_doc.end;
352                     let str = r_doc.as_str_slice();
353                     if lbl != str {
354                         return Err(Expected(format!("Expected label {} but \
355                                                      found {}", lbl, str)));
356                     }
357                 }
358             }
359             Ok(())
360         }
361
362         fn next_doc(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<Doc<'doc>> {
363             debug!(". next_doc(exp_tag={})", exp_tag);
364             if self.pos >= self.parent.end {
365                 return Err(Expected(format!("no more documents in \
366                                              current node!")));
367             }
368             let TaggedDoc { tag: r_tag, doc: r_doc } =
369                 try!(doc_at(self.parent.data, self.pos));
370             debug!("self.parent={}-{} self.pos={} r_tag={} r_doc={}-{}",
371                    self.parent.start,
372                    self.parent.end,
373                    self.pos,
374                    r_tag,
375                    r_doc.start,
376                    r_doc.end);
377             if r_tag != (exp_tag as uint) {
378                 return Err(Expected(format!("expected EBML doc with tag {} but \
379                                              found tag {}", exp_tag, r_tag)));
380             }
381             if r_doc.end > self.parent.end {
382                 return Err(Expected(format!("invalid EBML, child extends to \
383                                              {:#x}, parent to {:#x}",
384                                             r_doc.end, self.parent.end)));
385             }
386             self.pos = r_doc.end;
387             Ok(r_doc)
388         }
389
390         fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T> where
391             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
392         {
393             let d = try!(self.next_doc(exp_tag));
394             let old_parent = self.parent;
395             let old_pos = self.pos;
396             self.parent = d;
397             self.pos = d.start;
398             let r = try!(f(self));
399             self.parent = old_parent;
400             self.pos = old_pos;
401             Ok(r)
402         }
403
404         fn _next_uint(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<uint> {
405             let r = doc_as_u32(try!(self.next_doc(exp_tag)));
406             debug!("_next_uint exp_tag={} result={}", exp_tag, r);
407             Ok(r as uint)
408         }
409
410         pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R> where
411             F: FnOnce(&mut Decoder, Doc) -> DecodeResult<R>,
412         {
413             let doc = try!(self.next_doc(EsOpaque));
414
415             let (old_parent, old_pos) = (self.parent, self.pos);
416             self.parent = doc;
417             self.pos = doc.start;
418
419             let result = try!(op(self, doc));
420
421             self.parent = old_parent;
422             self.pos = old_pos;
423             Ok(result)
424         }
425     }
426
427     #[cfg(stage0)]
428     impl<'doc> serialize::Decoder<Error> for Decoder<'doc> {
429         fn read_nil(&mut self) -> DecodeResult<()> { Ok(()) }
430
431         fn read_u64(&mut self) -> DecodeResult<u64> { Ok(doc_as_u64(try!(self.next_doc(EsU64)))) }
432         fn read_u32(&mut self) -> DecodeResult<u32> { Ok(doc_as_u32(try!(self.next_doc(EsU32)))) }
433         fn read_u16(&mut self) -> DecodeResult<u16> { Ok(doc_as_u16(try!(self.next_doc(EsU16)))) }
434         fn read_u8 (&mut self) -> DecodeResult<u8 > { Ok(doc_as_u8 (try!(self.next_doc(EsU8 )))) }
435         fn read_uint(&mut self) -> DecodeResult<uint> {
436             let v = doc_as_u64(try!(self.next_doc(EsUint)));
437             if v > (::std::uint::MAX as u64) {
438                 Err(IntTooBig(v as uint))
439             } else {
440                 Ok(v as uint)
441             }
442         }
443
444         fn read_i64(&mut self) -> DecodeResult<i64> {
445             Ok(doc_as_u64(try!(self.next_doc(EsI64))) as i64)
446         }
447         fn read_i32(&mut self) -> DecodeResult<i32> {
448             Ok(doc_as_u32(try!(self.next_doc(EsI32))) as i32)
449         }
450         fn read_i16(&mut self) -> DecodeResult<i16> {
451             Ok(doc_as_u16(try!(self.next_doc(EsI16))) as i16)
452         }
453         fn read_i8 (&mut self) -> DecodeResult<i8> {
454             Ok(doc_as_u8(try!(self.next_doc(EsI8 ))) as i8)
455         }
456         fn read_int(&mut self) -> DecodeResult<int> {
457             let v = doc_as_u64(try!(self.next_doc(EsInt))) as i64;
458             if v > (int::MAX as i64) || v < (int::MIN as i64) {
459                 debug!("FIXME \\#6122: Removing this makes this function miscompile");
460                 Err(IntTooBig(v as uint))
461             } else {
462                 Ok(v as int)
463             }
464         }
465
466         fn read_bool(&mut self) -> DecodeResult<bool> {
467             Ok(doc_as_u8(try!(self.next_doc(EsBool))) != 0)
468         }
469
470         fn read_f64(&mut self) -> DecodeResult<f64> {
471             let bits = doc_as_u64(try!(self.next_doc(EsF64)));
472             Ok(unsafe { transmute(bits) })
473         }
474         fn read_f32(&mut self) -> DecodeResult<f32> {
475             let bits = doc_as_u32(try!(self.next_doc(EsF32)));
476             Ok(unsafe { transmute(bits) })
477         }
478         fn read_char(&mut self) -> DecodeResult<char> {
479             Ok(char::from_u32(doc_as_u32(try!(self.next_doc(EsChar)))).unwrap())
480         }
481         fn read_str(&mut self) -> DecodeResult<String> {
482             Ok(try!(self.next_doc(EsStr)).as_str())
483         }
484
485         // Compound types:
486         fn read_enum<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T> where
487             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
488         {
489             debug!("read_enum({})", name);
490             try!(self._check_label(name));
491
492             let doc = try!(self.next_doc(EsEnum));
493
494             let (old_parent, old_pos) = (self.parent, self.pos);
495             self.parent = doc;
496             self.pos = self.parent.start;
497
498             let result = try!(f(self));
499
500             self.parent = old_parent;
501             self.pos = old_pos;
502             Ok(result)
503         }
504
505         fn read_enum_variant<T, F>(&mut self, _: &[&str],
506                                    mut f: F) -> DecodeResult<T>
507             where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
508         {
509             debug!("read_enum_variant()");
510             let idx = try!(self._next_uint(EsEnumVid));
511             debug!("  idx={}", idx);
512
513             let doc = try!(self.next_doc(EsEnumBody));
514
515             let (old_parent, old_pos) = (self.parent, self.pos);
516             self.parent = doc;
517             self.pos = self.parent.start;
518
519             let result = try!(f(self, idx));
520
521             self.parent = old_parent;
522             self.pos = old_pos;
523             Ok(result)
524         }
525
526         fn read_enum_variant_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
527             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
528         {
529             debug!("read_enum_variant_arg(idx={})", idx);
530             f(self)
531         }
532
533         fn read_enum_struct_variant<T, F>(&mut self, _: &[&str],
534                                           mut f: F) -> DecodeResult<T>
535             where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
536         {
537             debug!("read_enum_struct_variant()");
538             let idx = try!(self._next_uint(EsEnumVid));
539             debug!("  idx={}", idx);
540
541             let doc = try!(self.next_doc(EsEnumBody));
542
543             let (old_parent, old_pos) = (self.parent, self.pos);
544             self.parent = doc;
545             self.pos = self.parent.start;
546
547             let result = try!(f(self, idx));
548
549             self.parent = old_parent;
550             self.pos = old_pos;
551             Ok(result)
552         }
553
554         fn read_enum_struct_variant_field<T, F>(&mut self,
555                                                 name: &str,
556                                                 idx: uint,
557                                                 f: F)
558                                                 -> DecodeResult<T> where
559             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
560         {
561                 debug!("read_enum_struct_variant_arg(name={}, idx={})", name, idx);
562             f(self)
563         }
564
565         fn read_struct<T, F>(&mut self, name: &str, _: uint, f: F) -> DecodeResult<T> where
566             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
567         {
568             debug!("read_struct(name={})", name);
569             f(self)
570         }
571
572         fn read_struct_field<T, F>(&mut self, name: &str, idx: uint, f: F) -> DecodeResult<T> where
573             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
574         {
575             debug!("read_struct_field(name={}, idx={})", name, idx);
576             try!(self._check_label(name));
577             f(self)
578         }
579
580         fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
581             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
582         {
583             debug!("read_tuple()");
584             self.read_seq(move |d, len| {
585                 if len == tuple_len {
586                     f(d)
587                 } else {
588                     Err(Expected(format!("Expected tuple of length `{}`, \
589                                           found tuple of length `{}`", tuple_len, len)))
590                 }
591             })
592         }
593
594         fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
595             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
596         {
597             debug!("read_tuple_arg(idx={})", idx);
598             self.read_seq_elt(idx, f)
599         }
600
601         fn read_tuple_struct<T, F>(&mut self, name: &str, len: uint, f: F) -> DecodeResult<T> where
602             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
603         {
604             debug!("read_tuple_struct(name={})", name);
605             self.read_tuple(len, f)
606         }
607
608         fn read_tuple_struct_arg<T, F>(&mut self,
609                                        idx: uint,
610                                        f: F)
611                                        -> DecodeResult<T> where
612             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
613         {
614             debug!("read_tuple_struct_arg(idx={})", idx);
615             self.read_tuple_arg(idx, f)
616         }
617
618         fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
619             F: FnMut(&mut Decoder<'doc>, bool) -> DecodeResult<T>,
620         {
621             debug!("read_option()");
622             self.read_enum("Option", move |this| {
623                 this.read_enum_variant(&["None", "Some"], move |this, idx| {
624                     match idx {
625                         0 => f(this, false),
626                         1 => f(this, true),
627                         _ => {
628                             Err(Expected(format!("Expected None or Some")))
629                         }
630                     }
631                 })
632             })
633         }
634
635         fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
636             F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
637         {
638             debug!("read_seq()");
639             self.push_doc(EsVec, move |d| {
640                 let len = try!(d._next_uint(EsVecLen));
641                 debug!("  len={}", len);
642                 f(d, len)
643             })
644         }
645
646         fn read_seq_elt<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
647             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
648         {
649             debug!("read_seq_elt(idx={})", idx);
650             self.push_doc(EsVecElt, f)
651         }
652
653         fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
654             F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
655         {
656             debug!("read_map()");
657             self.push_doc(EsMap, move |d| {
658                 let len = try!(d._next_uint(EsMapLen));
659                 debug!("  len={}", len);
660                 f(d, len)
661             })
662         }
663
664         fn read_map_elt_key<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
665             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
666         {
667             debug!("read_map_elt_key(idx={})", idx);
668             self.push_doc(EsMapKey, f)
669         }
670
671         fn read_map_elt_val<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
672             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
673         {
674             debug!("read_map_elt_val(idx={})", idx);
675             self.push_doc(EsMapVal, f)
676         }
677
678         fn error(&mut self, err: &str) -> Error {
679             ApplicationError(err.to_string())
680         }
681     }
682
683     #[cfg(not(stage0))]
684     impl<'doc> serialize::Decoder for Decoder<'doc> {
685         type Error = Error;
686         fn read_nil(&mut self) -> DecodeResult<()> { Ok(()) }
687
688         fn read_u64(&mut self) -> DecodeResult<u64> { Ok(doc_as_u64(try!(self.next_doc(EsU64)))) }
689         fn read_u32(&mut self) -> DecodeResult<u32> { Ok(doc_as_u32(try!(self.next_doc(EsU32)))) }
690         fn read_u16(&mut self) -> DecodeResult<u16> { Ok(doc_as_u16(try!(self.next_doc(EsU16)))) }
691         fn read_u8 (&mut self) -> DecodeResult<u8 > { Ok(doc_as_u8 (try!(self.next_doc(EsU8 )))) }
692         fn read_uint(&mut self) -> DecodeResult<uint> {
693             let v = doc_as_u64(try!(self.next_doc(EsUint)));
694             if v > (::std::uint::MAX as u64) {
695                 Err(IntTooBig(v as uint))
696             } else {
697                 Ok(v as uint)
698             }
699         }
700
701         fn read_i64(&mut self) -> DecodeResult<i64> {
702             Ok(doc_as_u64(try!(self.next_doc(EsI64))) as i64)
703         }
704         fn read_i32(&mut self) -> DecodeResult<i32> {
705             Ok(doc_as_u32(try!(self.next_doc(EsI32))) as i32)
706         }
707         fn read_i16(&mut self) -> DecodeResult<i16> {
708             Ok(doc_as_u16(try!(self.next_doc(EsI16))) as i16)
709         }
710         fn read_i8 (&mut self) -> DecodeResult<i8> {
711             Ok(doc_as_u8(try!(self.next_doc(EsI8 ))) as i8)
712         }
713         fn read_int(&mut self) -> DecodeResult<int> {
714             let v = doc_as_u64(try!(self.next_doc(EsInt))) as i64;
715             if v > (int::MAX as i64) || v < (int::MIN as i64) {
716                 debug!("FIXME \\#6122: Removing this makes this function miscompile");
717                 Err(IntTooBig(v as uint))
718             } else {
719                 Ok(v as int)
720             }
721         }
722
723         fn read_bool(&mut self) -> DecodeResult<bool> {
724             Ok(doc_as_u8(try!(self.next_doc(EsBool))) != 0)
725         }
726
727         fn read_f64(&mut self) -> DecodeResult<f64> {
728             let bits = doc_as_u64(try!(self.next_doc(EsF64)));
729             Ok(unsafe { transmute(bits) })
730         }
731         fn read_f32(&mut self) -> DecodeResult<f32> {
732             let bits = doc_as_u32(try!(self.next_doc(EsF32)));
733             Ok(unsafe { transmute(bits) })
734         }
735         fn read_char(&mut self) -> DecodeResult<char> {
736             Ok(char::from_u32(doc_as_u32(try!(self.next_doc(EsChar)))).unwrap())
737         }
738         fn read_str(&mut self) -> DecodeResult<String> {
739             Ok(try!(self.next_doc(EsStr)).as_str())
740         }
741
742         // Compound types:
743         fn read_enum<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T> where
744             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
745         {
746             debug!("read_enum({})", name);
747             try!(self._check_label(name));
748
749             let doc = try!(self.next_doc(EsEnum));
750
751             let (old_parent, old_pos) = (self.parent, self.pos);
752             self.parent = doc;
753             self.pos = self.parent.start;
754
755             let result = try!(f(self));
756
757             self.parent = old_parent;
758             self.pos = old_pos;
759             Ok(result)
760         }
761
762         fn read_enum_variant<T, F>(&mut self, _: &[&str],
763                                    mut f: F) -> DecodeResult<T>
764             where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
765         {
766             debug!("read_enum_variant()");
767             let idx = try!(self._next_uint(EsEnumVid));
768             debug!("  idx={}", idx);
769
770             let doc = try!(self.next_doc(EsEnumBody));
771
772             let (old_parent, old_pos) = (self.parent, self.pos);
773             self.parent = doc;
774             self.pos = self.parent.start;
775
776             let result = try!(f(self, idx));
777
778             self.parent = old_parent;
779             self.pos = old_pos;
780             Ok(result)
781         }
782
783         fn read_enum_variant_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
784             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
785         {
786             debug!("read_enum_variant_arg(idx={})", idx);
787             f(self)
788         }
789
790         fn read_enum_struct_variant<T, F>(&mut self, _: &[&str],
791                                           mut f: F) -> DecodeResult<T>
792             where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
793         {
794             debug!("read_enum_struct_variant()");
795             let idx = try!(self._next_uint(EsEnumVid));
796             debug!("  idx={}", idx);
797
798             let doc = try!(self.next_doc(EsEnumBody));
799
800             let (old_parent, old_pos) = (self.parent, self.pos);
801             self.parent = doc;
802             self.pos = self.parent.start;
803
804             let result = try!(f(self, idx));
805
806             self.parent = old_parent;
807             self.pos = old_pos;
808             Ok(result)
809         }
810
811         fn read_enum_struct_variant_field<T, F>(&mut self,
812                                                 name: &str,
813                                                 idx: uint,
814                                                 f: F)
815                                                 -> DecodeResult<T> where
816             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
817         {
818                 debug!("read_enum_struct_variant_arg(name={}, idx={})", name, idx);
819             f(self)
820         }
821
822         fn read_struct<T, F>(&mut self, name: &str, _: uint, f: F) -> DecodeResult<T> where
823             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
824         {
825             debug!("read_struct(name={})", name);
826             f(self)
827         }
828
829         fn read_struct_field<T, F>(&mut self, name: &str, idx: uint, f: F) -> DecodeResult<T> where
830             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
831         {
832             debug!("read_struct_field(name={}, idx={})", name, idx);
833             try!(self._check_label(name));
834             f(self)
835         }
836
837         fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
838             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
839         {
840             debug!("read_tuple()");
841             self.read_seq(move |d, len| {
842                 if len == tuple_len {
843                     f(d)
844                 } else {
845                     Err(Expected(format!("Expected tuple of length `{}`, \
846                                           found tuple of length `{}`", tuple_len, len)))
847                 }
848             })
849         }
850
851         fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
852             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
853         {
854             debug!("read_tuple_arg(idx={})", idx);
855             self.read_seq_elt(idx, f)
856         }
857
858         fn read_tuple_struct<T, F>(&mut self, name: &str, len: uint, f: F) -> DecodeResult<T> where
859             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
860         {
861             debug!("read_tuple_struct(name={})", name);
862             self.read_tuple(len, f)
863         }
864
865         fn read_tuple_struct_arg<T, F>(&mut self,
866                                        idx: uint,
867                                        f: F)
868                                        -> DecodeResult<T> where
869             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
870         {
871             debug!("read_tuple_struct_arg(idx={})", idx);
872             self.read_tuple_arg(idx, f)
873         }
874
875         fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
876             F: FnMut(&mut Decoder<'doc>, bool) -> DecodeResult<T>,
877         {
878             debug!("read_option()");
879             self.read_enum("Option", move |this| {
880                 this.read_enum_variant(&["None", "Some"], move |this, idx| {
881                     match idx {
882                         0 => f(this, false),
883                         1 => f(this, true),
884                         _ => {
885                             Err(Expected(format!("Expected None or Some")))
886                         }
887                     }
888                 })
889             })
890         }
891
892         fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
893             F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
894         {
895             debug!("read_seq()");
896             self.push_doc(EsVec, move |d| {
897                 let len = try!(d._next_uint(EsVecLen));
898                 debug!("  len={}", len);
899                 f(d, len)
900             })
901         }
902
903         fn read_seq_elt<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
904             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
905         {
906             debug!("read_seq_elt(idx={})", idx);
907             self.push_doc(EsVecElt, f)
908         }
909
910         fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
911             F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
912         {
913             debug!("read_map()");
914             self.push_doc(EsMap, move |d| {
915                 let len = try!(d._next_uint(EsMapLen));
916                 debug!("  len={}", len);
917                 f(d, len)
918             })
919         }
920
921         fn read_map_elt_key<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
922             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
923         {
924             debug!("read_map_elt_key(idx={})", idx);
925             self.push_doc(EsMapKey, f)
926         }
927
928         fn read_map_elt_val<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
929             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
930         {
931             debug!("read_map_elt_val(idx={})", idx);
932             self.push_doc(EsMapVal, f)
933         }
934
935         fn error(&mut self, err: &str) -> Error {
936             ApplicationError(err.to_string())
937         }
938     }
939 }
940
941 pub mod writer {
942     use std::clone::Clone;
943     use std::io::extensions::u64_to_be_bytes;
944     use std::io::{Writer, Seek};
945     use std::io;
946     use std::mem;
947
948     use super::{ EsVec, EsMap, EsEnum, EsVecLen, EsVecElt, EsMapLen, EsMapKey,
949         EsEnumVid, EsU64, EsU32, EsU16, EsU8, EsInt, EsI64, EsI32, EsI16, EsI8,
950         EsBool, EsF64, EsF32, EsChar, EsStr, EsMapVal, EsEnumBody, EsUint,
951         EsOpaque, EsLabel, EbmlEncoderTag };
952
953     use serialize;
954
955
956     pub type EncodeResult = io::IoResult<()>;
957
958     // rbml writing
959     pub struct Encoder<'a, W:'a> {
960         pub writer: &'a mut W,
961         size_positions: Vec<uint>,
962     }
963
964     fn write_sized_vuint<W: Writer>(w: &mut W, n: uint, size: uint) -> EncodeResult {
965         match size {
966             1u => w.write(&[0x80u8 | (n as u8)]),
967             2u => w.write(&[0x40u8 | ((n >> 8_u) as u8), n as u8]),
968             3u => w.write(&[0x20u8 | ((n >> 16_u) as u8), (n >> 8_u) as u8,
969                             n as u8]),
970             4u => w.write(&[0x10u8 | ((n >> 24_u) as u8), (n >> 16_u) as u8,
971                             (n >> 8_u) as u8, n as u8]),
972             _ => Err(io::IoError {
973                 kind: io::OtherIoError,
974                 desc: "int too big",
975                 detail: Some(format!("{}", n))
976             })
977         }
978     }
979
980     fn write_vuint<W: Writer>(w: &mut W, n: uint) -> EncodeResult {
981         if n < 0x7f_u { return write_sized_vuint(w, n, 1u); }
982         if n < 0x4000_u { return write_sized_vuint(w, n, 2u); }
983         if n < 0x200000_u { return write_sized_vuint(w, n, 3u); }
984         if n < 0x10000000_u { return write_sized_vuint(w, n, 4u); }
985         Err(io::IoError {
986             kind: io::OtherIoError,
987             desc: "int too big",
988             detail: Some(format!("{}", n))
989         })
990     }
991
992     // FIXME (#2741): Provide a function to write the standard rbml header.
993     impl<'a, W: Writer + Seek> Encoder<'a, W> {
994         pub fn new(w: &'a mut W) -> Encoder<'a, W> {
995             Encoder {
996                 writer: w,
997                 size_positions: vec!(),
998             }
999         }
1000
1001         /// FIXME(pcwalton): Workaround for badness in trans. DO NOT USE ME.
1002         pub unsafe fn unsafe_clone(&self) -> Encoder<'a, W> {
1003             Encoder {
1004                 writer: mem::transmute_copy(&self.writer),
1005                 size_positions: self.size_positions.clone(),
1006             }
1007         }
1008
1009         pub fn start_tag(&mut self, tag_id: uint) -> EncodeResult {
1010             debug!("Start tag {}", tag_id);
1011
1012             // Write the enum ID:
1013             try!(write_vuint(self.writer, tag_id));
1014
1015             // Write a placeholder four-byte size.
1016             self.size_positions.push(try!(self.writer.tell()) as uint);
1017             let zeroes: &[u8] = &[0u8, 0u8, 0u8, 0u8];
1018             self.writer.write(zeroes)
1019         }
1020
1021         pub fn end_tag(&mut self) -> EncodeResult {
1022             let last_size_pos = self.size_positions.pop().unwrap();
1023             let cur_pos = try!(self.writer.tell());
1024             try!(self.writer.seek(last_size_pos as i64, io::SeekSet));
1025             let size = cur_pos as uint - last_size_pos - 4;
1026             try!(write_sized_vuint(self.writer, size, 4u));
1027             let r = try!(self.writer.seek(cur_pos as i64, io::SeekSet));
1028
1029             debug!("End tag (size = {})", size);
1030             Ok(r)
1031         }
1032
1033         pub fn wr_tag<F>(&mut self, tag_id: uint, blk: F) -> EncodeResult where
1034             F: FnOnce() -> EncodeResult,
1035         {
1036             try!(self.start_tag(tag_id));
1037             try!(blk());
1038             self.end_tag()
1039         }
1040
1041         pub fn wr_tagged_bytes(&mut self, tag_id: uint, b: &[u8]) -> EncodeResult {
1042             try!(write_vuint(self.writer, tag_id));
1043             try!(write_vuint(self.writer, b.len()));
1044             self.writer.write(b)
1045         }
1046
1047         pub fn wr_tagged_u64(&mut self, tag_id: uint, v: u64) -> EncodeResult {
1048             u64_to_be_bytes(v, 8u, |v| {
1049                 self.wr_tagged_bytes(tag_id, v)
1050             })
1051         }
1052
1053         pub fn wr_tagged_u32(&mut self, tag_id: uint, v: u32)  -> EncodeResult{
1054             u64_to_be_bytes(v as u64, 4u, |v| {
1055                 self.wr_tagged_bytes(tag_id, v)
1056             })
1057         }
1058
1059         pub fn wr_tagged_u16(&mut self, tag_id: uint, v: u16) -> EncodeResult {
1060             u64_to_be_bytes(v as u64, 2u, |v| {
1061                 self.wr_tagged_bytes(tag_id, v)
1062             })
1063         }
1064
1065         pub fn wr_tagged_u8(&mut self, tag_id: uint, v: u8) -> EncodeResult {
1066             self.wr_tagged_bytes(tag_id, &[v])
1067         }
1068
1069         pub fn wr_tagged_i64(&mut self, tag_id: uint, v: i64) -> EncodeResult {
1070             u64_to_be_bytes(v as u64, 8u, |v| {
1071                 self.wr_tagged_bytes(tag_id, v)
1072             })
1073         }
1074
1075         pub fn wr_tagged_i32(&mut self, tag_id: uint, v: i32) -> EncodeResult {
1076             u64_to_be_bytes(v as u64, 4u, |v| {
1077                 self.wr_tagged_bytes(tag_id, v)
1078             })
1079         }
1080
1081         pub fn wr_tagged_i16(&mut self, tag_id: uint, v: i16) -> EncodeResult {
1082             u64_to_be_bytes(v as u64, 2u, |v| {
1083                 self.wr_tagged_bytes(tag_id, v)
1084             })
1085         }
1086
1087         pub fn wr_tagged_i8(&mut self, tag_id: uint, v: i8) -> EncodeResult {
1088             self.wr_tagged_bytes(tag_id, &[v as u8])
1089         }
1090
1091         pub fn wr_tagged_str(&mut self, tag_id: uint, v: &str) -> EncodeResult {
1092             self.wr_tagged_bytes(tag_id, v.as_bytes())
1093         }
1094
1095         pub fn wr_bytes(&mut self, b: &[u8]) -> EncodeResult {
1096             debug!("Write {} bytes", b.len());
1097             self.writer.write(b)
1098         }
1099
1100         pub fn wr_str(&mut self, s: &str) -> EncodeResult {
1101             debug!("Write str: {}", s);
1102             self.writer.write(s.as_bytes())
1103         }
1104     }
1105
1106     // FIXME (#2743): optionally perform "relaxations" on end_tag to more
1107     // efficiently encode sizes; this is a fixed point iteration
1108
1109     // Set to true to generate more debugging in EBML code.
1110     // Totally lame approach.
1111     static DEBUG: bool = true;
1112
1113     impl<'a, W: Writer + Seek> Encoder<'a, W> {
1114         // used internally to emit things like the vector length and so on
1115         fn _emit_tagged_uint(&mut self, t: EbmlEncoderTag, v: uint) -> EncodeResult {
1116             assert!(v <= 0xFFFF_FFFF_u);
1117             self.wr_tagged_u32(t as uint, v as u32)
1118         }
1119
1120         fn _emit_label(&mut self, label: &str) -> EncodeResult {
1121             // There are various strings that we have access to, such as
1122             // the name of a record field, which do not actually appear in
1123             // the encoded EBML (normally).  This is just for
1124             // efficiency.  When debugging, though, we can emit such
1125             // labels and then they will be checked by decoder to
1126             // try and check panics more quickly.
1127             if DEBUG { self.wr_tagged_str(EsLabel as uint, label) }
1128             else { Ok(()) }
1129         }
1130
1131         pub fn emit_opaque<F>(&mut self, f: F) -> EncodeResult where
1132             F: FnOnce(&mut Encoder<W>) -> EncodeResult,
1133         {
1134             try!(self.start_tag(EsOpaque as uint));
1135             try!(f(self));
1136             self.end_tag()
1137         }
1138     }
1139
1140     #[cfg(stage0)]
1141     impl<'a, W: Writer + Seek> serialize::Encoder<io::IoError> for Encoder<'a, W> {
1142
1143         fn emit_nil(&mut self) -> EncodeResult {
1144             Ok(())
1145         }
1146
1147         fn emit_uint(&mut self, v: uint) -> EncodeResult {
1148             self.wr_tagged_u64(EsUint as uint, v as u64)
1149         }
1150         fn emit_u64(&mut self, v: u64) -> EncodeResult {
1151             self.wr_tagged_u64(EsU64 as uint, v)
1152         }
1153         fn emit_u32(&mut self, v: u32) -> EncodeResult {
1154             self.wr_tagged_u32(EsU32 as uint, v)
1155         }
1156         fn emit_u16(&mut self, v: u16) -> EncodeResult {
1157             self.wr_tagged_u16(EsU16 as uint, v)
1158         }
1159         fn emit_u8(&mut self, v: u8) -> EncodeResult {
1160             self.wr_tagged_u8(EsU8 as uint, v)
1161         }
1162
1163         fn emit_int(&mut self, v: int) -> EncodeResult {
1164             self.wr_tagged_i64(EsInt as uint, v as i64)
1165         }
1166         fn emit_i64(&mut self, v: i64) -> EncodeResult {
1167             self.wr_tagged_i64(EsI64 as uint, v)
1168         }
1169         fn emit_i32(&mut self, v: i32) -> EncodeResult {
1170             self.wr_tagged_i32(EsI32 as uint, v)
1171         }
1172         fn emit_i16(&mut self, v: i16) -> EncodeResult {
1173             self.wr_tagged_i16(EsI16 as uint, v)
1174         }
1175         fn emit_i8(&mut self, v: i8) -> EncodeResult {
1176             self.wr_tagged_i8(EsI8 as uint, v)
1177         }
1178
1179         fn emit_bool(&mut self, v: bool) -> EncodeResult {
1180             self.wr_tagged_u8(EsBool as uint, v as u8)
1181         }
1182
1183         fn emit_f64(&mut self, v: f64) -> EncodeResult {
1184             let bits = unsafe { mem::transmute(v) };
1185             self.wr_tagged_u64(EsF64 as uint, bits)
1186         }
1187         fn emit_f32(&mut self, v: f32) -> EncodeResult {
1188             let bits = unsafe { mem::transmute(v) };
1189             self.wr_tagged_u32(EsF32 as uint, bits)
1190         }
1191         fn emit_char(&mut self, v: char) -> EncodeResult {
1192             self.wr_tagged_u32(EsChar as uint, v as u32)
1193         }
1194
1195         fn emit_str(&mut self, v: &str) -> EncodeResult {
1196             self.wr_tagged_str(EsStr as uint, v)
1197         }
1198
1199         fn emit_enum<F>(&mut self, name: &str, f: F) -> EncodeResult where
1200             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1201         {
1202             try!(self._emit_label(name));
1203             try!(self.start_tag(EsEnum as uint));
1204             try!(f(self));
1205             self.end_tag()
1206         }
1207
1208         fn emit_enum_variant<F>(&mut self,
1209                                 _: &str,
1210                                 v_id: uint,
1211                                 _: uint,
1212                                 f: F) -> EncodeResult where
1213             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1214         {
1215             try!(self._emit_tagged_uint(EsEnumVid, v_id));
1216             try!(self.start_tag(EsEnumBody as uint));
1217             try!(f(self));
1218             self.end_tag()
1219         }
1220
1221         fn emit_enum_variant_arg<F>(&mut self, _: uint, f: F) -> EncodeResult where
1222             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1223         {
1224             f(self)
1225         }
1226
1227         fn emit_enum_struct_variant<F>(&mut self,
1228                                        v_name: &str,
1229                                        v_id: uint,
1230                                        cnt: uint,
1231                                        f: F) -> EncodeResult where
1232             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1233         {
1234             self.emit_enum_variant(v_name, v_id, cnt, f)
1235         }
1236
1237         fn emit_enum_struct_variant_field<F>(&mut self,
1238                                              _: &str,
1239                                              idx: uint,
1240                                              f: F) -> EncodeResult where
1241             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1242         {
1243             self.emit_enum_variant_arg(idx, f)
1244         }
1245
1246         fn emit_struct<F>(&mut self, _: &str, _len: uint, f: F) -> EncodeResult where
1247             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1248         {
1249             f(self)
1250         }
1251
1252         fn emit_struct_field<F>(&mut self, name: &str, _: uint, f: F) -> EncodeResult where
1253             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1254         {
1255             try!(self._emit_label(name));
1256             f(self)
1257         }
1258
1259         fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
1260             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1261         {
1262             self.emit_seq(len, f)
1263         }
1264         fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
1265             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1266         {
1267             self.emit_seq_elt(idx, f)
1268         }
1269
1270         fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
1271             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1272         {
1273             self.emit_seq(len, f)
1274         }
1275         fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
1276             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1277         {
1278             self.emit_seq_elt(idx, f)
1279         }
1280
1281         fn emit_option<F>(&mut self, f: F) -> EncodeResult where
1282             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1283         {
1284             self.emit_enum("Option", f)
1285         }
1286         fn emit_option_none(&mut self) -> EncodeResult {
1287             self.emit_enum_variant("None", 0, 0, |_| Ok(()))
1288         }
1289         fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
1290             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1291         {
1292
1293             self.emit_enum_variant("Some", 1, 1, f)
1294         }
1295
1296         fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
1297             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1298         {
1299
1300             try!(self.start_tag(EsVec as uint));
1301             try!(self._emit_tagged_uint(EsVecLen, len));
1302             try!(f(self));
1303             self.end_tag()
1304         }
1305
1306         fn emit_seq_elt<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
1307             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1308         {
1309
1310             try!(self.start_tag(EsVecElt as uint));
1311             try!(f(self));
1312             self.end_tag()
1313         }
1314
1315         fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
1316             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1317         {
1318
1319             try!(self.start_tag(EsMap as uint));
1320             try!(self._emit_tagged_uint(EsMapLen, len));
1321             try!(f(self));
1322             self.end_tag()
1323         }
1324
1325         fn emit_map_elt_key<F>(&mut self, _idx: uint, mut f: F) -> EncodeResult where
1326             F: FnMut(&mut Encoder<'a, W>) -> EncodeResult,
1327         {
1328
1329             try!(self.start_tag(EsMapKey as uint));
1330             try!(f(self));
1331             self.end_tag()
1332         }
1333
1334         fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
1335             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1336         {
1337             try!(self.start_tag(EsMapVal as uint));
1338             try!(f(self));
1339             self.end_tag()
1340         }
1341     }
1342     #[cfg(not(stage0))]
1343     impl<'a, W: Writer + Seek> serialize::Encoder for Encoder<'a, W> {
1344         type Error = io::IoError;
1345
1346         fn emit_nil(&mut self) -> EncodeResult {
1347             Ok(())
1348         }
1349
1350         fn emit_uint(&mut self, v: uint) -> EncodeResult {
1351             self.wr_tagged_u64(EsUint as uint, v as u64)
1352         }
1353         fn emit_u64(&mut self, v: u64) -> EncodeResult {
1354             self.wr_tagged_u64(EsU64 as uint, v)
1355         }
1356         fn emit_u32(&mut self, v: u32) -> EncodeResult {
1357             self.wr_tagged_u32(EsU32 as uint, v)
1358         }
1359         fn emit_u16(&mut self, v: u16) -> EncodeResult {
1360             self.wr_tagged_u16(EsU16 as uint, v)
1361         }
1362         fn emit_u8(&mut self, v: u8) -> EncodeResult {
1363             self.wr_tagged_u8(EsU8 as uint, v)
1364         }
1365
1366         fn emit_int(&mut self, v: int) -> EncodeResult {
1367             self.wr_tagged_i64(EsInt as uint, v as i64)
1368         }
1369         fn emit_i64(&mut self, v: i64) -> EncodeResult {
1370             self.wr_tagged_i64(EsI64 as uint, v)
1371         }
1372         fn emit_i32(&mut self, v: i32) -> EncodeResult {
1373             self.wr_tagged_i32(EsI32 as uint, v)
1374         }
1375         fn emit_i16(&mut self, v: i16) -> EncodeResult {
1376             self.wr_tagged_i16(EsI16 as uint, v)
1377         }
1378         fn emit_i8(&mut self, v: i8) -> EncodeResult {
1379             self.wr_tagged_i8(EsI8 as uint, v)
1380         }
1381
1382         fn emit_bool(&mut self, v: bool) -> EncodeResult {
1383             self.wr_tagged_u8(EsBool as uint, v as u8)
1384         }
1385
1386         fn emit_f64(&mut self, v: f64) -> EncodeResult {
1387             let bits = unsafe { mem::transmute(v) };
1388             self.wr_tagged_u64(EsF64 as uint, bits)
1389         }
1390         fn emit_f32(&mut self, v: f32) -> EncodeResult {
1391             let bits = unsafe { mem::transmute(v) };
1392             self.wr_tagged_u32(EsF32 as uint, bits)
1393         }
1394         fn emit_char(&mut self, v: char) -> EncodeResult {
1395             self.wr_tagged_u32(EsChar as uint, v as u32)
1396         }
1397
1398         fn emit_str(&mut self, v: &str) -> EncodeResult {
1399             self.wr_tagged_str(EsStr as uint, v)
1400         }
1401
1402         fn emit_enum<F>(&mut self, name: &str, f: F) -> EncodeResult where
1403             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1404         {
1405             try!(self._emit_label(name));
1406             try!(self.start_tag(EsEnum as uint));
1407             try!(f(self));
1408             self.end_tag()
1409         }
1410
1411         fn emit_enum_variant<F>(&mut self,
1412                                 _: &str,
1413                                 v_id: uint,
1414                                 _: uint,
1415                                 f: F) -> EncodeResult where
1416             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1417         {
1418             try!(self._emit_tagged_uint(EsEnumVid, v_id));
1419             try!(self.start_tag(EsEnumBody as uint));
1420             try!(f(self));
1421             self.end_tag()
1422         }
1423
1424         fn emit_enum_variant_arg<F>(&mut self, _: uint, f: F) -> EncodeResult where
1425             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1426         {
1427             f(self)
1428         }
1429
1430         fn emit_enum_struct_variant<F>(&mut self,
1431                                        v_name: &str,
1432                                        v_id: uint,
1433                                        cnt: uint,
1434                                        f: F) -> EncodeResult where
1435             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1436         {
1437             self.emit_enum_variant(v_name, v_id, cnt, f)
1438         }
1439
1440         fn emit_enum_struct_variant_field<F>(&mut self,
1441                                              _: &str,
1442                                              idx: uint,
1443                                              f: F) -> EncodeResult where
1444             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1445         {
1446             self.emit_enum_variant_arg(idx, f)
1447         }
1448
1449         fn emit_struct<F>(&mut self, _: &str, _len: uint, f: F) -> EncodeResult where
1450             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1451         {
1452             f(self)
1453         }
1454
1455         fn emit_struct_field<F>(&mut self, name: &str, _: uint, f: F) -> EncodeResult where
1456             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1457         {
1458             try!(self._emit_label(name));
1459             f(self)
1460         }
1461
1462         fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
1463             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1464         {
1465             self.emit_seq(len, f)
1466         }
1467         fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
1468             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1469         {
1470             self.emit_seq_elt(idx, f)
1471         }
1472
1473         fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
1474             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1475         {
1476             self.emit_seq(len, f)
1477         }
1478         fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
1479             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1480         {
1481             self.emit_seq_elt(idx, f)
1482         }
1483
1484         fn emit_option<F>(&mut self, f: F) -> EncodeResult where
1485             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1486         {
1487             self.emit_enum("Option", f)
1488         }
1489         fn emit_option_none(&mut self) -> EncodeResult {
1490             self.emit_enum_variant("None", 0, 0, |_| Ok(()))
1491         }
1492         fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
1493             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1494         {
1495
1496             self.emit_enum_variant("Some", 1, 1, f)
1497         }
1498
1499         fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
1500             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1501         {
1502
1503             try!(self.start_tag(EsVec as uint));
1504             try!(self._emit_tagged_uint(EsVecLen, len));
1505             try!(f(self));
1506             self.end_tag()
1507         }
1508
1509         fn emit_seq_elt<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
1510             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1511         {
1512
1513             try!(self.start_tag(EsVecElt as uint));
1514             try!(f(self));
1515             self.end_tag()
1516         }
1517
1518         fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
1519             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1520         {
1521
1522             try!(self.start_tag(EsMap as uint));
1523             try!(self._emit_tagged_uint(EsMapLen, len));
1524             try!(f(self));
1525             self.end_tag()
1526         }
1527
1528         fn emit_map_elt_key<F>(&mut self, _idx: uint, mut f: F) -> EncodeResult where
1529             F: FnMut(&mut Encoder<'a, W>) -> EncodeResult,
1530         {
1531
1532             try!(self.start_tag(EsMapKey as uint));
1533             try!(f(self));
1534             self.end_tag()
1535         }
1536
1537         fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
1538             F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1539         {
1540             try!(self.start_tag(EsMapVal as uint));
1541             try!(f(self));
1542             self.end_tag()
1543         }
1544     }
1545 }
1546
1547 // ___________________________________________________________________________
1548 // Testing
1549
1550 #[cfg(test)]
1551 mod tests {
1552     use super::{Doc, reader, writer};
1553     use super::io::SeekableMemWriter;
1554
1555     use serialize::{Encodable, Decodable};
1556
1557     use std::option::Option;
1558     use std::option::Option::{None, Some};
1559
1560     #[test]
1561     fn test_vuint_at() {
1562         let data = &[
1563             0x80,
1564             0xff,
1565             0x40, 0x00,
1566             0x7f, 0xff,
1567             0x20, 0x00, 0x00,
1568             0x3f, 0xff, 0xff,
1569             0x10, 0x00, 0x00, 0x00,
1570             0x1f, 0xff, 0xff, 0xff
1571         ];
1572
1573         let mut res: reader::Res;
1574
1575         // Class A
1576         res = reader::vuint_at(data, 0).unwrap();
1577         assert_eq!(res.val, 0);
1578         assert_eq!(res.next, 1);
1579         res = reader::vuint_at(data, res.next).unwrap();
1580         assert_eq!(res.val, (1 << 7) - 1);
1581         assert_eq!(res.next, 2);
1582
1583         // Class B
1584         res = reader::vuint_at(data, res.next).unwrap();
1585         assert_eq!(res.val, 0);
1586         assert_eq!(res.next, 4);
1587         res = reader::vuint_at(data, res.next).unwrap();
1588         assert_eq!(res.val, (1 << 14) - 1);
1589         assert_eq!(res.next, 6);
1590
1591         // Class C
1592         res = reader::vuint_at(data, res.next).unwrap();
1593         assert_eq!(res.val, 0);
1594         assert_eq!(res.next, 9);
1595         res = reader::vuint_at(data, res.next).unwrap();
1596         assert_eq!(res.val, (1 << 21) - 1);
1597         assert_eq!(res.next, 12);
1598
1599         // Class D
1600         res = reader::vuint_at(data, res.next).unwrap();
1601         assert_eq!(res.val, 0);
1602         assert_eq!(res.next, 16);
1603         res = reader::vuint_at(data, res.next).unwrap();
1604         assert_eq!(res.val, (1 << 28) - 1);
1605         assert_eq!(res.next, 20);
1606     }
1607
1608     #[test]
1609     fn test_option_int() {
1610         fn test_v(v: Option<int>) {
1611             debug!("v == {}", v);
1612             let mut wr = SeekableMemWriter::new();
1613             {
1614                 let mut rbml_w = writer::Encoder::new(&mut wr);
1615                 let _ = v.encode(&mut rbml_w);
1616             }
1617             let rbml_doc = Doc::new(wr.get_ref());
1618             let mut deser = reader::Decoder::new(rbml_doc);
1619             let v1 = Decodable::decode(&mut deser).unwrap();
1620             debug!("v1 == {}", v1);
1621             assert_eq!(v, v1);
1622         }
1623
1624         test_v(Some(22));
1625         test_v(None);
1626         test_v(Some(3));
1627     }
1628 }
1629
1630 #[cfg(test)]
1631 mod bench {
1632     #![allow(non_snake_case)]
1633     use test::Bencher;
1634     use super::reader;
1635
1636     #[bench]
1637     pub fn vuint_at_A_aligned(b: &mut Bencher) {
1638         let data = range(0, 4*100).map(|i| {
1639             match i % 2 {
1640               0 => 0x80u8,
1641               _ => i as u8,
1642             }
1643         }).collect::<Vec<_>>();
1644         let mut sum = 0u;
1645         b.iter(|| {
1646             let mut i = 0;
1647             while i < data.len() {
1648                 sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
1649                 i += 4;
1650             }
1651         });
1652     }
1653
1654     #[bench]
1655     pub fn vuint_at_A_unaligned(b: &mut Bencher) {
1656         let data = range(0, 4*100+1).map(|i| {
1657             match i % 2 {
1658               1 => 0x80u8,
1659               _ => i as u8
1660             }
1661         }).collect::<Vec<_>>();
1662         let mut sum = 0u;
1663         b.iter(|| {
1664             let mut i = 1;
1665             while i < data.len() {
1666                 sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
1667                 i += 4;
1668             }
1669         });
1670     }
1671
1672     #[bench]
1673     pub fn vuint_at_D_aligned(b: &mut Bencher) {
1674         let data = range(0, 4*100).map(|i| {
1675             match i % 4 {
1676               0 => 0x10u8,
1677               3 => i as u8,
1678               _ => 0u8
1679             }
1680         }).collect::<Vec<_>>();
1681         let mut sum = 0u;
1682         b.iter(|| {
1683             let mut i = 0;
1684             while i < data.len() {
1685                 sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
1686                 i += 4;
1687             }
1688         });
1689     }
1690
1691     #[bench]
1692     pub fn vuint_at_D_unaligned(b: &mut Bencher) {
1693         let data = range(0, 4*100+1).map(|i| {
1694             match i % 4 {
1695               1 => 0x10u8,
1696               0 => i as u8,
1697               _ => 0u8
1698             }
1699         }).collect::<Vec<_>>();
1700         let mut sum = 0u;
1701         b.iter(|| {
1702             let mut i = 1;
1703             while i < data.len() {
1704                 sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
1705                 i += 4;
1706             }
1707         });
1708     }
1709 }