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