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
use components_arena::{RawId};
use core::any::{Any, TypeId};
use core::fmt::Debug;
use core::ops::{Deref, DerefMut};
use dyn_context::state::State;
use educe::Educe;

/// A type should satisfy this trait to be a dependency property type,
/// a dependency vector item type, or a flow data type.
pub trait Convenient: PartialEq + Clone + Debug + 'static { }

impl<T: PartialEq + Clone + Debug + 'static> Convenient for T { }

pub struct GlobDescriptor<Obj> {
    pub arena: TypeId,
    pub field_ref: fn(arena: &dyn Any, id: RawId) -> &Obj,
    pub field_mut: fn(arena: &mut dyn Any, id: RawId) -> &mut Obj
}

#[derive(Educe)]
#[educe(Debug, Clone, Copy)]
pub struct Glob<Obj> {
    pub id: RawId,
    pub descriptor: fn() -> GlobDescriptor<Obj>,
}

pub struct GlobRef<'a, Obj> {
    arena: &'a dyn Any,
    glob: Glob<Obj>,
}

impl<'a, Obj> Deref for GlobRef<'a, Obj> {
    type Target = Obj;

    fn deref(&self) -> &Obj {
        ((self.glob.descriptor)().field_ref)(self.arena.deref(), self.glob.id)
    }
}

pub struct GlobMut<'a, Obj> {
    arena: &'a mut dyn Any,
    glob: Glob<Obj>,
}

impl<'a, Obj> Deref for GlobMut<'a, Obj> {
    type Target = Obj;

    fn deref(&self) -> &Obj {
        ((self.glob.descriptor)().field_ref)(self.arena.deref(), self.glob.id)
    }
}

impl<'a, Obj> DerefMut for GlobMut<'a, Obj> {
    fn deref_mut(&mut self) -> &mut Obj {
        ((self.glob.descriptor)().field_mut)(self.arena.deref_mut(), self.glob.id)
    }
}

impl<Obj> Glob<Obj> {
    pub fn get(self, state: &dyn State) -> GlobRef<Obj> {
        let arena = (self.descriptor)().arena;
        GlobRef {
            arena: state.get_raw(arena).unwrap_or_else(|| panic!("{:?} required", arena)),
            glob: self
        }
    }

    pub fn get_mut(self, state: &mut dyn State) -> GlobMut<Obj> {
        let arena = (self.descriptor)().arena;
        GlobMut {
            arena: state.get_mut_raw(arena).unwrap_or_else(|| panic!("{:?} required", arena)),
            glob: self
        }
    }
}