1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use std::{
    pin::Pin,
    task::{Context, Poll},
};

use async_component_core::{AsyncComponent, ComponentPollFlags, StateCell};

#[derive(Debug, Default)]
pub struct OptionComponent<T> {
    updated: StateCell<()>,

    component: Option<T>,
}

impl<T: AsyncComponent> OptionComponent<T> {
    pub const fn new(component: Option<T>) -> Self {
        Self {
            updated: StateCell::new(()),
            component,
        }
    }

    pub const fn is_none(&self) -> bool {
        self.component.is_none()
    }

    pub const fn is_some(&self) -> bool {
        self.component.is_some()
    }

    pub const fn get(&self) -> Option<&T> {
        self.component.as_ref()
    }

    pub fn get_mut(&mut self) -> Option<&mut T> {
        self.component.as_mut()
    }

    pub fn take(&mut self) -> Option<()> {
        self.component.take()?;
        StateCell::invalidate(&mut self.updated);

        Some(())
    }

    pub fn set(&mut self, component: Option<T>) {
        self.component = component;
        StateCell::invalidate(&mut self.updated);
    }
}

impl<T: AsyncComponent> AsyncComponent for OptionComponent<T> {
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<ComponentPollFlags> {
        let mut result = ComponentPollFlags::empty();

        if StateCell::refresh(&mut self.updated) {
            result |= ComponentPollFlags::STATE;
        }

        if let Some(ref mut component) = self.component {
            if let Poll::Ready(flag) = Pin::new(component).poll_next(cx) {
                result |= flag;
            }
        }

        if result.is_empty() {
            Poll::Pending
        } else {
            Poll::Ready(result)
        }
    }
}

impl<T: AsyncComponent> From<Option<T>> for OptionComponent<T> {
    fn from(opt: Option<T>) -> Self {
        Self::new(opt)
    }
}