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
79
80
81
82
83
84
85
86
87
use atomic_polyfill::{AtomicBool, Ordering};

pub trait SplitState: Clone {
    fn same(&self, other: &Self) -> bool;
    fn is_open(&self) -> bool;
    fn set_open(&self, open: bool);
}

pub trait SplitStateContainer {
    type State: SplitState;

    fn state(self) -> Self::State;
}

pub struct SplitConnectionState {
    is_open: AtomicBool,
}

impl Default for SplitConnectionState {
    #[inline]
    fn default() -> Self {
        Self {
            is_open: AtomicBool::new(true),
        }
    }
}

impl<'a> SplitStateContainer for &'a mut SplitConnectionState {
    type State = &'a SplitConnectionState;

    fn state(self) -> Self::State {
        &*self
    }
}

impl SplitState for &SplitConnectionState {
    fn is_open(&self) -> bool {
        self.is_open.load(Ordering::Acquire)
    }

    fn set_open(&self, open: bool) {
        self.is_open.store(open, Ordering::Release);
    }

    fn same(&self, other: &Self) -> bool {
        core::ptr::eq(*self, *other)
    }
}

#[cfg(feature = "std")]
pub use stdlib::ManagedSplitState;

#[cfg(feature = "std")]
mod stdlib {
    use super::*;
    use std::sync::Arc;

    #[derive(Clone)]
    pub struct ManagedSplitState(Arc<SplitConnectionState>);
    impl ManagedSplitState {
        pub(crate) fn new() -> Self {
            Self(Arc::new(SplitConnectionState::default()))
        }
    }

    impl SplitStateContainer for ManagedSplitState {
        type State = ManagedSplitState;

        fn state(self) -> Self::State {
            self
        }
    }

    impl SplitState for ManagedSplitState {
        fn is_open(&self) -> bool {
            self.0.as_ref().is_open()
        }

        fn set_open(&self, open: bool) {
            self.0.as_ref().set_open(open)
        }

        fn same(&self, other: &Self) -> bool {
            Arc::ptr_eq(&self.0, &other.0)
        }
    }
}