use crate::error::RuChatError;
use std::io::stdin;
use tokio::io::AsyncWriteExt;
pub(crate) struct Io {
stdin: std::io::Stdin,
stdout: tokio::io::Stdout,
}
impl Io {
pub(crate) fn new() -> Self {
Self {
stdin: stdin(),
stdout: tokio::io::stdout(),
}
}
pub(crate) async fn read_line(&mut self, with_prompt: bool) -> Result<String, RuChatError> {
if with_prompt {
self.stdout.write_all(b"\n> ").await?;
self.stdout.flush().await?;
}
let mut input = String::new();
self.stdin.read_line(&mut input)?;
Ok(input.trim_end().to_string())
}
pub(crate) async fn write_line(&mut self, line: &str) -> Result<(), RuChatError> {
self.stdout.write_all(line.as_bytes()).await?;
self.stdout.flush().await?;
Ok(())
}
pub(crate) async fn write(&mut self, s: &str) -> Result<(), RuChatError> {
self.stdout.write_all(s.as_bytes()).await?;
self.stdout.flush().await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{self, AsyncWriteExt};
#[tokio::test]
async fn test_write_line() {
let mut io = Io::new();
let line = "Hello, world!";
let result = io.write_line(line).await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_write() {
let mut io = Io::new();
let text = "Hello, world!";
let result = io.write(text).await;
assert!(result.is_ok());
}
}