shrs_core/
state.rs

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
//! Globally accessible state store
//! States are accessible through handlers

use std::{
    any::{Any, TypeId},
    cell::{Ref, RefCell, RefMut},
    collections::HashMap,
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

use anyhow::{Context, Result};
use thiserror::Error;

use crate::prelude::Shell;
pub trait Param {
    type Item<'new>;

    fn retrieve<'r>(shell: &'r Shell, states: &'r States) -> Result<Self::Item<'r>>;
}

/// State store that uses types to index
impl<'res, T: 'static> Param for State<'res, T> {
    type Item<'new> = State<'new, T>;

    fn retrieve<'r>(_shell: &'r Shell, states: &'r States) -> Result<Self::Item<'r>> {
        Ok(State {
            value: states
                .states
                .get(&TypeId::of::<T>())
                .context("State Not Found")?
                .borrow(),
            _marker: PhantomData,
        })
    }
}

impl<'res, T: 'static> Param for StateMut<'res, T> {
    type Item<'new> = StateMut<'new, T>;

    fn retrieve<'r>(_shell: &'r Shell, states: &'r States) -> Result<Self::Item<'r>> {
        Ok(StateMut {
            value: states
                .states
                .get(&TypeId::of::<T>())
                .context("State Not Found")?
                .borrow_mut(),
            _marker: PhantomData,
        })
    }
}
// Not useful for us
// impl<T: 'static> Param for Result<T>
// where
//     T: Param,
//     <T as Param>::Item<'static>: 'static,
// {
//     type Item<'new> = Result<<T as Param>::Item<'new>>;

//     fn retrieve<'r>(shell: &'r Shell, states: &'r States) -> Result<Self::Item<'r>> {
//         Ok(T::retrieve(shell, states))
//     }
// }

impl<T: 'static> Param for Option<T>
where
    T: Param,
    <T as Param>::Item<'static>: 'static,
{
    type Item<'new> = Option<<T as Param>::Item<'new>>;

    fn retrieve<'r>(shell: &'r Shell, states: &'r States) -> Result<Self::Item<'r>> {
        Ok(T::retrieve(shell, states).ok())
    }
}

impl<'res> Param for &'res Shell {
    type Item<'new> = &'new Shell;

    fn retrieve<'r>(shell: &'r Shell, _states: &'r States) -> Result<Self::Item<'r>> {
        Ok(shell)
    }
}

pub struct State<'a, T: 'static> {
    value: Ref<'a, Box<dyn Any>>,
    _marker: PhantomData<&'a T>,
}

impl<T: 'static> Deref for State<'_, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.value.downcast_ref().unwrap()
    }
}

pub struct StateMut<'a, T: 'static> {
    value: RefMut<'a, Box<dyn Any>>,
    _marker: PhantomData<&'a mut T>,
}

impl<T: 'static> Deref for StateMut<'_, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.value.downcast_ref().unwrap()
    }
}

impl<T: 'static> DerefMut for StateMut<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.value.downcast_mut().unwrap()
    }
}

// Potential errors that can occur when interacting with state store
#[derive(Error, Debug)]
pub enum StateError {
    // TODO include the type in the error message
    #[error("Value is missing")]
    Missing,
    #[error("Failed to borrow")]
    Borrow,
    #[error("Failed to borrow mut")]
    BorrowMut,
    #[error("Failed to downcast")]
    Downcast,
}

// Global state store
#[derive(Default)]
pub struct States {
    states: HashMap<TypeId, RefCell<Box<dyn Any>>>,
}

impl States {
    // Insert a new piece of state of given type into global state store, overriding previously
    // existing values
    // TODO should we allow overriding contents of state?
    pub fn insert<S: 'static>(&mut self, res: S) {
        self.states
            .insert(TypeId::of::<S>(), RefCell::new(Box::new(res)));
    }

    // TODO this is potentially dangerous to allow arbitrary code to remove state
    pub fn remove<S>() -> Option<S> {
        todo!()
    }

    /// Get an immutable borrow of a state of a given type S from global state store. Will panic
    /// if a borrow exists or the type specified does not exist in the state store
    pub fn get<S: 'static>(&self) -> Ref<S> {
        self.try_get().unwrap()
    }

    /// Attempts to get an immutable borrow of a state of a given type S from global state store
    pub fn try_get<S: 'static>(&self) -> Result<Ref<S>, StateError> {
        let Some(s) = self.states.get(&TypeId::of::<S>()) else {
            return Err(StateError::Missing);
        };

        let Ok(s) = s.try_borrow() else {
            return Err(StateError::Borrow);
        };

        let Ok(s) = Ref::filter_map(s, |b| b.downcast_ref::<S>()) else {
            return Err(StateError::Downcast);
        };

        Ok(s)
    }

    /// Get a mutable borrow of a state of a given type S from global state store. Will panic
    /// if a borrow exists or the type specified does not exist in the state store
    pub fn get_mut<S: 'static>(&self) -> RefMut<S> {
        self.try_get_mut().unwrap()
    }

    /// Attempts to get a mutable borrow of a state of a given type S from global state store
    pub fn try_get_mut<S: 'static>(&self) -> Result<RefMut<S>, StateError> {
        let Some(s) = self.states.get(&TypeId::of::<S>()) else {
            return Err(StateError::Missing);
        };

        let Ok(s) = s.try_borrow_mut() else {
            return Err(StateError::Borrow);
        };

        let Ok(s) = RefMut::filter_map(s, |b| b.downcast_mut::<S>()) else {
            return Err(StateError::Downcast);
        };

        Ok(s)
    }
}