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
use crate::{
    fib::RootFiber,
    sync::linked_list::{DrainFilterRaw, LinkedList, Node as ListNode},
};
use core::{iter::FusedIterator, pin::Pin};

/// A lock-free list of fibers.
pub struct Chain {
    list: LinkedList<Node<()>>,
}

#[repr(C)]
pub struct Node<F> {
    advance: unsafe fn(*mut ListNode<Node<()>>) -> bool,
    deallocate: unsafe fn(*mut ListNode<Node<()>>),
    fib: F,
}

/// An iterator produced by [`Chain::drain`].
pub struct Drain<'a, F>
where
    F: FnMut(*mut ListNode<Node<()>>) -> bool,
{
    inner: DrainFilterRaw<'a, Node<()>, F>,
}

impl Chain {
    /// Creates an empty fiber chain.
    #[inline]
    pub const fn new() -> Self {
        Self { list: LinkedList::new() }
    }

    /// Adds a fiber first in the chain.
    #[inline]
    pub fn add<F: RootFiber>(&self, fib: F) {
        unsafe { self.list.push_raw(Node::allocate(fib)) };
    }

    /// Returns `true` if the chain is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.list.is_empty()
    }

    /// Returns an iterator that advances each fiber in the chain, returning
    /// completed ones.
    ///
    /// # Examples
    ///
    /// The returned iterator can be simply dropped, it's destructor will drop
    /// all completed fibers:
    ///
    /// ```
    /// use drone_core::fib::Chain;
    ///
    /// let chain = Chain::new();
    /// unsafe {
    ///     drop(chain.drain()); // run the iterator and drop completed fibers
    /// }
    /// ```
    ///
    /// Check if there is at least one active fiber:
    ///
    /// ```
    /// use drone_core::fib::Chain;
    ///
    /// let chain = Chain::new();
    /// let drain = unsafe { chain.drain() };
    /// if drain.is_end() {
    ///     println!("No active fibers to react to this interrupt");
    /// }
    /// ```
    ///
    /// # Safety
    ///
    /// This method must not be called again when the previous iterator is still
    /// alive.
    #[inline]
    pub unsafe fn drain(&self) -> Drain<'_, impl FnMut(*mut ListNode<Node<()>>) -> bool> {
        // This is the only place where nodes are getting removed. This cannot
        // run concurrently because of the safety invariant of this function.
        unsafe { Drain { inner: self.list.drain_filter_raw(Node::filter) } }
    }
}

impl Drop for Chain {
    fn drop(&mut self) {
        unsafe { self.list.drain_filter_raw(|_| true).for_each(Node::delete) };
    }
}

impl Node<()> {
    fn filter(node: *mut ListNode<Self>) -> bool {
        unsafe { ((*node).advance)(node) }
    }

    fn delete(node: *mut ListNode<Self>) {
        unsafe { ((*node).deallocate)(node) }
    }
}

impl<F: RootFiber> Node<F> {
    fn allocate(fib: F) -> *mut ListNode<Node<()>> {
        let node = Node { advance: Self::advance, deallocate: Self::deallocate, fib };
        unsafe { Self::upcast(Box::into_raw(Box::new(ListNode::from(node)))) }
    }

    unsafe fn advance(node: *mut ListNode<Node<()>>) -> bool {
        unsafe { Pin::new_unchecked(&mut (*Self::downcast(node)).fib).advance() }
    }

    unsafe fn deallocate(node: *mut ListNode<Node<()>>) {
        unsafe { Box::from_raw(Self::downcast(node)) };
    }

    unsafe fn upcast(node: *mut ListNode<Self>) -> *mut ListNode<Node<()>> {
        node.cast()
    }

    unsafe fn downcast(node: *mut ListNode<Node<()>>) -> *mut ListNode<Self> {
        node.cast()
    }
}

impl<F> Drain<'_, F>
where
    F: FnMut(*mut ListNode<Node<()>>) -> bool,
{
    /// Returns `true` if there are no fibers left in the chain.
    #[inline]
    pub fn is_end(&self) -> bool {
        self.inner.is_end()
    }
}

impl<F> Iterator for Drain<'_, F>
where
    F: FnMut(*mut ListNode<Node<()>>) -> bool,
{
    type Item = ();

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(Node::delete)
    }
}

impl<F> FusedIterator for Drain<'_, F> where F: FnMut(*mut ListNode<Node<()>>) -> bool {}