Bug 1625286 - Expose dispatch flags to `moz_task`. r=KrisWright

This commit adds a `dispatch_with_options` method to Rust task
runnables, which takes a builder-style `DispatchOptions`
argument controlling how the runnable should be dispatched.
Currently, the only supported option is `may_block`, which
corresponds to `nsIEventTarget::DISPATCH_EVENT_MAY_BLOCK`.

Differential Revision: https://phabricator.services.mozilla.com/D68688

--HG--
extra : moz-landing-system : lando
This commit is contained in:
Lina Cambridge 2020-03-30 19:24:08 +00:00
Родитель be03c17e1d
Коммит 80920e5871
1 изменённых файлов: 49 добавлений и 4 удалений

Просмотреть файл

@ -76,6 +76,45 @@ pub fn create_background_task_queue(
getter_addrefs(|p| unsafe { NS_CreateBackgroundTaskQueue(name.as_ptr(), p) })
}
/// Options to control how task runnables are dispatched.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct DispatchOptions(u32);
impl Default for DispatchOptions {
#[inline]
fn default() -> Self {
DispatchOptions(nsIEventTarget::DISPATCH_NORMAL as u32)
}
}
impl DispatchOptions {
/// Creates a blank set of options. The runnable will be dispatched using
/// the default mode.
#[inline]
pub fn new() -> Self {
DispatchOptions::default()
}
/// Indicates whether or not the dispatched runnable may block its target
/// thread by waiting on I/O. If `true`, the runnable may be dispatched to a
/// dedicated thread pool, leaving the main pool free for CPU-bound tasks.
#[inline]
pub fn may_block(self, may_block: bool) -> DispatchOptions {
const FLAG: u32 = nsIEventTarget::DISPATCH_EVENT_MAY_BLOCK as u32;
if may_block {
DispatchOptions(self.flags() | FLAG)
} else {
DispatchOptions(self.flags() & !FLAG)
}
}
/// Returns the set of bitflags to pass to `DispatchFromScript`.
#[inline]
fn flags(self) -> u32 {
self.0
}
}
/// A task represents an operation that asynchronously executes on a target
/// thread, and returns its result to the original thread.
pub trait Task {
@ -113,11 +152,17 @@ impl TaskRunnable {
}))
}
#[inline]
pub fn dispatch(&self, target_thread: &nsIEventTarget) -> Result<(), nsresult> {
unsafe {
target_thread.DispatchFromScript(self.coerce(), nsIEventTarget::DISPATCH_NORMAL as u32)
}
.to_result()
self.dispatch_with_options(target_thread, DispatchOptions::default())
}
pub fn dispatch_with_options(
&self,
target_thread: &nsIEventTarget,
options: DispatchOptions,
) -> Result<(), nsresult> {
unsafe { target_thread.DispatchFromScript(self.coerce(), options.flags()) }.to_result()
}
xpcom_method!(run => Run());