aboutsummaryrefslogtreecommitdiffstats
path: root/src/raw_guard.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/raw_guard.rs')
-rw-r--r--src/raw_guard.rs45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/raw_guard.rs b/src/raw_guard.rs
new file mode 100644
index 0000000..909ba9e
--- /dev/null
+++ b/src/raw_guard.rs
@@ -0,0 +1,45 @@
+use std::os::unix::io::AsRawFd as _;
+
+pub struct RawGuard {
+ termios: nix::sys::termios::Termios,
+ cleaned_up: bool,
+}
+
+impl RawGuard {
+ #[allow(clippy::new_without_default)]
+ pub fn new() -> Self {
+ let stdin = std::io::stdin().as_raw_fd();
+ let termios = nix::sys::termios::tcgetattr(stdin).unwrap();
+ let mut termios_raw = termios.clone();
+ nix::sys::termios::cfmakeraw(&mut termios_raw);
+ nix::sys::termios::tcsetattr(
+ stdin,
+ nix::sys::termios::SetArg::TCSANOW,
+ &termios_raw,
+ )
+ .unwrap();
+ Self {
+ termios,
+ cleaned_up: false,
+ }
+ }
+
+ 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();
+ }
+}