1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use crate::common::*;

use ctrlc;

pub struct InterruptHandler {
  blocks: u32,
  interrupted: bool,
}

impl InterruptHandler {
  pub fn install() -> Result<(), ctrlc::Error> {
    ctrlc::set_handler(|| InterruptHandler::instance().interrupt())
  }

  fn instance() -> MutexGuard<'static, InterruptHandler> {
    lazy_static! {
      static ref INSTANCE: Mutex<InterruptHandler> = Mutex::new(InterruptHandler::new());
    }

    match INSTANCE.lock() {
      Ok(guard) => guard,
      Err(poison_error) => die!(
        "{}",
        RuntimeError::Internal {
          message: format!("interrupt handler mutex poisoned: {}", poison_error),
        }
      ),
    }
  }

  fn new() -> InterruptHandler {
    InterruptHandler {
      blocks: 0,
      interrupted: false,
    }
  }

  fn interrupt(&mut self) {
    self.interrupted = true;

    if self.blocks > 0 {
      return;
    }

    Self::exit();
  }

  fn exit() {
    process::exit(130);
  }

  fn block(&mut self) {
    self.blocks += 1;
  }

  fn unblock(&mut self) {
    if self.blocks == 0 {
      die!(
        "{}",
        RuntimeError::Internal {
          message: "attempted to unblock interrupt handler, but handler was not blocked"
            .to_string(),
        }
      );
    }

    self.blocks -= 1;

    if self.interrupted {
      Self::exit();
    }
  }

  pub fn guard<T, F: FnOnce() -> T>(function: F) -> T {
    let _guard = InterruptGuard::new();
    function()
  }
}

pub struct InterruptGuard;

impl InterruptGuard {
  fn new() -> InterruptGuard {
    InterruptHandler::instance().block();
    InterruptGuard
  }
}

impl Drop for InterruptGuard {
  fn drop(&mut self) {
    InterruptHandler::instance().unblock();
  }
}