veloren_common/
link.rs

1use serde::{Deserialize, Serialize};
2use specs::{Component, DerefFlaggedStorage, SystemData};
3use std::{ops::Deref, sync::Arc};
4
5pub trait Link: Sized + Send + Sync + 'static {
6    type Error;
7
8    type CreateData<'a>: SystemData<'a>;
9    fn create(this: &LinkHandle<Self>, data: &mut Self::CreateData<'_>) -> Result<(), Self::Error>;
10
11    type PersistData<'a>: SystemData<'a>;
12    fn persist(this: &LinkHandle<Self>, data: &mut Self::PersistData<'_>) -> bool;
13
14    type DeleteData<'a>: SystemData<'a>;
15    fn delete(this: &LinkHandle<Self>, data: &mut Self::DeleteData<'_>);
16}
17
18pub trait Role {
19    type Link: Link;
20}
21
22#[derive(Serialize, Deserialize, Debug)]
23pub struct Is<R: Role> {
24    #[serde(bound(serialize = "R::Link: Serialize"))]
25    #[serde(bound(deserialize = "R::Link: Deserialize<'de>"))]
26    link: LinkHandle<R::Link>,
27}
28
29impl<R: Role> Is<R> {
30    pub fn delete(&self, data: &mut <R::Link as Link>::DeleteData<'_>) {
31        Link::delete(&self.link, data)
32    }
33}
34
35impl<R: Role> Clone for Is<R> {
36    fn clone(&self) -> Self {
37        Self {
38            link: self.link.clone(),
39        }
40    }
41}
42
43impl<R: Role> Deref for Is<R> {
44    type Target = R::Link;
45
46    fn deref(&self) -> &Self::Target { &self.link }
47}
48
49impl<R: Role + 'static> Component for Is<R>
50where
51    R::Link: Send + Sync + 'static,
52{
53    type Storage = DerefFlaggedStorage<Self, specs::VecStorage<Self>>;
54}
55
56#[derive(Serialize, Deserialize, Debug)]
57pub struct LinkHandle<L: Link> {
58    link: Arc<L>,
59}
60
61impl<L: Link> Clone for LinkHandle<L> {
62    fn clone(&self) -> Self {
63        Self {
64            link: Arc::clone(&self.link),
65        }
66    }
67}
68
69impl<L: Link> LinkHandle<L> {
70    pub fn from_link(link: L) -> Self {
71        Self {
72            link: Arc::new(link),
73        }
74    }
75
76    pub fn make_role<R: Role<Link = L>>(&self) -> Is<R> { Is { link: self.clone() } }
77}
78
79impl<L: Link> Deref for LinkHandle<L> {
80    type Target = L;
81
82    fn deref(&self) -> &Self::Target { &self.link }
83}