#![forbid(unsafe_code)]
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
use std::cell::Cell;
use std::future::Future;
use std::marker::PhantomData;
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::fmt;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::task::{Context, Poll};
use concurrent_queue::ConcurrentQueue;
type Runnable = async_task::Task<()>;
#[must_use = "tasks get canceled when dropped, use `.detach()` to run them in the background"]
#[derive(Debug)]
pub struct Task<T>(Option<async_task::JoinHandle<T, ()>>);
impl<T> Task<T> {
pub fn detach(mut self) {
self.0.take().unwrap();
}
pub async fn cancel(self) -> Option<T> {
let mut task = self;
let handle = task.0.take().unwrap();
handle.cancel();
handle.await
}
}
impl<T> Drop for Task<T> {
fn drop(&mut self) {
if let Some(handle) = &self.0 {
handle.cancel();
}
}
}
impl<T> Future for Task<T> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match Pin::new(&mut self.0.as_mut().unwrap()).poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(output) => Poll::Ready(output.expect("task has failed")),
}
}
}
#[derive(Debug)]
pub struct LocalExecutor {
queue: Arc<ConcurrentQueue<Runnable>>,
callback: Callback,
_marker: PhantomData<Rc<()>>,
}
impl UnwindSafe for LocalExecutor {}
impl RefUnwindSafe for LocalExecutor {}
impl LocalExecutor {
pub fn new(notify: impl Fn() + Send + Sync + 'static) -> LocalExecutor {
LocalExecutor {
queue: Arc::new(ConcurrentQueue::unbounded()),
callback: Callback::new(notify),
_marker: PhantomData,
}
}
pub fn spawn<T: 'static>(&self, future: impl Future<Output = T> + 'static) -> Task<T> {
let queue = self.queue.clone();
let callback = self.callback.clone();
let schedule = move |runnable| {
queue.push(runnable).unwrap();
callback.call();
};
let (runnable, handle) = async_task::spawn_local(future, schedule, ());
runnable.schedule();
Task(Some(handle))
}
pub fn tick(&self) -> bool {
if let Ok(r) = self.queue.pop() {
r.run();
true
} else {
false
}
}
}
impl Drop for LocalExecutor {
fn drop(&mut self) {
}
}
#[derive(Debug)]
struct Global {
queue: ConcurrentQueue<Runnable>,
shards: RwLock<Vec<Arc<ConcurrentQueue<Runnable>>>>,
notified: AtomicBool,
sleepers: Mutex<Sleepers>,
}
impl Global {
#[inline]
fn notify(&self) {
if !self
.notified
.compare_and_swap(false, true, Ordering::SeqCst)
{
let callback = self.sleepers.lock().unwrap().notify();
if let Some(cb) = callback {
cb.call();
}
}
}
}
#[derive(Debug)]
struct Sleepers {
count: usize,
callbacks: Vec<Callback>,
}
impl Sleepers {
fn insert(&mut self, callback: &Callback) {
self.count += 1;
self.callbacks.push(callback.clone());
}
fn update(&mut self, callback: &Callback) -> bool {
if self.callbacks.iter().all(|cb| cb != callback) {
self.callbacks.push(callback.clone());
true
} else {
false
}
}
fn remove(&mut self, callback: &Callback) {
self.count -= 1;
for i in (0..self.callbacks.len()).rev() {
if &self.callbacks[i] == callback {
self.callbacks.remove(i);
return;
}
}
}
fn is_notified(&self) -> bool {
self.count == 0 || self.count > self.callbacks.len()
}
fn notify(&mut self) -> Option<Callback> {
if self.callbacks.len() == self.count {
self.callbacks.pop()
} else {
None
}
}
}
#[derive(Debug)]
pub struct Executor {
global: Arc<Global>,
}
impl UnwindSafe for Executor {}
impl RefUnwindSafe for Executor {}
impl Executor {
pub fn new() -> Executor {
Executor {
global: Arc::new(Global {
queue: ConcurrentQueue::unbounded(),
shards: RwLock::new(Vec::new()),
notified: AtomicBool::new(true),
sleepers: Mutex::new(Sleepers {
count: 0,
callbacks: Vec::new(),
}),
}),
}
}
pub fn spawn<T: Send + 'static>(
&self,
future: impl Future<Output = T> + Send + 'static,
) -> Task<T> {
let global = self.global.clone();
let schedule = move |runnable| {
global.queue.push(runnable).unwrap();
global.notify();
};
let (runnable, handle) = async_task::spawn(future, schedule, ());
runnable.schedule();
Task(Some(handle))
}
pub fn ticker(&self, notify: impl Fn() + Send + Sync + 'static) -> Ticker {
let ticker = Ticker {
global: Arc::new(self.global.clone()),
shard: Arc::new(ConcurrentQueue::bounded(512)),
callback: Callback::new(notify),
sleeping: Cell::new(false),
ticks: Cell::new(0),
};
self.global
.shards
.write()
.unwrap()
.push(ticker.shard.clone());
ticker
}
}
impl Default for Executor {
fn default() -> Executor {
Executor::new()
}
}
#[derive(Debug)]
pub struct Ticker {
global: Arc<Arc<Global>>,
shard: Arc<ConcurrentQueue<Runnable>>,
callback: Callback,
sleeping: Cell<bool>,
ticks: Cell<usize>,
}
impl UnwindSafe for Ticker {}
impl RefUnwindSafe for Ticker {}
impl Ticker {
fn sleep(&self) -> bool {
let mut sleepers = self.global.sleepers.lock().unwrap();
if self.sleeping.get() {
if !sleepers.update(&self.callback) {
return false;
}
} else {
sleepers.insert(&self.callback);
}
self.global
.notified
.swap(sleepers.is_notified(), Ordering::SeqCst);
self.sleeping.set(true);
true
}
fn wake(&self) -> bool {
if self.sleeping.get() {
let mut sleepers = self.global.sleepers.lock().unwrap();
sleepers.remove(&self.callback);
self.global
.notified
.swap(sleepers.is_notified(), Ordering::SeqCst);
}
self.sleeping.replace(false)
}
pub fn tick(&self) -> bool {
loop {
match self.search() {
None => {
if !self.sleep() {
return false;
}
}
Some(r) => {
self.wake();
self.global.notify();
let ticks = self.ticks.get();
self.ticks.set(ticks.wrapping_add(1));
if ticks % 64 == 0 {
steal(&self.global.queue, &self.shard);
}
r.run();
return true;
}
}
}
}
fn search(&self) -> Option<Runnable> {
if let Ok(r) = self.shard.pop() {
return Some(r);
}
if let Ok(r) = self.global.queue.pop() {
steal(&self.global.queue, &self.shard);
return Some(r);
}
let shards = self.global.shards.read().unwrap();
let n = shards.len();
let start = fastrand::usize(..n);
let iter = shards.iter().chain(shards.iter()).skip(start).take(n);
let iter = iter.filter(|shard| !Arc::ptr_eq(shard, &self.shard));
for shard in iter {
steal(shard, &self.shard);
if let Ok(r) = self.shard.pop() {
return Some(r);
}
}
None
}
}
impl Drop for Ticker {
fn drop(&mut self) {
self.wake();
self.global
.shards
.write()
.unwrap()
.retain(|shard| !Arc::ptr_eq(shard, &self.shard));
while let Ok(r) = self.shard.pop() {
r.schedule();
}
self.global.notify();
}
}
fn steal<T>(src: &ConcurrentQueue<T>, dest: &ConcurrentQueue<T>) {
let mut count = (src.len() + 1) / 2;
if count > 0 {
if let Some(cap) = dest.capacity() {
count = count.min(cap - dest.len());
}
for _ in 0..count {
if let Ok(t) = src.pop() {
assert!(dest.push(t).is_ok());
} else {
break;
}
}
}
}
#[derive(Clone)]
struct Callback(Arc<Box<dyn Fn() + Send + Sync>>);
impl Callback {
fn new(f: impl Fn() + Send + Sync + 'static) -> Callback {
Callback(Arc::new(Box::new(f)))
}
fn call(&self) {
(self.0)();
}
}
impl PartialEq for Callback {
fn eq(&self, other: &Callback) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for Callback {}
impl fmt::Debug for Callback {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("<callback>")
.finish()
}
}