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
use core::ops;

// Note: Public documentation for this is in its re-export from `all_is_cubes::block`.
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd, exhaust::Exhaust)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[allow(missing_docs)]
#[repr(u8)]
#[non_exhaustive] // unlikely to change but on general principle: not supposed to match this
pub enum Resolution {
    R1 = 0,
    R2 = 1,
    R4 = 2,
    R8 = 3,
    R16 = 4,
    R32 = 5,
    R64 = 6,
    R128 = 7,
}
use core::fmt;

use crate::math::GridCoordinate;

impl Resolution {
    /// The maximum available resolution.
    pub const MAX: Resolution = Resolution::R128;

    /// Returns the [`Resolution`] that’s twice this one, or [`None`] at the limit.
    #[inline]
    pub const fn double(self) -> Option<Self> {
        match self {
            Self::R1 => Some(Self::R2),
            Self::R2 => Some(Self::R4),
            Self::R4 => Some(Self::R8),
            Self::R8 => Some(Self::R16),
            Self::R16 => Some(Self::R32),
            Self::R32 => Some(Self::R64),
            Self::R64 => Some(Self::R128),
            Self::R128 => None,
        }
    }

    /// Returns the [`Resolution`] that’s half this one, or [`None`] if `self` is
    /// [`R1`](Self::R1).
    #[inline]
    pub const fn halve(self) -> Option<Self> {
        match self {
            Self::R1 => None,
            Self::R2 => Some(Self::R1),
            Self::R4 => Some(Self::R2),
            Self::R8 => Some(Self::R4),
            Self::R16 => Some(Self::R8),
            Self::R32 => Some(Self::R16),
            Self::R64 => Some(Self::R32),
            Self::R128 => Some(Self::R64),
        }
    }

    #[inline]
    #[doc(hidden)] // interim while waiting for better const-eval support in Rust
    pub const fn to_grid(self) -> GridCoordinate {
        1 << self as GridCoordinate
    }
}

impl fmt::Debug for Resolution {
    #[allow(clippy::missing_inline_in_public_items)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        GridCoordinate::from(*self).fmt(f)
    }
}
impl fmt::Display for Resolution {
    #[allow(clippy::missing_inline_in_public_items)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        GridCoordinate::from(*self).fmt(f)
    }
}

macro_rules! impl_try_from {
    ($t:ty) => {
        impl TryFrom<$t> for Resolution {
            type Error = IntoResolutionError<$t>;
            #[inline]
            fn try_from(value: $t) -> Result<Self, Self::Error> {
                match value {
                    1 => Ok(Self::R1),
                    2 => Ok(Self::R2),
                    4 => Ok(Self::R4),
                    8 => Ok(Self::R8),
                    16 => Ok(Self::R16),
                    32 => Ok(Self::R32),
                    64 => Ok(Self::R64),
                    128 => Ok(Self::R128),
                    _ => Err(IntoResolutionError(value)),
                }
            }
        }
    };
}
impl_try_from!(i16);
impl_try_from!(i32);
impl_try_from!(i64);
impl_try_from!(i128);
impl_try_from!(isize);
impl_try_from!(u16);
impl_try_from!(u32);
impl_try_from!(u64);
impl_try_from!(u128);
impl_try_from!(usize);

impl From<Resolution> for i32 {
    /// ```
    /// # mod all_is_cubes { pub mod block { pub use all_is_cubes_base::resolution::Resolution; } }
    /// use all_is_cubes::block::Resolution;
    ///
    /// assert_eq!(64, i32::from(Resolution::R64));
    /// ```
    #[inline]
    fn from(r: Resolution) -> i32 {
        1 << (r as i32)
    }
}
impl From<Resolution> for u16 {
    #[inline]
    fn from(r: Resolution) -> u16 {
        1 << (r as u16)
    }
}
impl From<Resolution> for u32 {
    #[inline]
    fn from(r: Resolution) -> u32 {
        1 << (r as u32)
    }
}
impl From<Resolution> for usize {
    #[inline]
    fn from(r: Resolution) -> usize {
        1 << (r as usize)
    }
}
impl From<Resolution> for f32 {
    #[inline]
    fn from(r: Resolution) -> f32 {
        u16::from(r).into()
    }
}
impl From<Resolution> for f64 {
    #[inline]
    fn from(r: Resolution) -> f64 {
        u16::from(r).into()
    }
}

impl ops::Mul<Resolution> for Resolution {
    type Output = Option<Resolution>;

    #[inline]
    fn mul(self, rhs: Resolution) -> Self::Output {
        // not the most efficient way to implement this, but straightforward
        Self::try_from(u32::from(self) * u32::from(rhs)).ok()
    }
}

impl ops::Div<Resolution> for Resolution {
    type Output = Option<Resolution>;

    #[inline]
    fn div(self, rhs: Resolution) -> Self::Output {
        // not the most efficient way to implement this, but straightforward
        Self::try_from(u32::from(self) / u32::from(rhs)).ok()
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Resolution {
    #[allow(clippy::missing_inline_in_public_items)]
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        u16::from(*self).serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Resolution {
    #[allow(clippy::missing_inline_in_public_items)]
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        u16::deserialize(deserializer)?
            .try_into()
            .map_err(serde::de::Error::custom)
    }
}

/// Error type produced by [`TryFrom`] for [`Resolution`], and deserializing resolutions,
/// when the number is not a permitted resolution value.
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub struct IntoResolutionError<N>(N);

crate::util::cfg_should_impl_error! {
    impl<N: fmt::Display + fmt::Debug> std::error::Error for IntoResolutionError<N> {}
}

impl<N: fmt::Display> fmt::Display for IntoResolutionError<N> {
    #[allow(clippy::missing_inline_in_public_items)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{number} is not a permitted resolution; must be a power of 2 between 1 and 127",
            number = self.0
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec::Vec;
    use exhaust::Exhaust as _;
    use Resolution::*;

    const RS: [Resolution; 8] = [R1, R2, R4, R8, R16, R32, R64, R128];

    #[test]
    fn test_list_is_complete() {
        assert_eq!(
            Vec::from(RS),
            Resolution::exhaust().collect::<Vec<Resolution>>()
        );
    }

    #[test]
    fn max_is_max() {
        assert_eq!(Resolution::MAX, *RS.last().unwrap());
        assert_eq!(None, Resolution::MAX.double());
    }

    #[test]
    fn resolution_steps() {
        for i in 0..RS.len() - 1 {
            assert_eq!(RS[i].double().unwrap(), RS[i + 1]);
            assert_eq!(RS[i + 1].halve().unwrap(), RS[i]);
        }
    }

    #[test]
    fn resolution_values() {
        assert_eq!(RS.map(i32::from), [1, 2, 4, 8, 16, 32, 64, 128]);
        assert_eq!(RS.map(u16::from), [1, 2, 4, 8, 16, 32, 64, 128]);
        assert_eq!(RS.map(u32::from), [1, 2, 4, 8, 16, 32, 64, 128]);
        assert_eq!(RS.map(usize::from), [1, 2, 4, 8, 16, 32, 64, 128]);
    }

    #[test]
    fn mul() {
        assert_eq!(R4 * R2, Some(R8));
        assert_eq!(R128 * R2, None);
        assert_eq!(R2 * R128, None);
    }

    #[test]
    fn div() {
        assert_eq!(R8 / R2, Some(R4));
        assert_eq!(R128 / R128, Some(R1));
        assert_eq!(R1 / R2, None);
        assert_eq!(R64 / R128, None);
    }
}