]> git.lizzy.rs Git - rust.git/blob - src/librustuv/signal.rs
fd0b6acb8ae746ecef398637aeae07240f4faceb
[rust.git] / src / librustuv / signal.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use libc::c_int;
12 use std::rt::rtio::{RtioSignal, Callback};
13
14 use homing::{HomingIO, HomeHandle};
15 use super::{UvError, UvHandle};
16 use uvll;
17 use uvio::UvIoFactory;
18
19 pub struct SignalWatcher {
20     handle: *uvll::uv_signal_t,
21     home: HomeHandle,
22
23     cb: Box<Callback:Send>,
24 }
25
26 impl SignalWatcher {
27     pub fn new(io: &mut UvIoFactory, signum: int, cb: Box<Callback:Send>)
28                -> Result<Box<SignalWatcher>, UvError> {
29         let s = box SignalWatcher {
30             handle: UvHandle::alloc(None::<SignalWatcher>, uvll::UV_SIGNAL),
31             home: io.make_handle(),
32             cb: cb,
33         };
34         assert_eq!(unsafe {
35             uvll::uv_signal_init(io.uv_loop(), s.handle)
36         }, 0);
37
38         match unsafe {
39             uvll::uv_signal_start(s.handle, signal_cb, signum as c_int)
40         } {
41             0 => Ok(s.install()),
42             n => Err(UvError(n)),
43         }
44
45     }
46 }
47
48 extern fn signal_cb(handle: *uvll::uv_signal_t, _signum: c_int) {
49     let s: &mut SignalWatcher = unsafe { UvHandle::from_uv_handle(&handle) };
50     let _ = s.cb.call();
51 }
52
53 impl HomingIO for SignalWatcher {
54     fn home<'r>(&'r mut self) -> &'r mut HomeHandle { &mut self.home }
55 }
56
57 impl UvHandle<uvll::uv_signal_t> for SignalWatcher {
58     fn uv_handle(&self) -> *uvll::uv_signal_t { self.handle }
59 }
60
61 impl RtioSignal for SignalWatcher {}
62
63 impl Drop for SignalWatcher {
64     fn drop(&mut self) {
65         let _m = self.fire_homing_missile();
66         self.close();
67     }
68 }