use std::cell::RefCell;
use std::collections::HashMap;
use std::future::Future;
use std::hash::Hash;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use std::time::Duration;
use futures_core::Stream;
use crate::runtime::task::{Sleep, sleep};
use crate::widget::{Element, Scope};
use crate::widgets::{Snapshot, future_builder};
type Fetch<T> = Box<dyn FnMut() -> Pin<Box<dyn Future<Output = T>>>>;
type Again<T> = Box<dyn FnMut(&T) -> Option<Duration>>;
pub struct Polled<T> {
fetch: Fetch<T>,
again: Again<T>,
state: Step<T>,
}
enum Step<T> {
Start,
Fetch(Pin<Box<dyn Future<Output = T>>>),
Wait(Sleep),
Done,
}
pub fn polled<T: 'static, F: Future<Output = T> + 'static>(
mut fetch: impl FnMut() -> F + 'static,
again: impl FnMut(&T) -> Option<Duration> + 'static,
) -> Polled<T> {
Polled {
fetch: Box::new(move || Box::pin(fetch())),
again: Box::new(again),
state: Step::Start,
}
}
impl<T> Unpin for Polled<T> {}
impl<T> Stream for Polled<T> {
type Item = T;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<T>> {
let me = &mut *self;
loop {
match &mut me.state {
Step::Start => me.state = Step::Fetch((me.fetch)()),
Step::Fetch(f) => {
let Poll::Ready(v) = f.as_mut().poll(cx) else {
return Poll::Pending;
};
me.state = match (me.again)(&v) {
Some(d) => Step::Wait(sleep(d)),
None => Step::Done,
};
return Poll::Ready(Some(v));
}
Step::Wait(s) => {
if Pin::new(s).poll(cx).is_pending() {
return Poll::Pending;
}
me.state = Step::Start;
}
Step::Done => return Poll::Ready(None),
}
}
}
}
pub struct Latest<T>(Option<T>);
impl<T> Latest<T> {
pub fn get(&self) -> Option<&T> {
self.0.as_ref()
}
}
impl<T> Default for Latest<T> {
fn default() -> Self {
Latest(None)
}
}
impl<T> Extend<T> for Latest<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, items: I) {
if let Some(v) = items.into_iter().last() {
self.0 = Some(v);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
pub use thread::{Blocking, Wanted, blocking};
#[cfg(not(target_arch = "wasm32"))]
mod thread {
use std::any::Any;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
type Outcome<T> = Result<T, Box<dyn Any + Send>>;
struct Shared<T> {
slot: Mutex<(Option<Outcome<T>>, Option<Waker>)>,
wanted: AtomicBool,
}
pub struct Wanted(Arc<dyn Fn() -> bool + Send + Sync>);
impl Wanted {
pub fn get(&self) -> bool {
(self.0)()
}
}
pub struct Blocking<T>(Arc<Shared<T>>);
pub fn blocking<T: Send + 'static>(
work: impl FnOnce(&Wanted) -> T + Send + 'static,
) -> Blocking<T> {
let shared = Arc::new(Shared {
slot: Mutex::new((None, None)),
wanted: AtomicBool::new(true),
});
let s = shared.clone();
std::thread::spawn(move || {
let w = s.clone();
let wanted = Wanted(Arc::new(move || w.wanted.load(Ordering::Acquire)));
let out = catch_unwind(AssertUnwindSafe(|| work(&wanted)));
let waker = {
let mut slot = s.slot.lock().unwrap();
slot.0 = Some(out);
slot.1.take()
};
if let Some(w) = waker {
w.wake();
}
});
Blocking(shared)
}
impl<T> Future for Blocking<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<T> {
let mut slot = self.0.slot.lock().unwrap();
match slot.0.take() {
Some(Ok(v)) => Poll::Ready(v),
Some(Err(panic)) => {
drop(slot);
resume_unwind(panic)
}
None => {
slot.1 = Some(cx.waker().clone());
Poll::Pending
}
}
}
}
impl<T> Drop for Blocking<T> {
fn drop(&mut self) {
self.0.wanted.store(false, Ordering::Release);
}
}
}
pub struct Cache<K, V>(Rc<RefCell<HashMap<K, V>>>);
impl<K, V> Clone for Cache<K, V> {
fn clone(&self) -> Self {
Cache(self.0.clone())
}
}
impl<K, V> Default for Cache<K, V> {
fn default() -> Self {
Cache(Rc::default())
}
}
impl<K: Hash + Eq, V: Clone> Cache<K, V> {
pub fn new() -> Self {
Self::default()
}
pub fn get(&self, key: &K) -> Option<V> {
self.0.borrow().get(key).cloned()
}
pub fn insert(&self, key: K, value: V) {
self.0.borrow_mut().insert(key, value);
}
pub fn remove(&self, key: &K) {
self.0.borrow_mut().remove(key);
}
pub fn clear(&self) {
self.0.borrow_mut().clear();
}
}
pub fn cached<K, V, F, E>(
cache: &Cache<K, V>,
key: K,
fetch: impl FnOnce(Scope) -> F + 'static,
build: impl Fn(Option<&V>) -> E + 'static,
) -> Element
where
K: Hash + Eq + Clone + 'static,
V: Clone + 'static,
F: Future<Output = Option<V>> + 'static,
E: Into<Element>,
{
if let Some(v) = cache.get(&key) {
return build(Some(&v)).into();
}
let store = cache.clone();
let k = key.clone();
let fetch = move |scope: Scope| {
let f = fetch(scope);
async move {
let v = f.await;
if let Some(v) = &v {
store.insert(k, v.clone());
}
v
}
};
future_builder(key, fetch, move |s: &Snapshot<Option<Option<V>>>| {
build(s.data.as_ref().and_then(Option::as_ref))
})
.into()
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use std::sync::mpsc::channel;
use super::*;
#[test]
fn dropping_blocking_work_marks_it_unwanted() {
let (go, wait) = channel();
let (tell, seen) = channel();
let f = blocking(move |w| {
tell.send(w.get()).unwrap();
wait.recv().unwrap();
tell.send(w.get()).unwrap();
});
assert!(seen.recv().unwrap(), "wanted while awaited");
drop(f);
go.send(()).unwrap();
assert!(!seen.recv().unwrap(), "unwanted once dropped");
}
#[test]
fn latest_keeps_the_newest_item() {
let mut l = Latest::default();
l.extend([1, 2]);
l.extend([3]);
assert_eq!(l.get(), Some(&3));
}
}