#![doc = include_str!("../README.md")]
#[doc(hidden)]
#[path = "exports.rs"]
pub mod __private;
pub mod context;
use context::{with_current_context, StateContext};
use futures_core::Stream;
use std::{
ops::{Deref, DerefMut},
pin::Pin,
task::Poll,
};
pub trait AsyncComponent {
fn update_component(&mut self);
}
pub trait State {
type Output;
fn update(this: &mut Self) -> Option<Self::Output>;
}
#[derive(Debug)]
pub struct StateCell<T> {
changed: bool,
inner: T,
}
impl<T> StateCell<T> {
pub fn new(inner: T) -> Self {
with_current_context(StateContext::signal);
Self {
changed: true,
inner,
}
}
pub fn invalidate(this: &mut Self) {
if !this.changed {
this.changed = true;
}
with_current_context(StateContext::signal);
}
}
impl<T> Deref for StateCell<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> DerefMut for StateCell<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
StateCell::invalidate(self);
&mut self.inner
}
}
impl<T> State for StateCell<T> {
type Output = ();
fn update(this: &mut Self) -> Option<Self::Output> {
if this.changed {
this.changed = false;
Some(())
} else {
None
}
}
}
impl<T> From<T> for StateCell<T> {
fn from(inner: T) -> Self {
Self::new(inner)
}
}
impl<T: Default> Default for StateCell<T> {
fn default() -> Self {
Self::new(Default::default())
}
}
impl<T> Drop for StateCell<T> {
fn drop(&mut self) {
with_current_context(StateContext::signal);
}
}
#[derive(Debug)]
pub struct StreamCell<T> {
inner: T,
}
impl<T: Stream> StreamCell<T> {
pub fn new(inner: T) -> Self {
with_current_context(StateContext::signal);
Self { inner }
}
}
impl<T: Stream + Unpin> State for StreamCell<T> {
type Output = T::Item;
fn update(this: &mut Self) -> Option<Self::Output> {
with_current_context(|cx| {
match Pin::new(&mut this.inner).poll_next(&mut cx.task_context()) {
Poll::Ready(Some(output)) => Some(output),
_ => None,
}
})
}
}
impl<T: Stream> From<T> for StreamCell<T> {
fn from(inner: T) -> Self {
Self::new(inner)
}
}
impl<T: Stream + Default> Default for StreamCell<T> {
fn default() -> Self {
Self::new(Default::default())
}
}
impl<T> Drop for StreamCell<T> {
fn drop(&mut self) {
with_current_context(StateContext::signal);
}
}