use std::cell::{Ref, RefCell}; use std::cmp; use std::future::Future; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use std::sync::Arc; use super::super::main_thread::MainThreadMarker; // Unsafe wrapper type that allows us to use `T` when it's not `Send` from other threads. // `value` **must** only be accessed on the main thread. #[derive(Debug)] pub struct Wrapper { value: Value, handler: fn(&RefCell>, E), sender_data: S, sender_handler: fn(&S, E), } #[derive(Debug)] struct Value { // SAFETY: // This value must not be accessed if not on the main thread. // // - We wrap this in an `Arc` to allow it to be safely cloned without accessing the value. // - The `RefCell` lets us mutably access in the main thread but is safe to drop in any thread // because it has no `Drop` behavior. // - The `Option` lets us safely drop `T` only in the main thread. value: Arc>>, // Prevent's `Send` or `Sync` to be automatically implemented. local: PhantomData<*const ()>, } // SAFETY: See `Self::value`. unsafe impl Send for Value {} // SAFETY: See `Self::value`. unsafe impl Sync for Value {} impl Wrapper { pub fn new>( _: MainThreadMarker, value: V, handler: fn(&RefCell>, E), receiver: impl 'static + FnOnce(Arc>>) -> R, sender_data: S, sender_handler: fn(&S, E), ) -> Self { let value = Arc::new(RefCell::new(Some(value))); wasm_bindgen_futures::spawn_local({ let value = Arc::clone(&value); async move { receiver(Arc::clone(&value)).await; drop(value.borrow_mut().take().unwrap()); } }); Self { value: Value { value, local: PhantomData }, handler, sender_data, sender_handler } } pub fn send(&self, event: E) { if MainThreadMarker::new().is_some() { (self.handler)(&self.value.value, event) } else { (self.sender_handler)(&self.sender_data, event) } } pub fn value(&self, _: MainThreadMarker) -> Ref<'_, V> { Ref::map(self.value.value.borrow(), |value| value.as_ref().unwrap()) } pub fn with_sender_data(&self, f: impl FnOnce(&S) -> T) -> T { f(&self.sender_data) } } impl Clone for Wrapper { fn clone(&self) -> Self { Self { value: Value { value: self.value.value.clone(), local: PhantomData }, handler: self.handler, sender_data: self.sender_data.clone(), sender_handler: self.sender_handler, } } } impl Eq for Wrapper {} impl Hash for Wrapper { fn hash(&self, state: &mut H) { Arc::as_ptr(&self.value.value).hash(state) } } impl Ord for Wrapper { fn cmp(&self, other: &Self) -> cmp::Ordering { Arc::as_ptr(&self.value.value).cmp(&Arc::as_ptr(&other.value.value)) } } impl PartialOrd for Wrapper { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for Wrapper { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.value.value, &other.value.value) } }