1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
use rustc_serialize::json; use rustc_serialize::json::Json; use rustc_serialize::Encodable; use rmp_serialize::encode; use time::Tm; use std::io; use retry; use forwardable::msgpack::Message; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Record<T: Encodable> { tag: String, time: Tm, record: T, } pub enum FluentError { JsonEncodeError(json::EncoderError), MsgpackEncodeError(encode::Error), IOError(io::Error), RetryError(retry::RetryError), } impl From<io::Error> for FluentError { fn from(err: io::Error) -> FluentError { FluentError::IOError(err) } } impl From<encode::Error> for FluentError { fn from(err: encode::Error) -> FluentError { FluentError::MsgpackEncodeError(err) } } impl From<retry::RetryError> for FluentError { fn from(err: retry::RetryError) -> FluentError { FluentError::RetryError(err) } } impl From<json::EncoderError> for FluentError { fn from(err: json::EncoderError) -> FluentError { FluentError::JsonEncodeError(err) } } impl<T: Encodable> Record<T> { pub fn new(tag: String, time: Tm, record: T) -> Record<T> { Record { tag: tag, time: time, record: record, } } pub fn make_forwardable_json(self) -> Result<String, FluentError> { let tag = try!(json::encode(&self.tag)); let record = try!(json::encode(&self.record)); let option = Json::Null; let message = format!("[{},{},{},{}]", tag, self.time.to_timespec().sec, record, option); Ok(message) } pub fn to_message(self) -> Message<T> { Message::new(self.tag, self.time.to_timespec().sec, self.record) } } #[cfg(test)] mod tests { use super::*; use time; use std::collections::HashMap; use rustc_serialize::json; use rustc_serialize::json::Json; #[test] fn test_json_format() { let tag = "fruently".to_string(); let time = time::now(); let mut obj: HashMap<String, String> = HashMap::new(); obj.insert("name".to_string(), "fruently".to_string()); let record = Record::new(tag.clone(), time, obj.clone()); let forwardable_json = record.make_forwardable_json().ok().unwrap(); let json_tag = json::encode(&tag.clone()).ok().unwrap(); let json_obj = json::encode(&obj.clone()).ok().unwrap(); let expected = format!("[{},{},{},{}]", json_tag, time.to_timespec().sec, json_obj, Json::Null); assert_eq!(expected, forwardable_json); } }