1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::fmt;

use crate::{Error, FunctionStatus, Result, UnitNumber};

/// Represents the status of a JCM device unit, e.g. `Acceptor`, `Stacker`, `Recycler`, etc.
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UnitStatus {
    unit_number: UnitNumber,
    function_status: FunctionStatus,
}

impl UnitStatus {
    /// Creates a new [UnitStatus].
    pub const fn new() -> Self {
        Self {
            unit_number: UnitNumber::new(),
            function_status: FunctionStatus::new(),
        }
    }

    /// Gets the [UnitNumber] of the [UnitStatus].
    pub const fn unit_number(&self) -> UnitNumber {
        self.unit_number
    }

    /// Sets the [UnitNumber] of the [UnitStatus].
    pub fn set_unit_number(&mut self, val: UnitNumber) {
        self.unit_number = val;
    }

    /// Builder function that sets the [UnitNumber] of the [UnitStatus].
    pub fn with_unit_number(mut self, val: UnitNumber) -> Self {
        self.set_unit_number(val);
        self
    }

    /// Gets the [FunctionStatus] of the [UnitStatus].
    pub const fn function_status(&self) -> FunctionStatus {
        self.function_status
    }

    /// Sets the [FunctionStatus] of the [UnitStatus].
    pub fn set_function_status(&mut self, val: FunctionStatus) {
        self.function_status = val;
    }

    /// Builder function that sets the [FunctionStatus] of the [UnitStatus].
    pub fn with_function_status(mut self, val: FunctionStatus) -> Self {
        self.set_function_status(val);
        self
    }

    /// Gets the length of the [UnitStatus].
    pub const fn len() -> usize {
        UnitNumber::len() + FunctionStatus::len()
    }

    /// Gets whether the [UnitStatus] is empty.
    pub const fn is_empty(&self) -> bool {
        self.unit_number.is_empty() && self.function_status.is_empty()
    }

    /// Gets whether the [UnitStatus] is valid.
    pub const fn is_valid(&self) -> bool {
        self.unit_number.is_valid() && self.function_status.is_valid()
    }

    /// Infallible function that converts a byte array into a [UnitStatus].
    pub const fn from_bytes(val: &[u8]) -> Self {
        match val.len() {
            0 => Self::new(),
            1 => Self {
                unit_number: UnitNumber::from_u8(val[0]),
                function_status: FunctionStatus::new(),
            },
            _ => Self {
                unit_number: UnitNumber::from_u8(val[0]),
                function_status: FunctionStatus::from_u8(val[1]),
            },
        }
    }

    /// Infallible function that converts a [UnitStatus] into a byte array.
    pub const fn to_bytes(&self) -> [u8; 2] {
        [self.unit_number.to_u8(), self.function_status.to_u8()]
    }

    /// Infallible function that converts a [UnitStatus] into a byte array.
    pub const fn into_bytes(self) -> [u8; 2] {
        [self.unit_number.into_u8(), self.function_status.into_u8()]
    }
}

impl TryFrom<&[u8]> for UnitStatus {
    type Error = Error;

    fn try_from(val: &[u8]) -> Result<UnitStatus> {
        let len = Self::len();
        let val_len = val.len();

        if val_len < len {
            Err(Error::InvalidUnitStatusLen((val_len, len)))
        } else {
            Ok(Self {
                unit_number: UnitNumber::try_from(val[0])?,
                function_status: FunctionStatus::try_from(val[1])?,
            })
        }
    }
}

impl<const N: usize> TryFrom<&[u8; N]> for UnitStatus {
    type Error = Error;

    fn try_from(val: &[u8; N]) -> Result<UnitStatus> {
        val.as_ref().try_into()
    }
}

impl<const N: usize> TryFrom<[u8; N]> for UnitStatus {
    type Error = Error;

    fn try_from(val: [u8; N]) -> Result<UnitStatus> {
        val.as_ref().try_into()
    }
}

impl Default for UnitStatus {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for UnitStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{{")?;
        write!(f, r#""unit_number": {}, "#, self.unit_number)?;
        write!(f, r#""function_status": {}"#, self.function_status)?;
        write!(f, "}}")
    }
}

/// Convenience container for a list of [UnitStatus] items.
#[repr(C)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnitStatusList(pub Vec<UnitStatus>);

impl UnitStatusList {
    /// Creates a new [UnitStatusList].
    pub const fn new() -> Self {
        Self(Vec::new())
    }

    /// Gets a reference to the list of [UnitStatus] items.
    pub fn items(&self) -> &[UnitStatus] {
        self.0.as_ref()
    }

    /// Converts the [UnitStatusList] into its inner representation.
    pub fn into_inner(self) -> Vec<UnitStatus> {
        self.0
    }

    /// Writes the [UnitStatusList] to a byte buffer.
    pub fn to_bytes(&self, buf: &mut [u8]) -> Result<()> {
        let len = self.len();
        let buf_len = buf.len();

        if buf_len < len {
            Err(Error::InvalidUnitStatusListLen((buf_len, len)))
        } else {
            buf.iter_mut()
                .zip(self.0.iter().flat_map(|c| c.to_bytes()))
                .for_each(|(dst, src)| *dst = src);

            Ok(())
        }
    }

    /// Converts the [UnitStatusList] into a byte vector.
    pub fn as_bytes(&self) -> Vec<u8> {
        self.0.iter().flat_map(|c| c.to_bytes()).collect()
    }

    /// Converts the [UnitStatusList] into a byte vector.
    pub fn into_bytes(self) -> Vec<u8> {
        self.0.into_iter().flat_map(|c| c.into_bytes()).collect()
    }

    /// Gets the byte length of the [UnitStatusList].
    pub fn len(&self) -> usize {
        self.0.len().saturating_mul(UnitStatus::len())
    }

    /// Gets whether the [UnitStatusList] is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty() || self.0.iter().all(|u| u.is_empty())
    }
}

impl TryFrom<&[u8]> for UnitStatusList {
    type Error = Error;

    fn try_from(val: &[u8]) -> Result<Self> {
        let unit_len = UnitStatus::len();
        let val_len = val.len();

        if val_len % unit_len == 0 {
            Ok(Self(
                val.chunks_exact(UnitStatus::len())
                    .filter_map(|c| match UnitStatus::try_from(c) {
                        Ok(u) => Some(u),
                        Err(err) => {
                            log::warn!("invalid UnitStatus: {err}");
                            None
                        }
                    })
                    .collect(),
            ))
        } else {
            Err(Error::InvalidUnitStatusLen((val_len, unit_len)))
        }
    }
}

impl fmt::Display for UnitStatusList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[")?;
        for (i, unit) in self.0.iter().enumerate() {
            if i != 0 {
                write!(f, ", ")?;
            }
            write!(f, "{unit}")?;
        }
        write!(f, "]")
    }
}

impl Default for UnitStatusList {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_unit_status() -> Result<()> {
        const FUNC_STATS: [FunctionStatus; 9] = [
            FunctionStatus::Normal,
            FunctionStatus::NearFull,
            FunctionStatus::Full,
            FunctionStatus::BoxRemoved,
            FunctionStatus::JamAcceptor,
            FunctionStatus::JamStacker,
            FunctionStatus::Cheat,
            FunctionStatus::UnitRemoved,
            FunctionStatus::Failure,
        ];

        assert!(UnitStatus::try_from(&[]).is_err());
        assert!(UnitStatus::try_from(&[0u8]).is_err());
        assert!(UnitStatus::try_from(&[0u8, 0u8]).is_err());
        assert!(UnitStatus::try_from(&[1u8, 0u8]).is_ok());
        assert!(UnitStatus::try_from(&[1u8, 0u8, 0u8]).is_ok());

        let func_vals = FUNC_STATS.map(|f| f.to_u8());
        for num in 0x1..=0xf {
            for (i, func) in func_vals.into_iter().enumerate() {
                let raw = [num, func];
                let status = UnitStatus::try_from(&raw)?;
                let exp = UnitStatus::new()
                    .with_unit_number(UnitNumber::from_u8(num))
                    .with_function_status(FUNC_STATS[i]);

                assert_eq!(status.to_bytes(), raw);
                assert_eq!(status, exp);

                assert!(!status.is_empty());
                assert!(status.is_valid());
            }
        }

        Ok(())
    }
}