#![warn(rust_2018_idioms, missing_debug_implementations)]
mod connection;
mod errors;
pub use connection::Connection;
pub use errors::{ReadError, WriteError};
#[cfg(not(feature = "tokio"))]
mod imp {
use super::*;
use std::io::{BufRead, Write};
pub fn read<R: BufRead, T: serde::de::DeserializeOwned>(mut reader: R) -> Result<T, ReadError> {
let mut buf = String::new();
let num_bytes_read = reader.read_line(&mut buf).map_err(ReadError::Io)?;
if num_bytes_read == 0 {
return Err(ReadError::Eof);
}
Ok(serde_json::from_str(&buf).map_err(ReadError::Deserialize)?)
}
pub fn write<W: Write, T: serde::Serialize>(mut writer: W, t: &T) -> Result<(), WriteError> {
let json = serde_json::to_string(t).map_err(WriteError::Serialize)?;
writer.write_all(json.as_bytes()).map_err(WriteError::Io)?;
writer.write_all(b"\n").map_err(WriteError::Io)?;
Ok(())
}
}
#[cfg(feature = "tokio")]
mod imp {
use super::*;
use tokio::io::{AsyncBufRead as BufRead, AsyncBufReadExt, AsyncWrite as Write, AsyncWriteExt};
pub async fn read<R: BufRead + Unpin, T: serde::de::DeserializeOwned>(
mut reader: R,
) -> Result<T, ReadError> {
let mut buf = String::new();
let num_bytes_read = reader.read_line(&mut buf).await.map_err(ReadError::Io)?;
if num_bytes_read == 0 {
return Err(ReadError::Eof);
}
Ok(serde_json::from_str(&buf).map_err(ReadError::Deserialize)?)
}
pub async fn write<W: Write + Unpin, T: serde::Serialize>(
mut writer: W,
t: &T,
) -> Result<(), WriteError> {
let json = serde_json::to_string(t).map_err(WriteError::Serialize)?;
writer
.write_all(json.as_bytes())
.await
.map_err(WriteError::Io)?;
writer.write_all(b"\n").await.map_err(WriteError::Io)?;
Ok(())
}
}
pub use imp::*;