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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use bevy_utils::hashbrown::hash_set::IntoIter;
use bevy_utils::HashSet;
use std::any::{Any, TypeId};

/// A filter used to control which types can be added to a [`DynamicScene`].
///
/// This scene filter _can_ be used more generically to represent a filter for any given type;
/// however, note that its intended usage with `DynamicScene` only considers [components] and [resources].
/// Adding types that are not a component or resource will have no effect when used with `DynamicScene`.
///
/// [`DynamicScene`]: crate::DynamicScene
/// [components]: bevy_ecs::prelude::Component
/// [resources]: bevy_ecs::prelude::Resource
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub enum SceneFilter {
    /// Represents an unset filter.
    ///
    /// This is the equivalent of an empty [`Denylist`] or an [`Allowlist`] containing every type—
    /// essentially, all types are permissible.
    ///
    /// [Allowing] a type will convert this filter to an `Allowlist`.
    /// Similarly, [denying] a type will convert this filter to a `Denylist`.
    ///
    /// [`Denylist`]: SceneFilter::Denylist
    /// [`Allowlist`]: SceneFilter::Allowlist
    /// [Allowing]: SceneFilter::allow
    /// [denying]: SceneFilter::deny
    #[default]
    Unset,
    /// Contains the set of permitted types by their [`TypeId`].
    ///
    /// Types not contained within this set should not be allowed to be saved to an associated [`DynamicScene`].
    ///
    /// [`DynamicScene`]: crate::DynamicScene
    Allowlist(HashSet<TypeId>),
    /// Contains the set of prohibited types by their [`TypeId`].
    ///
    /// Types contained within this set should not be allowed to be saved to an associated [`DynamicScene`].
    ///
    /// [`DynamicScene`]: crate::DynamicScene
    Denylist(HashSet<TypeId>),
}

impl SceneFilter {
    /// Creates a filter where all types are allowed.
    ///
    /// This is the equivalent of creating an empty [`Denylist`].
    ///
    /// [`Denylist`]: SceneFilter::Denylist
    pub fn allow_all() -> Self {
        Self::Denylist(HashSet::new())
    }

    /// Creates a filter where all types are denied.
    ///
    /// This is the equivalent of creating an empty [`Allowlist`].
    ///
    /// [`Allowlist`]: SceneFilter::Allowlist
    pub fn deny_all() -> Self {
        Self::Allowlist(HashSet::new())
    }

    /// Allow the given type, `T`.
    ///
    /// If this filter is already set as a [`Denylist`],
    /// then the given type will be removed from the denied set.
    ///
    /// If this filter is [`Unset`], then it will be completely replaced by a new [`Allowlist`].
    ///
    /// [`Denylist`]: SceneFilter::Denylist
    /// [`Unset`]: SceneFilter::Unset
    /// [`Allowlist`]: SceneFilter::Allowlist
    #[must_use]
    pub fn allow<T: Any>(self) -> Self {
        self.allow_by_id(TypeId::of::<T>())
    }

    /// Allow the given type.
    ///
    /// If this filter is already set as a [`Denylist`],
    /// then the given type will be removed from the denied set.
    ///
    /// If this filter is [`Unset`], then it will be completely replaced by a new [`Allowlist`].
    ///
    /// [`Denylist`]: SceneFilter::Denylist
    /// [`Unset`]: SceneFilter::Unset
    /// [`Allowlist`]: SceneFilter::Allowlist
    #[must_use]
    pub fn allow_by_id(mut self, type_id: TypeId) -> Self {
        match &mut self {
            Self::Unset => {
                self = Self::Allowlist(HashSet::from([type_id]));
            }
            Self::Allowlist(list) => {
                list.insert(type_id);
            }
            Self::Denylist(list) => {
                list.remove(&type_id);
            }
        }
        self
    }

    /// Deny the given type, `T`.
    ///
    /// If this filter is already set as an [`Allowlist`],
    /// then the given type will be removed from the allowed set.
    ///
    /// If this filter is [`Unset`], then it will be completely replaced by a new [`Denylist`].
    ///
    /// [`Allowlist`]: SceneFilter::Allowlist
    /// [`Unset`]: SceneFilter::Unset
    /// [`Denylist`]: SceneFilter::Denylist
    #[must_use]
    pub fn deny<T: Any>(self) -> Self {
        self.deny_by_id(TypeId::of::<T>())
    }

    /// Deny the given type.
    ///
    /// If this filter is already set as an [`Allowlist`],
    /// then the given type will be removed from the allowed set.
    ///
    /// If this filter is [`Unset`], then it will be completely replaced by a new [`Denylist`].
    ///
    /// [`Allowlist`]: SceneFilter::Allowlist
    /// [`Unset`]: SceneFilter::Unset
    /// [`Denylist`]: SceneFilter::Denylist
    #[must_use]
    pub fn deny_by_id(mut self, type_id: TypeId) -> Self {
        match &mut self {
            Self::Unset => self = Self::Denylist(HashSet::from([type_id])),
            Self::Allowlist(list) => {
                list.remove(&type_id);
            }
            Self::Denylist(list) => {
                list.insert(type_id);
            }
        }
        self
    }

    /// Returns true if the given type, `T`, is allowed by the filter.
    ///
    /// If the filter is [`Unset`], this will always return `true`.
    ///
    /// [`Unset`]: SceneFilter::Unset
    pub fn is_allowed<T: Any>(&self) -> bool {
        self.is_allowed_by_id(TypeId::of::<T>())
    }

    /// Returns true if the given type is allowed by the filter.
    ///
    /// If the filter is [`Unset`], this will always return `true`.
    ///
    /// [`Unset`]: SceneFilter::Unset
    pub fn is_allowed_by_id(&self, type_id: TypeId) -> bool {
        match self {
            Self::Unset => true,
            Self::Allowlist(list) => list.contains(&type_id),
            Self::Denylist(list) => !list.contains(&type_id),
        }
    }

    /// Returns true if the given type, `T`, is denied by the filter.
    ///
    /// If the filter is [`Unset`], this will always return `false`.
    ///
    /// [`Unset`]: SceneFilter::Unset
    pub fn is_denied<T: Any>(&self) -> bool {
        self.is_denied_by_id(TypeId::of::<T>())
    }

    /// Returns true if the given type is denied by the filter.
    ///
    /// If the filter is [`Unset`], this will always return `false`.
    ///
    /// [`Unset`]: SceneFilter::Unset
    pub fn is_denied_by_id(&self, type_id: TypeId) -> bool {
        !self.is_allowed_by_id(type_id)
    }

    /// Returns an iterator over the items in the filter.
    ///
    /// If the filter is [`Unset`], this will return an empty iterator.
    ///
    /// [`Unset`]: SceneFilter::Unset
    pub fn iter(&self) -> Box<dyn ExactSizeIterator<Item = &TypeId> + '_> {
        match self {
            Self::Unset => Box::new(core::iter::empty()),
            Self::Allowlist(list) | Self::Denylist(list) => Box::new(list.iter()),
        }
    }

    /// Returns the number of items in the filter.
    ///
    /// If the filter is [`Unset`], this will always return a length of zero.
    ///
    /// [`Unset`]: SceneFilter::Unset
    pub fn len(&self) -> usize {
        match self {
            Self::Unset => 0,
            Self::Allowlist(list) | Self::Denylist(list) => list.len(),
        }
    }

    /// Returns true if there are zero items in the filter.
    ///
    /// If the filter is [`Unset`], this will always return `true`.
    ///
    /// [`Unset`]: SceneFilter::Unset
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Unset => true,
            Self::Allowlist(list) | Self::Denylist(list) => list.is_empty(),
        }
    }
}

impl IntoIterator for SceneFilter {
    type Item = TypeId;
    type IntoIter = IntoIter<TypeId>;

    fn into_iter(self) -> Self::IntoIter {
        match self {
            Self::Unset => HashSet::new().into_iter(),
            Self::Allowlist(list) | Self::Denylist(list) => list.into_iter(),
        }
    }
}

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

    #[test]
    fn should_set_list_type_if_none() {
        let filter = SceneFilter::Unset.allow::<i32>();
        assert!(matches!(filter, SceneFilter::Allowlist(_)));

        let filter = SceneFilter::Unset.deny::<i32>();
        assert!(matches!(filter, SceneFilter::Denylist(_)));
    }

    #[test]
    fn should_add_to_list() {
        let filter = SceneFilter::default().allow::<i16>().allow::<i32>();
        assert_eq!(2, filter.len());
        assert!(filter.is_allowed::<i16>());
        assert!(filter.is_allowed::<i32>());

        let filter = SceneFilter::default().deny::<i16>().deny::<i32>();
        assert_eq!(2, filter.len());
        assert!(filter.is_denied::<i16>());
        assert!(filter.is_denied::<i32>());
    }

    #[test]
    fn should_remove_from_list() {
        let filter = SceneFilter::default()
            .allow::<i16>()
            .allow::<i32>()
            .deny::<i32>();
        assert_eq!(1, filter.len());
        assert!(filter.is_allowed::<i16>());
        assert!(!filter.is_allowed::<i32>());

        let filter = SceneFilter::default()
            .deny::<i16>()
            .deny::<i32>()
            .allow::<i32>();
        assert_eq!(1, filter.len());
        assert!(filter.is_denied::<i16>());
        assert!(!filter.is_denied::<i32>());
    }
}