From 11dc4d104b21b75d63e10e42ea4ee767c7bd5fdf Mon Sep 17 00:00:00 2001 From: sigoden Date: Tue, 7 Mar 2023 11:51:52 +0800 Subject: refactor: optimize ctrl+c/ctrl+d abort handling (#27) --- src/repl/abort.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/repl/abort.rs (limited to 'src/repl/abort.rs') diff --git a/src/repl/abort.rs b/src/repl/abort.rs new file mode 100644 index 0000000..f76abb6 --- /dev/null +++ b/src/repl/abort.rs @@ -0,0 +1,51 @@ +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; + +pub type SharedAbortSignal = Arc; + +pub struct AbortSignal { + ctrlc: AtomicBool, + ctrld: AtomicBool, +} + +impl AbortSignal { + pub fn new() -> SharedAbortSignal { + Arc::new(Self { + ctrlc: AtomicBool::new(false), + ctrld: AtomicBool::new(false), + }) + } + + pub fn aborted(&self) -> bool { + if self.aborted_ctrlc() { + return true; + } + if self.aborted_ctrld() { + return true; + } + false + } + + pub fn aborted_ctrlc(&self) -> bool { + self.ctrlc.load(Ordering::SeqCst) + } + + pub fn aborted_ctrld(&self) -> bool { + self.ctrld.load(Ordering::SeqCst) + } + + pub fn reset(&self) { + self.ctrlc.store(false, Ordering::SeqCst); + self.ctrld.store(false, Ordering::SeqCst); + } + + pub fn set_ctrlc(&self) { + self.ctrlc.store(true, Ordering::SeqCst); + } + + pub fn set_ctrld(&self) { + self.ctrld.store(true, Ordering::SeqCst); + } +} -- cgit v1.2.3