|
| 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 | +// This briefuly tests the capability of `Cell` and `RefCell` to implement the |
| 12 | +// `Encodable` and `Decodable` traits via `#[deriving(Encodable, Decodable)]` |
| 13 | + |
| 14 | +extern crate serialize; |
| 15 | + |
| 16 | +use std::cell::{Cell, RefCell}; |
| 17 | +use std::io::MemWriter; |
| 18 | +use serialize::{Encodable, Decodable}; |
| 19 | +use serialize::ebml; |
| 20 | +use serialize::ebml::writer::Encoder; |
| 21 | +use serialize::ebml::reader::Decoder; |
| 22 | + |
| 23 | +#[deriving(Encodable, Decodable)] |
| 24 | +struct A { |
| 25 | + baz: int |
| 26 | +} |
| 27 | + |
| 28 | +#[deriving(Encodable, Decodable)] |
| 29 | +struct B { |
| 30 | + foo: Cell<bool>, |
| 31 | + bar: RefCell<A>, |
| 32 | +} |
| 33 | + |
| 34 | +fn main() { |
| 35 | + let obj = B { |
| 36 | + foo: Cell::new(true), |
| 37 | + bar: RefCell::new( A { baz: 2 } ) |
| 38 | + }; |
| 39 | + let mut w = MemWriter::new(); |
| 40 | + { |
| 41 | + let mut e = Encoder::new(&mut w); |
| 42 | + match obj.encode(&mut e) { |
| 43 | + Ok(()) => (), |
| 44 | + Err(e) => fail!("Failed to encode: {}", e) |
| 45 | + }; |
| 46 | + } |
| 47 | + let doc = ebml::Doc::new(w.get_ref()); |
| 48 | + let mut dec = Decoder::new(doc); |
| 49 | + let obj2: B = match Decodable::decode(&mut dec) { |
| 50 | + Ok(v) => v, |
| 51 | + Err(e) => fail!("Failed to decode: {}", e) |
| 52 | + }; |
| 53 | + assert!(obj.foo.get() == obj2.foo.get()); |
| 54 | + assert!(obj.bar.borrow().baz == obj2.bar.borrow().baz); |
| 55 | +} |
0 commit comments