]> git.lizzy.rs Git - rust.git/blob - src/librustuv/timer.rs
auto merge of #13704 : edwardw/rust/doc-hidden, r=alexcrichton
[rust.git] / src / librustuv / timer.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::mem;
13 use std::rt::rtio::RtioTimer;
14 use std::rt::task::BlockedTask;
15
16 use homing::{HomeHandle, HomingIO};
17 use super::{UvHandle, ForbidUnwind, ForbidSwitch, wait_until_woken_after, Loop};
18 use uvio::UvIoFactory;
19 use uvll;
20
21 pub struct TimerWatcher {
22     handle: *uvll::uv_timer_t,
23     home: HomeHandle,
24     action: Option<NextAction>,
25     blocker: Option<BlockedTask>,
26     id: uint, // see comments in timer_cb
27 }
28
29 pub enum NextAction {
30     WakeTask,
31     SendOnce(Sender<()>),
32     SendMany(Sender<()>, uint),
33 }
34
35 impl TimerWatcher {
36     pub fn new(io: &mut UvIoFactory) -> ~TimerWatcher {
37         let handle = io.make_handle();
38         let me = ~TimerWatcher::new_home(&io.loop_, handle);
39         me.install()
40     }
41
42     pub fn new_home(loop_: &Loop, home: HomeHandle) -> TimerWatcher {
43         let handle = UvHandle::alloc(None::<TimerWatcher>, uvll::UV_TIMER);
44         assert_eq!(unsafe { uvll::uv_timer_init(loop_.handle, handle) }, 0);
45         TimerWatcher {
46             handle: handle,
47             action: None,
48             blocker: None,
49             home: home,
50             id: 0,
51         }
52     }
53
54     pub fn start(&mut self, f: uvll::uv_timer_cb, msecs: u64, period: u64) {
55         assert_eq!(unsafe {
56             uvll::uv_timer_start(self.handle, f, msecs, period)
57         }, 0)
58     }
59
60     pub fn stop(&mut self) {
61         assert_eq!(unsafe { uvll::uv_timer_stop(self.handle) }, 0)
62     }
63
64     pub unsafe fn set_data<T>(&mut self, data: *T) {
65         uvll::set_data_for_uv_handle(self.handle, data);
66     }
67 }
68
69 impl HomingIO for TimerWatcher {
70     fn home<'r>(&'r mut self) -> &'r mut HomeHandle { &mut self.home }
71 }
72
73 impl UvHandle<uvll::uv_timer_t> for TimerWatcher {
74     fn uv_handle(&self) -> *uvll::uv_timer_t { self.handle }
75 }
76
77 impl RtioTimer for TimerWatcher {
78     fn sleep(&mut self, msecs: u64) {
79         // As with all of the below functions, we must be extra careful when
80         // destroying the previous action. If the previous action was a channel,
81         // destroying it could invoke a context switch. For these situtations,
82         // we must temporarily un-home ourselves, then destroy the action, and
83         // then re-home again.
84         let missile = self.fire_homing_missile();
85         self.id += 1;
86         self.stop();
87         let _missile = match mem::replace(&mut self.action, None) {
88             None => missile, // no need to do a homing dance
89             Some(action) => {
90                 drop(missile);      // un-home ourself
91                 drop(action);       // destroy the previous action
92                 self.fire_homing_missile()  // re-home ourself
93             }
94         };
95
96         // If the descheduling operation unwinds after the timer has been
97         // started, then we need to call stop on the timer.
98         let _f = ForbidUnwind::new("timer");
99
100         self.action = Some(WakeTask);
101         wait_until_woken_after(&mut self.blocker, &self.uv_loop(), || {
102             self.start(timer_cb, msecs, 0);
103         });
104         self.stop();
105     }
106
107     fn oneshot(&mut self, msecs: u64) -> Receiver<()> {
108         let (tx, rx) = channel();
109
110         // similarly to the destructor, we must drop the previous action outside
111         // of the homing missile
112         let _prev_action = {
113             let _m = self.fire_homing_missile();
114             self.id += 1;
115             self.stop();
116             self.start(timer_cb, msecs, 0);
117             mem::replace(&mut self.action, Some(SendOnce(tx)))
118         };
119
120         return rx;
121     }
122
123     fn period(&mut self, msecs: u64) -> Receiver<()> {
124         let (tx, rx) = channel();
125
126         // similarly to the destructor, we must drop the previous action outside
127         // of the homing missile
128         let _prev_action = {
129             let _m = self.fire_homing_missile();
130             self.id += 1;
131             self.stop();
132             self.start(timer_cb, msecs, msecs);
133             mem::replace(&mut self.action, Some(SendMany(tx, self.id)))
134         };
135
136         return rx;
137     }
138 }
139
140 extern fn timer_cb(handle: *uvll::uv_timer_t, status: c_int) {
141     let _f = ForbidSwitch::new("timer callback can't switch");
142     assert_eq!(status, 0);
143     let timer: &mut TimerWatcher = unsafe { UvHandle::from_uv_handle(&handle) };
144
145     match timer.action.take_unwrap() {
146         WakeTask => {
147             let task = timer.blocker.take_unwrap();
148             let _ = task.wake().map(|t| t.reawaken());
149         }
150         SendOnce(chan) => { let _ = chan.send_opt(()); }
151         SendMany(chan, id) => {
152             let _ = chan.send_opt(());
153
154             // Note that the above operation could have performed some form of
155             // scheduling. This means that the timer may have decided to insert
156             // some other action to happen. This 'id' keeps track of the updates
157             // to the timer, so we only reset the action back to sending on this
158             // channel if the id has remained the same. This is essentially a
159             // bug in that we have mutably aliasable memory, but that's libuv
160             // for you. We're guaranteed to all be running on the same thread,
161             // so there's no need for any synchronization here.
162             if timer.id == id {
163                 timer.action = Some(SendMany(chan, id));
164             }
165         }
166     }
167 }
168
169 impl Drop for TimerWatcher {
170     fn drop(&mut self) {
171         // note that this drop is a little subtle. Dropping a channel which is
172         // held internally may invoke some scheduling operations. We can't take
173         // the channel unless we're on the home scheduler, but once we're on the
174         // home scheduler we should never move. Hence, we take the timer's
175         // action item and then move it outside of the homing block.
176         let _action = {
177             let _m = self.fire_homing_missile();
178             self.stop();
179             self.close();
180             self.action.take()
181         };
182     }
183 }
184
185 #[cfg(test)]
186 mod test {
187     use std::rt::rtio::RtioTimer;
188     use super::super::local_loop;
189     use super::TimerWatcher;
190
191     #[test]
192     fn oneshot() {
193         let mut timer = TimerWatcher::new(local_loop());
194         let port = timer.oneshot(1);
195         port.recv();
196         let port = timer.oneshot(1);
197         port.recv();
198     }
199
200     #[test]
201     fn override() {
202         let mut timer = TimerWatcher::new(local_loop());
203         let oport = timer.oneshot(1);
204         let pport = timer.period(1);
205         timer.sleep(1);
206         assert_eq!(oport.recv_opt(), Err(()));
207         assert_eq!(pport.recv_opt(), Err(()));
208         timer.oneshot(1).recv();
209     }
210
211     #[test]
212     fn period() {
213         let mut timer = TimerWatcher::new(local_loop());
214         let port = timer.period(1);
215         port.recv();
216         port.recv();
217         let port2 = timer.period(1);
218         port2.recv();
219         port2.recv();
220     }
221
222     #[test]
223     fn sleep() {
224         let mut timer = TimerWatcher::new(local_loop());
225         timer.sleep(1);
226         timer.sleep(1);
227     }
228
229     #[test] #[should_fail]
230     fn oneshot_fail() {
231         let mut timer = TimerWatcher::new(local_loop());
232         let _port = timer.oneshot(1);
233         fail!();
234     }
235
236     #[test] #[should_fail]
237     fn period_fail() {
238         let mut timer = TimerWatcher::new(local_loop());
239         let _port = timer.period(1);
240         fail!();
241     }
242
243     #[test] #[should_fail]
244     fn normal_fail() {
245         let _timer = TimerWatcher::new(local_loop());
246         fail!();
247     }
248
249     #[test]
250     fn closing_channel_during_drop_doesnt_kill_everything() {
251         // see issue #10375
252         let mut timer = TimerWatcher::new(local_loop());
253         let timer_port = timer.period(1000);
254
255         spawn(proc() {
256             let _ = timer_port.recv_opt();
257         });
258
259         // when we drop the TimerWatcher we're going to destroy the channel,
260         // which must wake up the task on the other end
261     }
262
263     #[test]
264     fn reset_doesnt_switch_tasks() {
265         // similar test to the one above.
266         let mut timer = TimerWatcher::new(local_loop());
267         let timer_port = timer.period(1000);
268
269         spawn(proc() {
270             let _ = timer_port.recv_opt();
271         });
272
273         drop(timer.oneshot(1));
274     }
275     #[test]
276     fn reset_doesnt_switch_tasks2() {
277         // similar test to the one above.
278         let mut timer = TimerWatcher::new(local_loop());
279         let timer_port = timer.period(1000);
280
281         spawn(proc() {
282             let _ = timer_port.recv_opt();
283         });
284
285         timer.sleep(1);
286     }
287
288     #[test]
289     fn sender_goes_away_oneshot() {
290         let port = {
291             let mut timer = TimerWatcher::new(local_loop());
292             timer.oneshot(1000)
293         };
294         assert_eq!(port.recv_opt(), Err(()));
295     }
296
297     #[test]
298     fn sender_goes_away_period() {
299         let port = {
300             let mut timer = TimerWatcher::new(local_loop());
301             timer.period(1000)
302         };
303         assert_eq!(port.recv_opt(), Err(()));
304     }
305
306     #[test]
307     fn receiver_goes_away_oneshot() {
308         let mut timer1 = TimerWatcher::new(local_loop());
309         drop(timer1.oneshot(1));
310         let mut timer2 = TimerWatcher::new(local_loop());
311         // while sleeping, the prevous timer should fire and not have its
312         // callback do something terrible.
313         timer2.sleep(2);
314     }
315
316     #[test]
317     fn receiver_goes_away_period() {
318         let mut timer1 = TimerWatcher::new(local_loop());
319         drop(timer1.period(1));
320         let mut timer2 = TimerWatcher::new(local_loop());
321         // while sleeping, the prevous timer should fire and not have its
322         // callback do something terrible.
323         timer2.sleep(2);
324     }
325 }