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.
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.
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.
15 //! It is loosely based on the Extensible Binary Markup Language (ebml):
16 //! http://www.matroska.org/technical/specs/rfc/index.html
18 #![crate_name = "rbml"]
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)]
31 extern crate serialize;
34 #[phase(plugin, link)]
41 #[cfg(test)] extern crate test;
43 pub use self::EbmlEncoderTag::*;
44 pub use self::Error::*;
50 /// Common data structures
51 #[derive(Clone, Copy)]
58 impl<'doc> Doc<'doc> {
59 pub fn new(data: &'doc [u8]) -> Doc<'doc> {
60 Doc { data: data, start: 0u, end: data.len() }
63 pub fn get<'a>(&'a self, tag: uint) -> Doc<'a> {
64 reader::get_doc(*self, tag)
67 pub fn as_str_slice<'a>(&'a self) -> &'a str {
68 str::from_utf8(self.data[self.start..self.end]).unwrap()
71 pub fn as_str(&self) -> String {
72 self.as_str_slice().to_string()
76 pub struct TaggedDoc<'a> {
82 pub enum EbmlEncoderTag {
112 EsLabel, // Used only when debugging
119 IoError(std::io::IoError),
120 ApplicationError(String)
122 // --------------------------------------
128 use std::io::extensions::u64_from_be_bytes;
129 use std::mem::transmute;
131 use std::option::Option;
132 use std::option::Option::{None, Some};
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 };
142 pub type DecodeResult<T> = Result<T, Error>;
145 macro_rules! try_or {
146 ($e:expr, $r:expr) => (
150 debug!("ignored error: {}", e);
164 fn vuint_at_slow(data: &[u8], start: uint) -> DecodeResult<Res> {
166 if a & 0x80u8 != 0u8 {
167 return Ok(Res {val: (a & 0x7fu8) as uint, next: start + 1u});
169 if a & 0x40u8 != 0u8 {
170 return Ok(Res {val: ((a & 0x3fu8) as uint) << 8u |
171 (data[start + 1u] as uint),
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),
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),
187 Err(IntTooBig(a as uint))
190 pub fn vuint_at(data: &[u8], start: uint) -> DecodeResult<Res> {
191 if data.len() - start < 4 {
192 return vuint_at_slow(data, start);
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.
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).
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)
219 let ptr = data.as_ptr().offset(start as int) as *const u32;
220 let val = Int::from_be(*ptr);
222 let i = (val >> 28u) as uint;
223 let (shift, mask) = SHIFT_MASK_TABLE[i];
225 val: ((val >> shift) & mask) as uint,
226 next: start + (((32 - shift) >> 3) as uint)
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;
237 doc: Doc { data: data, start: elt_size.next, end: end }
241 pub fn maybe_get_doc<'a>(d: Doc<'a>, tg: uint) -> Option<Doc<'a>> {
242 let mut pos = d.start;
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,
255 pub fn get_doc<'a>(d: Doc<'a>, tg: uint) -> Doc<'a> {
256 match maybe_get_doc(d, tg) {
259 error!("failed to find block with tag {}", tg);
265 pub fn docs<F>(d: Doc, mut it: F) -> bool where
266 F: FnMut(uint, Doc) -> bool,
268 let mut pos = d.start;
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) {
281 pub fn tagged_docs<F>(d: Doc, tg: uint, mut it: F) -> bool where
282 F: FnMut(Doc) -> bool,
284 let mut pos = d.start;
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,
300 pub fn with_doc_data<T, F>(d: Doc, f: F) -> T where
301 F: FnOnce(&[u8]) -> T,
303 f(d.data[d.start..d.end])
307 pub fn doc_as_u8(d: Doc) -> u8 {
308 assert_eq!(d.end, d.start + 1u);
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
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
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)
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 }
332 pub struct Decoder<'a> {
337 impl<'doc> Decoder<'doc> {
338 pub fn new(d: Doc<'doc>) -> Decoder<'doc> {
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));
350 if r_tag == (EsLabel as uint) {
351 self.pos = r_doc.end;
352 let str = r_doc.as_str_slice();
354 return Err(Expected(format!("Expected label {} but \
355 found {}", lbl, str)));
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 \
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={}-{}",
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)));
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)));
386 self.pos = r_doc.end;
390 fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T> where
391 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
393 let d = try!(self.next_doc(exp_tag));
394 let old_parent = self.parent;
395 let old_pos = self.pos;
398 let r = try!(f(self));
399 self.parent = old_parent;
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);
410 pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R> where
411 F: FnOnce(&mut Decoder, Doc) -> DecodeResult<R>,
413 let doc = try!(self.next_doc(EsOpaque));
415 let (old_parent, old_pos) = (self.parent, self.pos);
417 self.pos = doc.start;
419 let result = try!(op(self, doc));
421 self.parent = old_parent;
428 impl<'doc> serialize::Decoder<Error> for Decoder<'doc> {
429 fn read_nil(&mut self) -> DecodeResult<()> { Ok(()) }
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))
444 fn read_i64(&mut self) -> DecodeResult<i64> {
445 Ok(doc_as_u64(try!(self.next_doc(EsI64))) as i64)
447 fn read_i32(&mut self) -> DecodeResult<i32> {
448 Ok(doc_as_u32(try!(self.next_doc(EsI32))) as i32)
450 fn read_i16(&mut self) -> DecodeResult<i16> {
451 Ok(doc_as_u16(try!(self.next_doc(EsI16))) as i16)
453 fn read_i8 (&mut self) -> DecodeResult<i8> {
454 Ok(doc_as_u8(try!(self.next_doc(EsI8 ))) as i8)
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))
466 fn read_bool(&mut self) -> DecodeResult<bool> {
467 Ok(doc_as_u8(try!(self.next_doc(EsBool))) != 0)
470 fn read_f64(&mut self) -> DecodeResult<f64> {
471 let bits = doc_as_u64(try!(self.next_doc(EsF64)));
472 Ok(unsafe { transmute(bits) })
474 fn read_f32(&mut self) -> DecodeResult<f32> {
475 let bits = doc_as_u32(try!(self.next_doc(EsF32)));
476 Ok(unsafe { transmute(bits) })
478 fn read_char(&mut self) -> DecodeResult<char> {
479 Ok(char::from_u32(doc_as_u32(try!(self.next_doc(EsChar)))).unwrap())
481 fn read_str(&mut self) -> DecodeResult<String> {
482 Ok(try!(self.next_doc(EsStr)).as_str())
486 fn read_enum<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T> where
487 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
489 debug!("read_enum({})", name);
490 try!(self._check_label(name));
492 let doc = try!(self.next_doc(EsEnum));
494 let (old_parent, old_pos) = (self.parent, self.pos);
496 self.pos = self.parent.start;
498 let result = try!(f(self));
500 self.parent = old_parent;
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>,
509 debug!("read_enum_variant()");
510 let idx = try!(self._next_uint(EsEnumVid));
511 debug!(" idx={}", idx);
513 let doc = try!(self.next_doc(EsEnumBody));
515 let (old_parent, old_pos) = (self.parent, self.pos);
517 self.pos = self.parent.start;
519 let result = try!(f(self, idx));
521 self.parent = old_parent;
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>,
529 debug!("read_enum_variant_arg(idx={})", idx);
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>,
537 debug!("read_enum_struct_variant()");
538 let idx = try!(self._next_uint(EsEnumVid));
539 debug!(" idx={}", idx);
541 let doc = try!(self.next_doc(EsEnumBody));
543 let (old_parent, old_pos) = (self.parent, self.pos);
545 self.pos = self.parent.start;
547 let result = try!(f(self, idx));
549 self.parent = old_parent;
554 fn read_enum_struct_variant_field<T, F>(&mut self,
558 -> DecodeResult<T> where
559 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
561 debug!("read_enum_struct_variant_arg(name={}, idx={})", name, idx);
565 fn read_struct<T, F>(&mut self, name: &str, _: uint, f: F) -> DecodeResult<T> where
566 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
568 debug!("read_struct(name={})", name);
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>,
575 debug!("read_struct_field(name={}, idx={})", name, idx);
576 try!(self._check_label(name));
580 fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
581 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
583 debug!("read_tuple()");
584 self.read_seq(move |d, len| {
585 if len == tuple_len {
588 Err(Expected(format!("Expected tuple of length `{}`, \
589 found tuple of length `{}`", tuple_len, len)))
594 fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
595 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
597 debug!("read_tuple_arg(idx={})", idx);
598 self.read_seq_elt(idx, f)
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>,
604 debug!("read_tuple_struct(name={})", name);
605 self.read_tuple(len, f)
608 fn read_tuple_struct_arg<T, F>(&mut self,
611 -> DecodeResult<T> where
612 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
614 debug!("read_tuple_struct_arg(idx={})", idx);
615 self.read_tuple_arg(idx, f)
618 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
619 F: FnMut(&mut Decoder<'doc>, bool) -> DecodeResult<T>,
621 debug!("read_option()");
622 self.read_enum("Option", move |this| {
623 this.read_enum_variant(&["None", "Some"], move |this, idx| {
628 Err(Expected(format!("Expected None or Some")))
635 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
636 F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
638 debug!("read_seq()");
639 self.push_doc(EsVec, move |d| {
640 let len = try!(d._next_uint(EsVecLen));
641 debug!(" len={}", len);
646 fn read_seq_elt<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
647 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
649 debug!("read_seq_elt(idx={})", idx);
650 self.push_doc(EsVecElt, f)
653 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
654 F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
656 debug!("read_map()");
657 self.push_doc(EsMap, move |d| {
658 let len = try!(d._next_uint(EsMapLen));
659 debug!(" len={}", len);
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>,
667 debug!("read_map_elt_key(idx={})", idx);
668 self.push_doc(EsMapKey, f)
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>,
674 debug!("read_map_elt_val(idx={})", idx);
675 self.push_doc(EsMapVal, f)
678 fn error(&mut self, err: &str) -> Error {
679 ApplicationError(err.to_string())
684 impl<'doc> serialize::Decoder for Decoder<'doc> {
686 fn read_nil(&mut self) -> DecodeResult<()> { Ok(()) }
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))
701 fn read_i64(&mut self) -> DecodeResult<i64> {
702 Ok(doc_as_u64(try!(self.next_doc(EsI64))) as i64)
704 fn read_i32(&mut self) -> DecodeResult<i32> {
705 Ok(doc_as_u32(try!(self.next_doc(EsI32))) as i32)
707 fn read_i16(&mut self) -> DecodeResult<i16> {
708 Ok(doc_as_u16(try!(self.next_doc(EsI16))) as i16)
710 fn read_i8 (&mut self) -> DecodeResult<i8> {
711 Ok(doc_as_u8(try!(self.next_doc(EsI8 ))) as i8)
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))
723 fn read_bool(&mut self) -> DecodeResult<bool> {
724 Ok(doc_as_u8(try!(self.next_doc(EsBool))) != 0)
727 fn read_f64(&mut self) -> DecodeResult<f64> {
728 let bits = doc_as_u64(try!(self.next_doc(EsF64)));
729 Ok(unsafe { transmute(bits) })
731 fn read_f32(&mut self) -> DecodeResult<f32> {
732 let bits = doc_as_u32(try!(self.next_doc(EsF32)));
733 Ok(unsafe { transmute(bits) })
735 fn read_char(&mut self) -> DecodeResult<char> {
736 Ok(char::from_u32(doc_as_u32(try!(self.next_doc(EsChar)))).unwrap())
738 fn read_str(&mut self) -> DecodeResult<String> {
739 Ok(try!(self.next_doc(EsStr)).as_str())
743 fn read_enum<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T> where
744 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
746 debug!("read_enum({})", name);
747 try!(self._check_label(name));
749 let doc = try!(self.next_doc(EsEnum));
751 let (old_parent, old_pos) = (self.parent, self.pos);
753 self.pos = self.parent.start;
755 let result = try!(f(self));
757 self.parent = old_parent;
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>,
766 debug!("read_enum_variant()");
767 let idx = try!(self._next_uint(EsEnumVid));
768 debug!(" idx={}", idx);
770 let doc = try!(self.next_doc(EsEnumBody));
772 let (old_parent, old_pos) = (self.parent, self.pos);
774 self.pos = self.parent.start;
776 let result = try!(f(self, idx));
778 self.parent = old_parent;
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>,
786 debug!("read_enum_variant_arg(idx={})", idx);
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>,
794 debug!("read_enum_struct_variant()");
795 let idx = try!(self._next_uint(EsEnumVid));
796 debug!(" idx={}", idx);
798 let doc = try!(self.next_doc(EsEnumBody));
800 let (old_parent, old_pos) = (self.parent, self.pos);
802 self.pos = self.parent.start;
804 let result = try!(f(self, idx));
806 self.parent = old_parent;
811 fn read_enum_struct_variant_field<T, F>(&mut self,
815 -> DecodeResult<T> where
816 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
818 debug!("read_enum_struct_variant_arg(name={}, idx={})", name, idx);
822 fn read_struct<T, F>(&mut self, name: &str, _: uint, f: F) -> DecodeResult<T> where
823 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
825 debug!("read_struct(name={})", name);
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>,
832 debug!("read_struct_field(name={}, idx={})", name, idx);
833 try!(self._check_label(name));
837 fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
838 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
840 debug!("read_tuple()");
841 self.read_seq(move |d, len| {
842 if len == tuple_len {
845 Err(Expected(format!("Expected tuple of length `{}`, \
846 found tuple of length `{}`", tuple_len, len)))
851 fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
852 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
854 debug!("read_tuple_arg(idx={})", idx);
855 self.read_seq_elt(idx, f)
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>,
861 debug!("read_tuple_struct(name={})", name);
862 self.read_tuple(len, f)
865 fn read_tuple_struct_arg<T, F>(&mut self,
868 -> DecodeResult<T> where
869 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
871 debug!("read_tuple_struct_arg(idx={})", idx);
872 self.read_tuple_arg(idx, f)
875 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
876 F: FnMut(&mut Decoder<'doc>, bool) -> DecodeResult<T>,
878 debug!("read_option()");
879 self.read_enum("Option", move |this| {
880 this.read_enum_variant(&["None", "Some"], move |this, idx| {
885 Err(Expected(format!("Expected None or Some")))
892 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
893 F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
895 debug!("read_seq()");
896 self.push_doc(EsVec, move |d| {
897 let len = try!(d._next_uint(EsVecLen));
898 debug!(" len={}", len);
903 fn read_seq_elt<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
904 F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
906 debug!("read_seq_elt(idx={})", idx);
907 self.push_doc(EsVecElt, f)
910 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
911 F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
913 debug!("read_map()");
914 self.push_doc(EsMap, move |d| {
915 let len = try!(d._next_uint(EsMapLen));
916 debug!(" len={}", len);
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>,
924 debug!("read_map_elt_key(idx={})", idx);
925 self.push_doc(EsMapKey, f)
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>,
931 debug!("read_map_elt_val(idx={})", idx);
932 self.push_doc(EsMapVal, f)
935 fn error(&mut self, err: &str) -> Error {
936 ApplicationError(err.to_string())
942 use std::clone::Clone;
943 use std::io::extensions::u64_to_be_bytes;
944 use std::io::{Writer, Seek};
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 };
956 pub type EncodeResult = io::IoResult<()>;
959 pub struct Encoder<'a, W:'a> {
960 pub writer: &'a mut W,
961 size_positions: Vec<uint>,
964 fn write_sized_vuint<W: Writer>(w: &mut W, n: uint, size: uint) -> EncodeResult {
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,
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,
975 detail: Some(format!("{}", n))
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); }
986 kind: io::OtherIoError,
988 detail: Some(format!("{}", n))
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> {
997 size_positions: vec!(),
1001 /// FIXME(pcwalton): Workaround for badness in trans. DO NOT USE ME.
1002 pub unsafe fn unsafe_clone(&self) -> Encoder<'a, W> {
1004 writer: mem::transmute_copy(&self.writer),
1005 size_positions: self.size_positions.clone(),
1009 pub fn start_tag(&mut self, tag_id: uint) -> EncodeResult {
1010 debug!("Start tag {}", tag_id);
1012 // Write the enum ID:
1013 try!(write_vuint(self.writer, tag_id));
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)
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));
1029 debug!("End tag (size = {})", size);
1033 pub fn wr_tag<F>(&mut self, tag_id: uint, blk: F) -> EncodeResult where
1034 F: FnOnce() -> EncodeResult,
1036 try!(self.start_tag(tag_id));
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)
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)
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)
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)
1065 pub fn wr_tagged_u8(&mut self, tag_id: uint, v: u8) -> EncodeResult {
1066 self.wr_tagged_bytes(tag_id, &[v])
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)
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)
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)
1087 pub fn wr_tagged_i8(&mut self, tag_id: uint, v: i8) -> EncodeResult {
1088 self.wr_tagged_bytes(tag_id, &[v as u8])
1091 pub fn wr_tagged_str(&mut self, tag_id: uint, v: &str) -> EncodeResult {
1092 self.wr_tagged_bytes(tag_id, v.as_bytes())
1095 pub fn wr_bytes(&mut self, b: &[u8]) -> EncodeResult {
1096 debug!("Write {} bytes", b.len());
1097 self.writer.write(b)
1100 pub fn wr_str(&mut self, s: &str) -> EncodeResult {
1101 debug!("Write str: {}", s);
1102 self.writer.write(s.as_bytes())
1106 // FIXME (#2743): optionally perform "relaxations" on end_tag to more
1107 // efficiently encode sizes; this is a fixed point iteration
1109 // Set to true to generate more debugging in EBML code.
1110 // Totally lame approach.
1111 static DEBUG: bool = true;
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)
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) }
1131 pub fn emit_opaque<F>(&mut self, f: F) -> EncodeResult where
1132 F: FnOnce(&mut Encoder<W>) -> EncodeResult,
1134 try!(self.start_tag(EsOpaque as uint));
1141 impl<'a, W: Writer + Seek> serialize::Encoder<io::IoError> for Encoder<'a, W> {
1143 fn emit_nil(&mut self) -> EncodeResult {
1147 fn emit_uint(&mut self, v: uint) -> EncodeResult {
1148 self.wr_tagged_u64(EsUint as uint, v as u64)
1150 fn emit_u64(&mut self, v: u64) -> EncodeResult {
1151 self.wr_tagged_u64(EsU64 as uint, v)
1153 fn emit_u32(&mut self, v: u32) -> EncodeResult {
1154 self.wr_tagged_u32(EsU32 as uint, v)
1156 fn emit_u16(&mut self, v: u16) -> EncodeResult {
1157 self.wr_tagged_u16(EsU16 as uint, v)
1159 fn emit_u8(&mut self, v: u8) -> EncodeResult {
1160 self.wr_tagged_u8(EsU8 as uint, v)
1163 fn emit_int(&mut self, v: int) -> EncodeResult {
1164 self.wr_tagged_i64(EsInt as uint, v as i64)
1166 fn emit_i64(&mut self, v: i64) -> EncodeResult {
1167 self.wr_tagged_i64(EsI64 as uint, v)
1169 fn emit_i32(&mut self, v: i32) -> EncodeResult {
1170 self.wr_tagged_i32(EsI32 as uint, v)
1172 fn emit_i16(&mut self, v: i16) -> EncodeResult {
1173 self.wr_tagged_i16(EsI16 as uint, v)
1175 fn emit_i8(&mut self, v: i8) -> EncodeResult {
1176 self.wr_tagged_i8(EsI8 as uint, v)
1179 fn emit_bool(&mut self, v: bool) -> EncodeResult {
1180 self.wr_tagged_u8(EsBool as uint, v as u8)
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)
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)
1191 fn emit_char(&mut self, v: char) -> EncodeResult {
1192 self.wr_tagged_u32(EsChar as uint, v as u32)
1195 fn emit_str(&mut self, v: &str) -> EncodeResult {
1196 self.wr_tagged_str(EsStr as uint, v)
1199 fn emit_enum<F>(&mut self, name: &str, f: F) -> EncodeResult where
1200 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1202 try!(self._emit_label(name));
1203 try!(self.start_tag(EsEnum as uint));
1208 fn emit_enum_variant<F>(&mut self,
1212 f: F) -> EncodeResult where
1213 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1215 try!(self._emit_tagged_uint(EsEnumVid, v_id));
1216 try!(self.start_tag(EsEnumBody as uint));
1221 fn emit_enum_variant_arg<F>(&mut self, _: uint, f: F) -> EncodeResult where
1222 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1227 fn emit_enum_struct_variant<F>(&mut self,
1231 f: F) -> EncodeResult where
1232 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1234 self.emit_enum_variant(v_name, v_id, cnt, f)
1237 fn emit_enum_struct_variant_field<F>(&mut self,
1240 f: F) -> EncodeResult where
1241 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1243 self.emit_enum_variant_arg(idx, f)
1246 fn emit_struct<F>(&mut self, _: &str, _len: uint, f: F) -> EncodeResult where
1247 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1252 fn emit_struct_field<F>(&mut self, name: &str, _: uint, f: F) -> EncodeResult where
1253 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1255 try!(self._emit_label(name));
1259 fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
1260 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1262 self.emit_seq(len, f)
1264 fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
1265 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1267 self.emit_seq_elt(idx, f)
1270 fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
1271 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1273 self.emit_seq(len, f)
1275 fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
1276 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1278 self.emit_seq_elt(idx, f)
1281 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
1282 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1284 self.emit_enum("Option", f)
1286 fn emit_option_none(&mut self) -> EncodeResult {
1287 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
1289 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
1290 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1293 self.emit_enum_variant("Some", 1, 1, f)
1296 fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
1297 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1300 try!(self.start_tag(EsVec as uint));
1301 try!(self._emit_tagged_uint(EsVecLen, len));
1306 fn emit_seq_elt<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
1307 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1310 try!(self.start_tag(EsVecElt as uint));
1315 fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
1316 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1319 try!(self.start_tag(EsMap as uint));
1320 try!(self._emit_tagged_uint(EsMapLen, len));
1325 fn emit_map_elt_key<F>(&mut self, _idx: uint, mut f: F) -> EncodeResult where
1326 F: FnMut(&mut Encoder<'a, W>) -> EncodeResult,
1329 try!(self.start_tag(EsMapKey as uint));
1334 fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
1335 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1337 try!(self.start_tag(EsMapVal as uint));
1343 impl<'a, W: Writer + Seek> serialize::Encoder for Encoder<'a, W> {
1344 type Error = io::IoError;
1346 fn emit_nil(&mut self) -> EncodeResult {
1350 fn emit_uint(&mut self, v: uint) -> EncodeResult {
1351 self.wr_tagged_u64(EsUint as uint, v as u64)
1353 fn emit_u64(&mut self, v: u64) -> EncodeResult {
1354 self.wr_tagged_u64(EsU64 as uint, v)
1356 fn emit_u32(&mut self, v: u32) -> EncodeResult {
1357 self.wr_tagged_u32(EsU32 as uint, v)
1359 fn emit_u16(&mut self, v: u16) -> EncodeResult {
1360 self.wr_tagged_u16(EsU16 as uint, v)
1362 fn emit_u8(&mut self, v: u8) -> EncodeResult {
1363 self.wr_tagged_u8(EsU8 as uint, v)
1366 fn emit_int(&mut self, v: int) -> EncodeResult {
1367 self.wr_tagged_i64(EsInt as uint, v as i64)
1369 fn emit_i64(&mut self, v: i64) -> EncodeResult {
1370 self.wr_tagged_i64(EsI64 as uint, v)
1372 fn emit_i32(&mut self, v: i32) -> EncodeResult {
1373 self.wr_tagged_i32(EsI32 as uint, v)
1375 fn emit_i16(&mut self, v: i16) -> EncodeResult {
1376 self.wr_tagged_i16(EsI16 as uint, v)
1378 fn emit_i8(&mut self, v: i8) -> EncodeResult {
1379 self.wr_tagged_i8(EsI8 as uint, v)
1382 fn emit_bool(&mut self, v: bool) -> EncodeResult {
1383 self.wr_tagged_u8(EsBool as uint, v as u8)
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)
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)
1394 fn emit_char(&mut self, v: char) -> EncodeResult {
1395 self.wr_tagged_u32(EsChar as uint, v as u32)
1398 fn emit_str(&mut self, v: &str) -> EncodeResult {
1399 self.wr_tagged_str(EsStr as uint, v)
1402 fn emit_enum<F>(&mut self, name: &str, f: F) -> EncodeResult where
1403 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1405 try!(self._emit_label(name));
1406 try!(self.start_tag(EsEnum as uint));
1411 fn emit_enum_variant<F>(&mut self,
1415 f: F) -> EncodeResult where
1416 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1418 try!(self._emit_tagged_uint(EsEnumVid, v_id));
1419 try!(self.start_tag(EsEnumBody as uint));
1424 fn emit_enum_variant_arg<F>(&mut self, _: uint, f: F) -> EncodeResult where
1425 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1430 fn emit_enum_struct_variant<F>(&mut self,
1434 f: F) -> EncodeResult where
1435 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1437 self.emit_enum_variant(v_name, v_id, cnt, f)
1440 fn emit_enum_struct_variant_field<F>(&mut self,
1443 f: F) -> EncodeResult where
1444 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1446 self.emit_enum_variant_arg(idx, f)
1449 fn emit_struct<F>(&mut self, _: &str, _len: uint, f: F) -> EncodeResult where
1450 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1455 fn emit_struct_field<F>(&mut self, name: &str, _: uint, f: F) -> EncodeResult where
1456 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1458 try!(self._emit_label(name));
1462 fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
1463 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1465 self.emit_seq(len, f)
1467 fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
1468 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1470 self.emit_seq_elt(idx, f)
1473 fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
1474 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1476 self.emit_seq(len, f)
1478 fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
1479 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1481 self.emit_seq_elt(idx, f)
1484 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
1485 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1487 self.emit_enum("Option", f)
1489 fn emit_option_none(&mut self) -> EncodeResult {
1490 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
1492 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
1493 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1496 self.emit_enum_variant("Some", 1, 1, f)
1499 fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
1500 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1503 try!(self.start_tag(EsVec as uint));
1504 try!(self._emit_tagged_uint(EsVecLen, len));
1509 fn emit_seq_elt<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
1510 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1513 try!(self.start_tag(EsVecElt as uint));
1518 fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
1519 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1522 try!(self.start_tag(EsMap as uint));
1523 try!(self._emit_tagged_uint(EsMapLen, len));
1528 fn emit_map_elt_key<F>(&mut self, _idx: uint, mut f: F) -> EncodeResult where
1529 F: FnMut(&mut Encoder<'a, W>) -> EncodeResult,
1532 try!(self.start_tag(EsMapKey as uint));
1537 fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
1538 F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
1540 try!(self.start_tag(EsMapVal as uint));
1547 // ___________________________________________________________________________
1552 use super::{Doc, reader, writer};
1553 use super::io::SeekableMemWriter;
1555 use serialize::{Encodable, Decodable};
1557 use std::option::Option;
1558 use std::option::Option::{None, Some};
1561 fn test_vuint_at() {
1569 0x10, 0x00, 0x00, 0x00,
1570 0x1f, 0xff, 0xff, 0xff
1573 let mut res: reader::Res;
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);
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);
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);
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);
1609 fn test_option_int() {
1610 fn test_v(v: Option<int>) {
1611 debug!("v == {}", v);
1612 let mut wr = SeekableMemWriter::new();
1614 let mut rbml_w = writer::Encoder::new(&mut wr);
1615 let _ = v.encode(&mut rbml_w);
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);
1632 #![allow(non_snake_case)]
1637 pub fn vuint_at_A_aligned(b: &mut Bencher) {
1638 let data = range(0, 4*100).map(|i| {
1643 }).collect::<Vec<_>>();
1647 while i < data.len() {
1648 sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
1655 pub fn vuint_at_A_unaligned(b: &mut Bencher) {
1656 let data = range(0, 4*100+1).map(|i| {
1661 }).collect::<Vec<_>>();
1665 while i < data.len() {
1666 sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
1673 pub fn vuint_at_D_aligned(b: &mut Bencher) {
1674 let data = range(0, 4*100).map(|i| {
1680 }).collect::<Vec<_>>();
1684 while i < data.len() {
1685 sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
1692 pub fn vuint_at_D_unaligned(b: &mut Bencher) {
1693 let data = range(0, 4*100+1).map(|i| {
1699 }).collect::<Vec<_>>();
1703 while i < data.len() {
1704 sum += reader::vuint_at(data.as_slice(), i).unwrap().val;