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
use std::ops::{Deref, DerefMut};

use event_listener::PriorityEventListener;
use parking_lot::{Mutex, MutexGuard};

mod event_listener;
mod pv;

/// An async mutex where the lock operation takes a priority.
pub struct PriorityMutex<T> {
    inner: Mutex<T>,
    listen: PriorityEventListener,
}

impl<T> PriorityMutex<T> {
    /// Creates a new priority mutex.
    pub fn new(t: T) -> Self {
        Self {
            inner: Mutex::new(t),
            listen: PriorityEventListener::new(),
        }
    }

    /// Locks the mutex. When the mutex becomes available, lower priorities are woken up first.
    pub async fn lock(&self, priority: u32) -> PriorityMutexGuard<'_, T> {
        let guard = loop {
            if let Some(val) = self.inner.try_lock() {
                break val;
            } else {
                let listener = self.listen.listen(priority);
                if let Some(val) = self.inner.try_lock() {
                    break val;
                }
                listener.wait().await;
            }
        };
        PriorityMutexGuard {
            inner: guard,
            parent: self,
        }
    }
}

pub struct PriorityMutexGuard<'a, T> {
    inner: MutexGuard<'a, T>,
    parent: &'a PriorityMutex<T>,
}

impl<'a, T> Drop for PriorityMutexGuard<'a, T> {
    fn drop(&mut self) {
        self.parent.listen.notify_one();
    }
}

impl<'a, T> Deref for PriorityMutexGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.inner.deref()
    }
}

impl<'a, T> DerefMut for PriorityMutexGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.deref_mut()
    }
}