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
use crate::{
    ecs::Entity,
    prefab::{Prefab, PrefabComponent, PrefabError, PrefabProxy},
    state::StateToken,
};
use serde::{Deserialize, Serialize};
use std::{
    borrow::Cow,
    collections::{HashMap, VecDeque},
    marker::PhantomData,
};

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Tag(pub Cow<'static, str>);

impl Prefab for Tag {}
impl PrefabComponent for Tag {}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Name(pub Cow<'static, str>);

impl Prefab for Name {}
impl PrefabComponent for Name {}

#[derive(Debug, Default, Clone)]
pub struct NonPersistent(pub StateToken);

impl PrefabProxy<NonPersistentPrefabProxy> for NonPersistent {
    fn from_proxy_with_extras(
        _: NonPersistentPrefabProxy,
        _: &HashMap<String, Entity>,
        state_token: StateToken,
    ) -> Result<Self, PrefabError> {
        Ok(NonPersistent(state_token))
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct NonPersistentPrefabProxy;

impl Prefab for NonPersistentPrefabProxy {}

#[derive(Clone)]
pub struct Events<T>
where
    T: Send + Sync,
{
    buffer: VecDeque<T>,

    capacity: Option<usize>,

    pub auto_clear: bool,
}

impl<T> Default for Events<T>
where
    T: Send + Sync,
{
    fn default() -> Self {
        Self::new(None, true)
    }
}

impl<T> Events<T>
where
    T: Send + Sync,
{
    pub fn new(capacity: Option<usize>, auto_clear: bool) -> Self {
        Self {
            buffer: VecDeque::with_capacity(capacity.unwrap_or_default()),
            capacity,
            auto_clear,
        }
    }

    pub fn clear(&mut self) {
        self.buffer.clear();
    }

    pub fn read(&self) -> impl Iterator<Item = &T> {
        self.buffer.iter()
    }

    pub fn consume(&mut self) -> impl Iterator<Item = T> + '_ {
        self.buffer.drain(..)
    }

    pub fn consume_if<F>(&mut self, mut f: F) -> Vec<T>
    where
        F: FnMut(&T) -> bool,
    {
        if self.buffer.is_empty() {
            return Default::default();
        }
        let mut result = Vec::with_capacity(self.buffer.len());
        let mut buffer = VecDeque::with_capacity(self.buffer.capacity());
        for message in self.buffer.drain(..) {
            if f(&message) {
                result.push(message);
            } else {
                buffer.push_back(message);
            }
        }
        result
    }

    pub fn send(&mut self, message: T) {
        if let Some(capacity) = self.capacity {
            if self.buffer.len() >= capacity {
                self.buffer.pop_front();
            }
        }
        self.buffer.push_back(message);
    }

    pub fn try_send(&mut self, message: T) -> bool {
        if let Some(capacity) = self.capacity {
            if self.buffer.len() >= capacity {
                return false;
            }
        }
        self.buffer.push_back(message);
        true
    }
}

impl<T> PrefabProxy<EventsPrefabProxy<T>> for Events<T>
where
    T: Send + Sync + 'static,
{
    fn from_proxy_with_extras(
        proxy: EventsPrefabProxy<T>,
        _: &HashMap<String, Entity>,
        _: StateToken,
    ) -> Result<Self, PrefabError> {
        Ok(Events::new(proxy.capacity, proxy.auto_clear))
    }
}

#[derive(Default, Serialize, Deserialize)]
pub struct EventsPrefabProxy<T>
where
    T: Send + Sync,
{
    #[serde(default)]
    pub capacity: Option<usize>,
    #[serde(default = "EventsPrefabProxy::<T>::default_auto_clear")]
    pub auto_clear: bool,
    #[serde(skip)]
    _phantom: PhantomData<fn() -> T>,
}

impl<T> EventsPrefabProxy<T>
where
    T: Send + Sync,
{
    fn default_auto_clear() -> bool {
        true
    }
}

impl<T> Prefab for EventsPrefabProxy<T> where T: Send + Sync {}

#[cfg(test)]
mod tests {
    use super::*;
    use hecs::Component;

    #[test]
    fn test_component() {
        fn foo<T: Component>() {
            println!("{} is Component", std::any::type_name::<T>());
        }

        foo::<Tag>();
        foo::<Name>();
        foo::<NonPersistent>();
        foo::<Events<()>>();
    }
}