|
| 1 | +// Copyright 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 | +extern crate ser = "serialize"; |
| 12 | + |
| 13 | +use serialize = self::ser; |
| 14 | + //necessary for deriving(Encodable) |
| 15 | +use ser::{Encodable, Encoder}; |
| 16 | +use ser::json; |
| 17 | +use ser::ebml::writer; |
| 18 | +use std::io::MemWriter; |
| 19 | +use std::str::from_utf8_owned; |
| 20 | + |
| 21 | +#[deriving(Encodable)] |
| 22 | +struct Foo { |
| 23 | + baz: bool, |
| 24 | +} |
| 25 | + |
| 26 | +#[deriving(Encodable)] |
| 27 | +struct Bar { |
| 28 | + froboz: uint, |
| 29 | +} |
| 30 | + |
| 31 | +enum WireProtocol { |
| 32 | + JSON, |
| 33 | + EBML, |
| 34 | + // ... |
| 35 | +} |
| 36 | + |
| 37 | +fn encode_json<'a, |
| 38 | + T: Encodable<json::Encoder<'a>, |
| 39 | + std::io::IoError>>(val: &T, |
| 40 | + wr: &'a mut MemWriter) { |
| 41 | + let mut encoder = json::Encoder::new(wr); |
| 42 | + val.encode(&mut encoder); |
| 43 | +} |
| 44 | +fn encode_ebml<'a, |
| 45 | + T: Encodable<writer::Encoder<'a, MemWriter>, |
| 46 | + std::io::IoError>>(val: &T, |
| 47 | + wr: &'a mut MemWriter) { |
| 48 | + let mut encoder = writer::Encoder(wr); |
| 49 | + val.encode(&mut encoder); |
| 50 | +} |
| 51 | + |
| 52 | +pub fn main() { |
| 53 | + let target = Foo{baz: false,}; |
| 54 | + let mut wr = MemWriter::new(); |
| 55 | + let proto = JSON; |
| 56 | + match proto { |
| 57 | + JSON => encode_json(&target, &mut wr), |
| 58 | + EBML => encode_ebml(&target, &mut wr) |
| 59 | + } |
| 60 | +} |
0 commit comments