diff --git a/src/line.rs b/src/line.rs new file mode 100644 index 0000000..935200a --- /dev/null +++ b/src/line.rs @@ -0,0 +1,36 @@ +use crate::{error::Error, stdout_handle}; + +use anyhow::Result; +use windows::Win32::System::Console; + +pub struct Line { + chars: Vec, +} + +impl Line { + pub fn new() -> Self { + Self { chars: Vec::new() } + } + + /// adds a character to the end of the line + pub fn append(&mut self, c: char) { + self.chars.push(c) + } + + pub fn clear(&mut self) { + self.chars.clear() + } + + pub fn print(&self) -> Result<()> { + let s: String = self.chars.iter().collect(); + unsafe { + Error::check(Console::WriteConsoleA( + stdout_handle()?, + s.as_bytes(), + None, + None, + ))?; + } + Ok(()) + } +} diff --git a/src/main.rs b/src/main.rs index 8a2dcff..9210c98 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,9 @@ mod error; +mod line; mod log; -use std::ffi::OsString; +use line::Line; use windows::Win32::{Foundation::HANDLE, System::Console}; -use windows::{h, s, w}; use anyhow::{Context, Result}; @@ -186,7 +186,7 @@ fn stdin_handle() -> Result { } } -fn stdout_handle() -> Result { +pub fn stdout_handle() -> Result { unsafe { let handle = Console::GetStdHandle(Console::STD_OUTPUT_HANDLE) .context("unable to get stdin handle")?; @@ -249,7 +249,7 @@ fn main() -> Result<()> { let stdin = stdin_handle()?; let stdout = stdout_handle()?; let mut buf = [Console::INPUT_RECORD::default(); 100]; - let mut line = String::new(); + let mut line = Line::new(); loop { let mut n: u32 = 0; @@ -306,19 +306,14 @@ fn main() -> Result<()> { None, None, ))?; - Error::check(Console::WriteConsoleA( - stdout, - line.as_bytes(), - None, - None, - ))?; + line.print()?; Error::check(Console::WriteConsoleA( stdout, "\r\n".as_bytes(), None, None, ))?; - line = String::new(); + line.clear(); } } else if key_code == 74 && (modifiers & Console::LEFT_CTRL_PRESSED @@ -336,7 +331,7 @@ fn main() -> Result<()> { if !c.is_control() { let mut buf = [0 as u8; 8]; let s = c.encode_utf8(&mut buf); - line.push_str(s); + s.chars().for_each(|c| line.append(c)); Error::check(Console::WriteConsoleW( stdout, s.as_bytes(),