Skip to main content

datex_core/shared_values/
ownership.rs

1use crate::shared_values::SharedContainerMutability;
2use binrw::{BinRead, BinWrite};
3use core::{
4    cmp::Ordering,
5    fmt,
6    fmt::{Display, Formatter},
7};
8use num_enum::TryFromPrimitive;
9use serde::{Deserialize, Serialize};
10
11use serde_repr::*;
12#[derive(
13    Debug,
14    Clone,
15    Copy,
16    PartialEq,
17    Eq,
18    Hash,
19    TryFromPrimitive,
20    BinRead,
21    BinWrite,
22    Serialize_repr,
23    Deserialize_repr,
24)]
25#[brw(repr(u8))]
26#[repr(u8)]
27pub enum ReferenceMutability {
28    Immutable = 0,
29    Mutable = 1,
30}
31impl ReferenceMutability {
32    pub const fn string(&self) -> &'static str {
33        match self {
34            ReferenceMutability::Immutable => "'",
35            ReferenceMutability::Mutable => "'mut",
36        }
37    }
38}
39
40impl Display for ReferenceMutability {
41    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
42        write!(f, "{}", self.string())
43    }
44}
45
46impl From<ReferenceMutability> for SharedContainerOwnership {
47    fn from(mutability: ReferenceMutability) -> Self {
48        SharedContainerOwnership::Referenced(mutability)
49    }
50}
51
52impl From<ReferenceMutability> for SharedContainerMutability {
53    fn from(mutability: ReferenceMutability) -> Self {
54        match mutability {
55            ReferenceMutability::Immutable => {
56                SharedContainerMutability::Immutable
57            }
58            ReferenceMutability::Mutable => SharedContainerMutability::Mutable,
59        }
60    }
61}
62
63impl PartialOrd<Self> for ReferenceMutability {
64    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
65        Some(self.cmp(other))
66    }
67}
68
69impl Ord for ReferenceMutability {
70    fn cmp(&self, other: &Self) -> Ordering {
71        match (self, other) {
72            (
73                ReferenceMutability::Immutable,
74                ReferenceMutability::Immutable,
75            ) => Ordering::Equal,
76            (ReferenceMutability::Immutable, ReferenceMutability::Mutable) => {
77                Ordering::Less
78            }
79            (ReferenceMutability::Mutable, ReferenceMutability::Immutable) => {
80                Ordering::Greater
81            }
82            (ReferenceMutability::Mutable, ReferenceMutability::Mutable) => {
83                Ordering::Equal
84            }
85        }
86    }
87}
88
89#[derive(
90    Debug,
91    Clone,
92    Copy,
93    PartialEq,
94    Eq,
95    Hash,
96    Serialize,
97    Deserialize,
98    BinRead,
99    BinWrite,
100)]
101#[serde(untagged)]
102pub enum SharedContainerOwnership {
103    #[brw(magic = 0x0u8)]
104    Owned,
105    #[brw(magic = 0x1u8)]
106    Referenced(ReferenceMutability),
107}
108
109impl TryFrom<Option<u8>> for SharedContainerOwnership {
110    type Error = &'static str;
111    fn try_from(value: Option<u8>) -> Result<Self, Self::Error> {
112        match value {
113            None => Ok(SharedContainerOwnership::Owned),
114            Some(i) => {
115                let mutability = ReferenceMutability::try_from(i)
116                    .map_err(|_| "Invalid ownership value")?;
117                Ok(SharedContainerOwnership::Referenced(mutability))
118            }
119        }
120    }
121}
122
123impl SharedContainerOwnership {
124    const OWNED: &'static str = SharedContainerOwnership::Owned.string();
125    const REFERENCED_IMMUTABLE: &'static str =
126        SharedContainerOwnership::Referenced(ReferenceMutability::Immutable)
127            .string();
128    const REFERENCED_MUTABLE: &'static str =
129        SharedContainerOwnership::Referenced(ReferenceMutability::Mutable)
130            .string();
131
132    pub const fn string(&self) -> &'static str {
133        match self {
134            SharedContainerOwnership::Owned => "",
135            SharedContainerOwnership::Referenced(mutability) => {
136                mutability.string()
137            }
138        }
139    }
140    pub const fn try_from_string(s: &str) -> Option<Self> {
141        match s {
142            Self::OWNED => Some(SharedContainerOwnership::Owned),
143            Self::REFERENCED_IMMUTABLE => {
144                Some(SharedContainerOwnership::Referenced(
145                    ReferenceMutability::Immutable,
146                ))
147            }
148            Self::REFERENCED_MUTABLE => {
149                Some(SharedContainerOwnership::Referenced(
150                    ReferenceMutability::Mutable,
151                ))
152            }
153            _ => None,
154        }
155    }
156}
157
158impl Display for SharedContainerOwnership {
159    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
160        write!(f, "{}", self.string())
161    }
162}
163
164impl PartialOrd<Self> for SharedContainerOwnership {
165    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
166        Some(self.cmp(other))
167    }
168}
169
170impl Ord for SharedContainerOwnership {
171    fn cmp(&self, other: &Self) -> Ordering {
172        match (self, other) {
173            (
174                SharedContainerOwnership::Owned,
175                SharedContainerOwnership::Owned,
176            ) => Ordering::Equal,
177            (
178                SharedContainerOwnership::Owned,
179                SharedContainerOwnership::Referenced(_),
180            ) => Ordering::Greater,
181            (
182                SharedContainerOwnership::Referenced(_),
183                SharedContainerOwnership::Owned,
184            ) => Ordering::Less,
185            (
186                SharedContainerOwnership::Referenced(m1),
187                SharedContainerOwnership::Referenced(m2),
188            ) => m1.cmp(m2),
189        }
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use crate::shared_values::{ReferenceMutability, SharedContainerOwnership};
196    use test_case::test_case;
197    #[test_case(SharedContainerOwnership::Owned; "owned")]
198    #[test_case(SharedContainerOwnership::Referenced(ReferenceMutability::Immutable); "referenced immutable")]
199    #[test_case(SharedContainerOwnership::Referenced(ReferenceMutability::Mutable); "referenced mutable")]
200    fn ownership_serde(ownership: SharedContainerOwnership) {
201        let serialized = serde_json::to_value(ownership).unwrap();
202        let deserialized: SharedContainerOwnership =
203            serde_json::from_value(serialized).unwrap();
204        assert_eq!(ownership, deserialized);
205    }
206}