Debian Codegraph @

third_party/rust/uniffi_core/src/oneshot.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 //! Implements a simple oneshot channel.
6 //!
7 //! We used to use the `oneshot` crate for this, but the dependency was hard to manage
8 //! (https://github.com/mozilla/uniffi-rs/issues/1736)
9 //!
10 //! This implementation is less efficient, but the difference is probably negligible for most
11 //! use-cases involving UniFFI.
12
13 use std::{
14 future::Future,
15 pin::Pin,
16 sync::{Arc, Mutex},
17 task::{Context, Poll, Waker},
18 };
19
20 pub struct Sender<T>(Arc<Mutex<OneshotInner<T>>>);
21 pub struct Receiver<T>(Arc<Mutex<OneshotInner<T>>>);
22
23 struct OneshotInner<T> {
24 value: Option<T>,
25 waker: Option<Waker>,
26 }
27
28 pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
29 let arc = Arc::new(Mutex::new(OneshotInner {
30 value: None,
31 waker: None,
32 }));
33 (Sender(arc.clone()), Receiver(arc))
34 }
35
36 impl<T> Sender<T> {
37 /// Send a value to the receiver
38 pub fn send(self, value: T) {
39 let mut inner = self.0.lock().unwrap();
40 inner.value = Some(value);
41 if let Some(waker) = inner.waker.take() {
42 waker.wake();
43 }
44 }
45
46 /// Convert a Sender into a raw pointer
47 ///
48 /// from_raw must be called with this pointer or else the sender will leak
49 pub fn into_raw(self) -> *const () {
50 Arc::into_raw(self.0) as *const ()
51 }
52
53 /// Convert a raw pointer back to a Sender
54 ///
55 /// # Safety
56 ///
57 /// `raw_ptr` must have come from into_raw(). Once a pointer is passed into `from_raw` it must
58 /// not be used again.
59 pub unsafe fn from_raw(raw_ptr: *const ()) -> Self {
60 Self(Arc::from_raw(raw_ptr as *const Mutex<OneshotInner<T>>))
61 }
62 }
63
64 impl<T> Future for Receiver<T> {
65 type Output = T;
66
67 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
68 let mut inner = self.0.lock().unwrap();
69 match inner.value.take() {
70 Some(v) => Poll::Ready(v),
71 None => {
72 inner.waker = Some(cx.waker().clone());
73 Poll::Pending
74 }
75 }
76 }
77 }