Skip to main content

quickjs_jit_stdlib/llrt/llrt_utils/
mc_oneshot.rs

1// Vendored from LLRT d9fd873e793c (libs/llrt_utils/src/mc_oneshot.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5
6use std::sync::{
7    atomic::{AtomicBool, Ordering},
8    Arc, RwLock,
9};
10
11use rquickjs::{
12    class::{Trace, Tracer},
13    Value,
14};
15use std::ops::Deref;
16use tokio::sync::Notify;
17
18#[derive(Debug)]
19pub struct Shared<T> {
20    is_sent: AtomicBool,
21    value: RwLock<Option<T>>,
22    notify: Notify,
23}
24
25#[derive(Clone, Debug)]
26pub struct Sender<T: Clone>(Arc<Shared<T>>);
27
28impl<T: Clone> Deref for Sender<T> {
29    type Target = Arc<Shared<T>>;
30    fn deref(&self) -> &Self::Target {
31        &self.0
32    }
33}
34
35impl<'js> Trace<'js> for Sender<Value<'js>> {
36    fn trace<'a>(&self, tracer: Tracer<'a, 'js>) {
37        if let Ok(v) = self.value.read() {
38            if let Some(v) = v.as_ref() {
39                tracer.mark(v)
40            }
41        }
42    }
43}
44
45impl<T: Clone> Sender<T> {
46    pub fn send(&self, value: T) {
47        if !self.is_sent.load(Ordering::Relaxed) {
48            self.value.write().unwrap().replace(value);
49            self.is_sent.store(true, Ordering::Release);
50            self.notify.notify_waiters();
51        }
52    }
53
54    pub fn subscribe(&self) -> Receiver<T> {
55        Receiver(Arc::clone(&self.0))
56    }
57}
58
59#[derive(Clone, Debug)]
60pub struct Receiver<T: Clone>(Arc<Shared<T>>);
61
62impl<T: Clone> Deref for Receiver<T> {
63    type Target = Arc<Shared<T>>;
64    fn deref(&self) -> &Self::Target {
65        &self.0
66    }
67}
68
69impl<T: Clone> Receiver<T> {
70    pub async fn recv(&self) -> T {
71        if !self.is_sent.load(Ordering::Acquire) {
72            self.notify.notified().await;
73        }
74        self.value.read().unwrap().clone().unwrap()
75    }
76}
77
78pub fn channel<T: Clone>() -> (Sender<T>, Receiver<T>) {
79    let shared = Arc::new(Shared {
80        is_sent: AtomicBool::new(false),
81        value: RwLock::new(None),
82        notify: Notify::new(),
83    });
84
85    (Sender(Arc::clone(&shared)), Receiver(shared))
86}
87
88#[cfg(test)]
89mod tests {
90    use tokio::join;
91
92    #[tokio::test]
93    async fn test() {
94        let (tx, rx1) = super::channel::<bool>();
95
96        let rx2 = tx.subscribe();
97        let rx3 = tx.subscribe();
98
99        let a = tokio::spawn(async move {
100            let val = rx1.recv().await; //wait for value to become false
101            assert!(val)
102        });
103
104        let b = tokio::spawn(async move {
105            let val = rx2.recv().await; //wait for value to become false
106            assert!(val)
107        });
108
109        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
110
111        tx.send(true);
112
113        let val = rx3.recv().await;
114        assert!(val);
115
116        let (a, b) = join!(a, b);
117        a.unwrap();
118        b.unwrap();
119    }
120}