From ae4f5469711705e2686fd2be65e4fbc700f93e12 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Sun, 7 Mar 2021 18:38:22 -0500 Subject: separate out the guards from the main structs --- src/input.rs | 56 +++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 19 deletions(-) (limited to 'src/input.rs') diff --git a/src/input.rs b/src/input.rs index fb0d80f..a61afa5 100644 --- a/src/input.rs +++ b/src/input.rs @@ -79,15 +79,39 @@ impl Key { } } -#[derive(Clone)] -pub struct Input { +pub struct RawGuard { termios: nix::sys::termios::Termios, + cleaned_up: bool, +} + +impl RawGuard { + pub fn cleanup(&mut self) { + if self.cleaned_up { + return; + } + self.cleaned_up = true; + let stdin = std::io::stdin().as_raw_fd(); + let _ = nix::sys::termios::tcsetattr( + stdin, + nix::sys::termios::SetArg::TCSANOW, + &self.termios, + ); + } +} + +impl Drop for RawGuard { + fn drop(&mut self) { + self.cleanup(); + } +} + +pub struct Input { buf: Vec, } #[allow(clippy::new_without_default)] impl Input { - pub fn new() -> Self { + pub fn new() -> (Self, RawGuard) { let stdin = std::io::stdin().as_raw_fd(); let termios = nix::sys::termios::tcgetattr(stdin).unwrap(); let mut termios_raw = termios.clone(); @@ -98,8 +122,17 @@ impl Input { &termios_raw, ) .unwrap(); + ( + Self::new_without_raw(), + RawGuard { + termios, + cleaned_up: false, + }, + ) + } + + pub fn new_without_raw() -> Self { Self { - termios, buf: Vec::with_capacity(4096), } } @@ -120,15 +153,6 @@ impl Input { self.real_read_key(false, true) } - pub fn cleanup(&mut self) { - let stdin = std::io::stdin().as_raw_fd(); - let _ = nix::sys::termios::tcsetattr( - stdin, - nix::sys::termios::SetArg::TCSANOW, - &self.termios, - ); - } - fn real_read_key( &mut self, combine: bool, @@ -389,9 +413,3 @@ impl std::io::Read for Input { std::io::stdin().read(buf) } } - -impl Drop for Input { - fn drop(&mut self) { - self.cleanup(); - } -} -- cgit v1.2.3-54-g00ecf