jsonrpc/
service_util.rs

1// Copyright 2016 Bruno Medeiros
2//
3// Licensed under the Apache License, Version 2.0 
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>. 
5// This file may not be copied, modified, or distributed
6// except according to those terms.
7
8use std::result::Result;
9use std::io;
10
11pub use util::core::GError;
12pub use util::core::GResult;
13
14
15pub trait MessageReader {
16    fn read_next(&mut self) -> Result<String, GError>;
17}
18
19/// Read a message by reading lines from a BufRead.
20/// This is of use mainly for tests and example code.
21pub struct ReadLineMessageReader<T: io::BufRead>(pub T);
22
23impl<T : io::BufRead> MessageReader for ReadLineMessageReader<T> {
24    fn read_next(&mut self) -> Result<String, GError> {
25        let mut result = String::new();
26        try!(self.0.read_line(&mut result));
27        Ok(result)
28    }
29}
30
31pub trait MessageWriter {
32    fn write_message(&mut self, msg: &str) -> Result<(), GError>;
33}
34
35/// Handle a message simply by writing to a io::Write and appending a newline.
36/// This is of use mainly for tests and example code.
37pub struct WriteLineMessageWriter<T: io::Write>(pub T);
38
39impl<T : io::Write> MessageWriter for WriteLineMessageWriter<T> {
40    fn write_message(&mut self, msg: &str) -> Result<(), GError> {
41        try!(self.0.write_all(msg.as_bytes()));
42        try!(self.0.write_all(&['\n' as u8]));
43        try!(self.0.flush());
44        Ok(())
45    }
46}