Skip to main content

async_selector/selector/
borrowed.rs

1use std::{
2    ops::{Deref, DerefMut},
3    pin::Pin,
4    sync::Arc,
5};
6
7use crate::{
8    list::cursor::{BorrowedNode, BorrowedNodeMut},
9    mpsc,
10    selector::Id,
11    task::Task,
12};
13
14/// An immutable borrow of a task stored in a [`Selector`](crate::selector::Selector).
15pub struct Borrowed<'a, P> {
16    pub(super) node: BorrowedNode<'a, Task<P>>,
17    pub(super) queue: &'a mpsc::Receiver<Task<P>>,
18}
19
20impl<P> Borrowed<'_, P> {
21    /// Manually wakes the task.
22    pub fn wake(&self) {
23        let node = self.node.node().clone();
24        self.queue.send(node);
25    }
26
27    /// Returns the id of this task.
28    pub fn id(&self) -> Id<P> {
29        Id(Arc::downgrade(self.node.node()))
30    }
31}
32
33impl<P> Deref for Borrowed<'_, P> {
34    type Target = P;
35
36    fn deref(&self) -> &Self::Target {
37        self.node.get_protected()
38    }
39}
40
41/// Mutable borrow of a task stored in a [`Selector`](crate::selector::Selector).
42///
43/// **Important:** before modifying tasks stored in the selector, see the wakeups [section](crate::selector::Selector#wakeups).
44pub struct BorrowedMut<'a, P> {
45    pub(super) node: BorrowedNodeMut<'a, Task<P>>,
46    pub(super) queue: &'a mpsc::Receiver<Task<P>>,
47}
48
49impl<P> BorrowedMut<'_, P> {
50    /// Manually wakes the task.
51    pub fn wake(&self) {
52        let node = self.node.node().clone();
53        self.queue.send(node);
54    }
55
56    /// Returns the id of this task.
57    pub fn id(&self) -> Id<P> {
58        Id(Arc::downgrade(self.node.node()))
59    }
60
61    /// Returns a pinned reference to the task.
62    ///
63    /// **Important:** before modifying tasks stored in the selector, see the wakeups [section](crate::selector::Selector#wakeups).
64    pub fn get_mut(&mut self) -> Pin<&mut P> {
65        self.node.get_protected_mut()
66    }
67}
68
69impl<P> Deref for BorrowedMut<'_, P> {
70    type Target = P;
71
72    fn deref(&self) -> &Self::Target {
73        self.node.get_protected()
74    }
75}
76
77impl<P: Unpin> DerefMut for BorrowedMut<'_, P> {
78    fn deref_mut(&mut self) -> &mut Self::Target {
79        self.get_mut().get_mut()
80    }
81}