Skip to main content

datex_core/global/protocol_structures/
injected_values.rs

1use crate::{global::stack_index::StackIndex, prelude::*};
2use binrw::{
3    BinRead, BinResult, BinWrite, Endian,
4    io::{Read, Seek, Write},
5};
6use core::fmt::Display;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub enum SharedInjectedValueType {
10    // shared x
11    Move = 2,
12    // 'mut shared mut x
13    RefMut = 1,
14    // 'shared x
15    Ref = 0,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
19pub enum LocalInjectedValueType {
20    /// The value is moved into the child scope and no longer used afterward
21    Move = 2,
22    /// The value is temporarily borrowed in the child scope - the changed value must be written back to the parent scope afterward
23    RefMut = 1,
24    /// The value is moved into the child scope but still used afterward (clone or immutable ref (&x))
25    Copy = 0,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display)]
29pub enum InjectedValueType {
30    Local(LocalInjectedValueType),
31    Shared(SharedInjectedValueType),
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, BinRead, BinWrite)]
35pub struct InjectedValueDeclaration {
36    pub(crate) index: StackIndex,
37    pub(crate) ty: InjectedValueType,
38}
39
40impl Display for InjectedValueDeclaration {
41    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
42        write!(f, "[index:{}, type: {:?}]", self.index, self.ty)
43    }
44}
45
46impl From<InjectedValueType> for u8 {
47    fn from(injected_value_type: InjectedValueType) -> Self {
48        match injected_value_type {
49            InjectedValueType::Local(local_type) => match local_type {
50                LocalInjectedValueType::Move => 0,
51                LocalInjectedValueType::Copy => 1,
52                LocalInjectedValueType::RefMut => 2,
53            },
54            InjectedValueType::Shared(shared_type) => match shared_type {
55                SharedInjectedValueType::Move => 3,
56                SharedInjectedValueType::Ref => 4,
57                SharedInjectedValueType::RefMut => 5,
58            },
59        }
60    }
61}
62
63impl TryFrom<u8> for InjectedValueType {
64    type Error = ();
65    fn try_from(value: u8) -> Result<Self, Self::Error> {
66        match value {
67            0 => Ok(InjectedValueType::Local(LocalInjectedValueType::Move)),
68            1 => Ok(InjectedValueType::Local(LocalInjectedValueType::Copy)),
69            2 => Ok(InjectedValueType::Local(LocalInjectedValueType::RefMut)),
70            3 => Ok(InjectedValueType::Shared(SharedInjectedValueType::Move)),
71            4 => Ok(InjectedValueType::Shared(SharedInjectedValueType::Ref)),
72            5 => Ok(InjectedValueType::Shared(SharedInjectedValueType::RefMut)),
73            _ => Err(()),
74        }
75    }
76}
77
78impl BinWrite for InjectedValueType {
79    type Args<'a> = ();
80
81    fn write_options<W: Write + Seek>(
82        &self,
83        writer: &mut W,
84        endian: Endian,
85        _: Self::Args<'_>,
86    ) -> BinResult<()> {
87        // only handle le for now
88        if endian != Endian::Little {
89            return Err(binrw::Error::AssertFail {
90                pos: writer.stream_position().unwrap_or(0),
91                message:
92                    "Only little-endian is supported for InjectedValueType"
93                        .to_string(),
94            });
95        }
96        // write type
97        writer.write_all(&[u8::from(*self)])?;
98
99        Ok(())
100    }
101}
102
103impl BinRead for InjectedValueType {
104    type Args<'a> = ();
105
106    fn read_options<R: Read + Seek>(
107        reader: &mut R,
108        endian: Endian,
109        _: Self::Args<'_>,
110    ) -> BinResult<Self> {
111        // only handle le for now
112        if endian != Endian::Little {
113            return Err(binrw::Error::AssertFail {
114                pos: reader.stream_position().unwrap_or(0),
115                message:
116                    "Only little-endian is supported for InjectedValueType"
117                        .to_string(),
118            });
119        }
120        // read type
121        let mut type_buf = [0u8; 1];
122        reader.read_exact(&mut type_buf)?;
123        let value_type =
124            InjectedValueType::try_from(type_buf[0]).map_err(|_| {
125                binrw::Error::AssertFail {
126                    pos: reader.stream_position().unwrap_or(0),
127                    message: format!(
128                        "Invalid InjectedValueType value: {}",
129                        type_buf[0]
130                    ),
131                }
132            })?;
133        Ok(value_type)
134    }
135}