rust/src/libnative/io/timer_win32.rs
Alex Crichton 545d4718c8 std: Make std::comm return types consistent
There are currently a number of return values from the std::comm methods, not
all of which are necessarily completely expressive:

  Sender::try_send(t: T) -> bool
    This method currently doesn't transmit back the data `t` if the send fails
    due to the other end having disconnected. Additionally, this shares the name
    of the synchronous try_send method, but it differs in semantics in that it
    only has one failure case, not two (the buffer can never be full).

  SyncSender::try_send(t: T) -> TrySendResult<T>
    This method accurately conveys all possible information, but it uses a
    custom type to the std::comm module with no convenience methods on it.
    Additionally, if you want to inspect the result you're forced to import
    something from `std::comm`.

  SyncSender::send_opt(t: T) -> Option<T>
    This method uses Some(T) as an "error value" and None as a "success value",
    but almost all other uses of Option<T> have Some/None the other way

  Receiver::try_recv(t: T) -> TryRecvResult<T>
    Similarly to the synchronous try_send, this custom return type is lacking in
    terms of usability (no convenience methods).

With this number of drawbacks in mind, I believed it was time to re-work the
return types of these methods. The new API for the comm module is:

  Sender::send(t: T) -> ()
  Sender::send_opt(t: T) -> Result<(), T>
  SyncSender::send(t: T) -> ()
  SyncSender::send_opt(t: T) -> Result<(), T>
  SyncSender::try_send(t: T) -> Result<(), TrySendError<T>>
  Receiver::recv() -> T
  Receiver::recv_opt() -> Result<T, ()>
  Receiver::try_recv() -> Result<T, TryRecvError>

The notable changes made are:

* Sender::try_send => Sender::send_opt. This renaming brings the semantics in
  line with the SyncSender::send_opt method. An asychronous send only has one
  failure case, unlike the synchronous try_send method which has two failure
  cases (full/disconnected).

* Sender::send_opt returns the data back to the caller if the send is guaranteed
  to fail. This method previously returned `bool`, but then it was unable to
  retrieve the data if the data was guaranteed to fail to send. There is still a
  race such that when `Ok(())` is returned the data could still fail to be
  received, but that's inherent to an asynchronous channel.

* Result is now the basis of all return values. This not only adds lots of
  convenience methods to all return values for free, but it also means that you
  can inspect the return values with no extra imports (Ok/Err are in the
  prelude). Additionally, it's now self documenting when something failed or not
  because the return value has "Err" in the name.

Things I'm a little uneasy about:

* The methods send_opt and recv_opt are not returning options, but rather
  results. I felt more strongly that Option was the wrong return type than the
  _opt prefix was wrong, and I coudn't think of a much better name for these
  methods. One possible way to think about them is to read the _opt suffix as
  "optionally".

* Result<T, ()> is often better expressed as Option<T>. This is only applicable
  to the recv_opt() method, but I thought it would be more consistent for
  everything to return Result rather than one method returning an Option.

Despite my two reasons to feel uneasy, I feel much better about the consistency
in return values at this point, and I think the only real open question is if
there's a better suffix for {send,recv}_opt.

Closes #11527
2014-04-10 21:41:19 -07:00

203 lines
6.5 KiB
Rust

// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Timers based on win32 WaitableTimers
//!
//! This implementation is meant to be used solely on windows. As with other
//! implementations, there is a worker thread which is doing all the waiting on
//! a large number of timers for all active timers in the system. This worker
//! thread uses the select() equivalent, WaitForMultipleObjects. One of the
//! objects being waited on is a signal into the worker thread to notify that
//! the incoming channel should be looked at.
//!
//! Other than that, the implementation is pretty straightforward in terms of
//! the other two implementations of timers with nothing *that* new showing up.
use libc;
use std::ptr;
use std::rt::rtio;
use io::timer_helper;
use io::IoResult;
pub struct Timer {
obj: libc::HANDLE,
on_worker: bool,
}
pub enum Req {
NewTimer(libc::HANDLE, Sender<()>, bool),
RemoveTimer(libc::HANDLE, Sender<()>),
Shutdown,
}
fn helper(input: libc::HANDLE, messages: Receiver<Req>) {
let mut objs = vec![input];
let mut chans = vec![];
'outer: loop {
let idx = unsafe {
imp::WaitForMultipleObjects(objs.len() as libc::DWORD,
objs.as_ptr(),
0 as libc::BOOL,
libc::INFINITE)
};
if idx == 0 {
loop {
match messages.try_recv() {
Ok(NewTimer(obj, c, one)) => {
objs.push(obj);
chans.push((c, one));
}
Ok(RemoveTimer(obj, c)) => {
c.send(());
match objs.iter().position(|&o| o == obj) {
Some(i) => {
drop(objs.remove(i));
drop(chans.remove(i - 1));
}
None => {}
}
}
Ok(Shutdown) => {
assert_eq!(objs.len(), 1);
assert_eq!(chans.len(), 0);
break 'outer;
}
_ => break
}
}
} else {
let remove = {
match chans.get(idx as uint - 1) {
&(ref c, oneshot) => c.send_opt(()).is_err() || oneshot
}
};
if remove {
drop(objs.remove(idx as uint));
drop(chans.remove(idx as uint - 1));
}
}
}
}
impl Timer {
pub fn new() -> IoResult<Timer> {
timer_helper::boot(helper);
let obj = unsafe {
imp::CreateWaitableTimerA(ptr::mut_null(), 0, ptr::null())
};
if obj.is_null() {
Err(super::last_error())
} else {
Ok(Timer { obj: obj, on_worker: false, })
}
}
pub fn sleep(ms: u64) {
use std::rt::rtio::RtioTimer;
let mut t = Timer::new().ok().expect("must allocate a timer!");
t.sleep(ms);
}
fn remove(&mut self) {
if !self.on_worker { return }
let (tx, rx) = channel();
timer_helper::send(RemoveTimer(self.obj, tx));
rx.recv();
self.on_worker = false;
}
}
impl rtio::RtioTimer for Timer {
fn sleep(&mut self, msecs: u64) {
self.remove();
// there are 10^6 nanoseconds in a millisecond, and the parameter is in
// 100ns intervals, so we multiply by 10^4.
let due = -(msecs * 10000) as libc::LARGE_INTEGER;
assert_eq!(unsafe {
imp::SetWaitableTimer(self.obj, &due, 0, ptr::null(),
ptr::mut_null(), 0)
}, 1);
let _ = unsafe { imp::WaitForSingleObject(self.obj, libc::INFINITE) };
}
fn oneshot(&mut self, msecs: u64) -> Receiver<()> {
self.remove();
let (tx, rx) = channel();
// see above for the calculation
let due = -(msecs * 10000) as libc::LARGE_INTEGER;
assert_eq!(unsafe {
imp::SetWaitableTimer(self.obj, &due, 0, ptr::null(),
ptr::mut_null(), 0)
}, 1);
timer_helper::send(NewTimer(self.obj, tx, true));
self.on_worker = true;
return rx;
}
fn period(&mut self, msecs: u64) -> Receiver<()> {
self.remove();
let (tx, rx) = channel();
// see above for the calculation
let due = -(msecs * 10000) as libc::LARGE_INTEGER;
assert_eq!(unsafe {
imp::SetWaitableTimer(self.obj, &due, msecs as libc::LONG,
ptr::null(), ptr::mut_null(), 0)
}, 1);
timer_helper::send(NewTimer(self.obj, tx, false));
self.on_worker = true;
return rx;
}
}
impl Drop for Timer {
fn drop(&mut self) {
self.remove();
assert!(unsafe { libc::CloseHandle(self.obj) != 0 });
}
}
mod imp {
use libc::{LPSECURITY_ATTRIBUTES, BOOL, LPCSTR, HANDLE, LARGE_INTEGER,
LONG, LPVOID, DWORD, c_void};
pub type PTIMERAPCROUTINE = *c_void;
extern "system" {
pub fn CreateWaitableTimerA(lpTimerAttributes: LPSECURITY_ATTRIBUTES,
bManualReset: BOOL,
lpTimerName: LPCSTR) -> HANDLE;
pub fn SetWaitableTimer(hTimer: HANDLE,
pDueTime: *LARGE_INTEGER,
lPeriod: LONG,
pfnCompletionRoutine: PTIMERAPCROUTINE,
lpArgToCompletionRoutine: LPVOID,
fResume: BOOL) -> BOOL;
pub fn WaitForMultipleObjects(nCount: DWORD,
lpHandles: *HANDLE,
bWaitAll: BOOL,
dwMilliseconds: DWORD) -> DWORD;
pub fn WaitForSingleObject(hHandle: HANDLE,
dwMilliseconds: DWORD) -> DWORD;
}
}