1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#![feature(coerce_unsized)]
#![feature(unsize)]
#![feature(once_cell)]

#![deny(missing_docs)]

//! lofi - Low Overhead FIbers
//!
//! This library provides a low-latency fork-join task executor backed by
//! a custom allocator. See [Executor][Executor] to start.

pub mod state;
mod alloc;
mod noop_waker;
mod unchecked_any;
mod universal_type_id;

pub use universal_type_id::UniversalTypeId;

use std::{
    collections::VecDeque,
    future::Future,
    mem,
    pin::Pin,
    sync::Mutex,
    task::{self, Poll},
};
use alloc::{Chunker, CBox, CArc, CWeak};
use noop_waker::noop_context;

/// Future executor driven by calls to [tick][Executor::tick]().
pub struct Executor {
    spawn_context: SpawnContext,
    tasks: VecDeque<Pin<CBox<dyn Future<Output=()>>>>,
    tasks_temp: Vec<Pin<CBox<dyn Future<Output=()>>>>,
    exclusive_tasks: Vec<Pin<CBox<dyn Future<Output=()>>>>,
}

/// A handle for a running future. Allows awaiting for another future completion.
pub struct JoinHandle<T: Send>(CArc<Mutex<Option<T>>>);

pub(crate) struct SpawnContext {
    alloc: Chunker,
    spawned: Vec<Pin<CBox<dyn Future<Output=()>>>>,
}

/// Yield the current future.
///
/// This is the same as calling `lofi::yield_ticks(1)`.
pub fn yield_now() -> impl Future<Output=()> {
    yield_ticks(1)
}

/// Yield the current future for `count` ticks.
pub fn yield_ticks(count: usize) -> impl Future<Output=()> {
    return Roll(count);

    struct Roll(usize);

    impl Future for Roll {
        type Output = ();

        fn poll(mut self: Pin<&mut Self>, _: &mut task::Context) -> Poll<()> {
            if self.0 == 0 {
                Poll::Ready(())
            } else {
                self.0 -= 1;
                Poll::Pending
            }
        }
    }
}

impl Executor {
    /// Create a new executor.
    pub fn new() -> Self {
        Self {
            spawn_context: SpawnContext {
                alloc: Chunker::new(),
                spawned: Vec::new(),
            },
            tasks: VecDeque::new(),
            tasks_temp: Vec::new(),
            exclusive_tasks: Vec::new(),
        }
    }

    /// Insert a future to be run in this executor.
    pub fn insert<F>(&mut self, future: F)
    where
        F: Future<Output=()> + Send + Sync + 'static
    {
        self.spawn_context.spawn(future);
    }

    /// Advance all futures in the executor.
    ///
    /// `state` parameter will be shared across all executing futures.
    pub fn tick<'a, T>(&mut self, state: &mut T)
    where
        T: 'a + UniversalTypeId + Sync
    {
        use state::{AccessMode, AwaitCondition};

        self.tasks_temp.extend(self.spawn_context.spawned.drain(..));
        self.tasks_temp.extend(self.tasks.drain(..));

        unsafe {
            state::set_broadcast(&mut self.spawn_context, state);
            state::set_access_mode(AccessMode::Shared);
        }

        for mut task in self.tasks_temp.drain(..) {
            let poll_result = task.as_mut().poll(&mut noop_context());
            let await_condition = unsafe { state::read_await_condition() };
            match (poll_result, await_condition) {
                (Poll::Pending, AwaitCondition::NextTick) => self.tasks.push_front(task),
                (Poll::Pending, AwaitCondition::Exclusive) => self.exclusive_tasks.push(task),
                (Poll::Ready(_), _) => mem::drop(task),
            }
        }

        unsafe {
            state::set_access_mode(AccessMode::Exclusive);
        }
        for mut task in self.exclusive_tasks.drain(..) {
            match task.as_mut().poll(&mut noop_context()) {
                Poll::Pending => self.tasks.push_front(task),
                Poll::Ready(_) => mem::drop(task),
            }
        }

        unsafe {
            state::reset_broadcast();
        }

        self.spawn_context.alloc.quiescent_cleanup();
    }
}

impl SpawnContext {
    pub(crate) fn spawn<F>(&mut self, future: F)
    where
        F: Future<Output=()> + Send + Sync + 'static
    {
        let boxed_future = self.alloc.alloc_box(future) as CBox<dyn Future<Output=()>>;
        let task = CBox::pin(boxed_future);
        self.spawned.push(task);
    }

    pub(crate) fn spawn_ret<F, T>(&mut self, future: F) -> JoinHandle<T>
    where
        F: Future<Output=T> + Send + Sync + 'static,
        T: Send + 'static
    {
        let arc = self.alloc.alloc_arc(Mutex::new(None));
        let weak = arc.make_weak();
        let handle = JoinHandle(arc);
        self.spawn(wrap_return(future, weak));
        return handle;

        async fn wrap_return<F, T>(fut: F, return_place: CWeak<Mutex<Option<T>>>)
        where
            F: Future<Output=T>,
            T: Send
        {
            let value = fut.await;
            if let Some(arc) = return_place.upgrade() {
                *arc.lock().unwrap() = Some(value);
            }
        }
    }
}

impl<T: Send + 'static> Future for JoinHandle<T> {
    type Output = T;

    fn poll(self: Pin<&mut Self>, _: &mut task::Context) -> Poll<Self::Output> {
        let value = self.0.lock().unwrap().take();
        match value {
            Some(value) => Poll::Ready(value),
            None => Poll::Pending,
        }
    }
}