Skip to main content

datex_core/shared_values/
ownership.rs

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