Created
November 1, 2015 22:28
-
-
Save johshoff/1f4922d0cd693159fe2c to your computer and use it in GitHub Desktop.
encode hashmap as list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate rustc_serialize; | |
use std::collections::HashMap; | |
use rustc_serialize::{Encodable, Encoder}; | |
use rustc_serialize::json; | |
#[derive(RustcEncodable, PartialEq, Eq, Hash, Debug)] | |
struct Point { | |
x: u64, | |
y: u64, | |
} | |
impl Point { | |
fn new(x: u64, y: u64) -> Point { | |
Point { x: x, y: y } | |
} | |
} | |
struct PointRelations { | |
points: HashMap<Point, Point> | |
} | |
impl Encodable for PointRelations { | |
fn encode<E : Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> { | |
encoder.emit_seq(self.points.len()*2, |encoder| { | |
for (i, (key, value)) in self.points.iter().enumerate() { | |
try!(encoder.emit_seq_elt(i, |encoder| { | |
encoder.emit_tuple(2, |encoder| { | |
try!(encoder.emit_tuple_arg(0, |encoder| { key .encode(encoder) })); | |
try!(encoder.emit_tuple_arg(1, |encoder| { value.encode(encoder) })); | |
Ok(()) | |
}) | |
})); | |
} | |
Ok(()) | |
}) | |
} | |
} | |
fn main() { | |
let point_relations = PointRelations { points: { | |
let mut points = HashMap::new(); | |
points.insert(Point::new(3, 4), Point::new(5, 6)); | |
points.insert(Point::new(7, 8), Point::new(9, 0)); | |
points | |
} }; | |
println!("{}", json::encode(&point_relations).unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment