Skip to main content

naia_shared/world/component/
property_mutate.rs

1use std::ops::{Deref, DerefMut};
2
3/// Tracks which Properties have changed and need to be queued for syncing with
4/// the Client
5pub trait PropertyMutate: PropertyMutateClone + Send + Sync + 'static {
6    /// Given the index of the Property whose value has changed, queue that
7    /// Property for transmission to the Client
8    fn mutate(&mut self, property_index: u8) -> bool;
9}
10
11/// Helper trait enabling `Box<dyn PropertyMutate>` to be cloned without knowing the concrete type.
12pub trait PropertyMutateClone {
13    /// Returns a heap-allocated clone of this mutator.
14    fn clone_box(&self) -> Box<dyn PropertyMutate>;
15}
16
17impl<T: 'static + Clone + PropertyMutate> PropertyMutateClone for T {
18    fn clone_box(&self) -> Box<dyn PropertyMutate> {
19        Box::new(self.clone())
20    }
21}
22
23impl Clone for Box<dyn PropertyMutate> {
24    fn clone(&self) -> Box<dyn PropertyMutate> {
25        PropertyMutateClone::clone_box(self.as_ref())
26    }
27}
28
29/// Owned handle to a heap-allocated [`PropertyMutate`] implementor, used by `EntityProperty` to signal field changes.
30#[derive(Clone)]
31pub struct PropertyMutator {
32    inner: Box<dyn PropertyMutate>,
33}
34
35impl PropertyMutator {
36    /// Creates a `PropertyMutator` wrapping the given concrete `PropertyMutate` implementation.
37    pub fn new<M: PropertyMutate>(mutator: M) -> Self {
38        let inner = Box::new(mutator);
39        Self { inner }
40    }
41
42    /// Returns a freshly cloned `PropertyMutator` backed by a new heap allocation.
43    pub fn clone_new(&self) -> Self {
44        //let current_inner: &dyn PropertyMutateClone = self.inner.as_ref() as &dyn
45        // PropertyMutateClone;
46        let new_inner = self.inner.as_ref().clone_box();
47
48        Self { inner: new_inner }
49    }
50}
51
52impl Deref for PropertyMutator {
53    type Target = dyn PropertyMutate;
54
55    fn deref(&self) -> &Self::Target {
56        self.inner.deref()
57    }
58}
59
60impl DerefMut for PropertyMutator {
61    fn deref_mut(&mut self) -> &mut Self::Target {
62        self.inner.deref_mut()
63    }
64}