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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use std::{
    convert::TryInto,
    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign},
};

/// An absolute (non-negative) offset from the beginning of a core.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Offset {
    value: u32,
    core_size: u32,
}

impl Offset {
    /// Create a new Offset. The value will be adjusted to be within bounds of the core.
    ///
    /// # Panics
    /// If `core_size` is invalid. Both 0 and `u32::MAX` are disallowed.
    #[must_use]
    pub fn new(value: i32, core_size: u32) -> Self {
        // TODO: should there be a minimum allowed core size?
        TryInto::<i32>::try_into(core_size).unwrap_or_else(|_| {
            panic!(
                "Attempt to create offset with invalid core_size {}",
                core_size
            )
        });

        let mut result = Self {
            value: 0,
            core_size,
        };
        result.set_value(value);
        result
    }

    /// Get the value of the offset. This will always be less than the core size.
    #[must_use]
    pub fn value(&self) -> u32 {
        self.value
    }

    /// Set the value of the offset. The value will be adjusted to be within
    /// bounds of the core size.
    pub fn set_value(&mut self, value: i32) {
        let core_isize = self
            .core_size
            .try_into()
            .expect("Core size should never be > i32::MAX");

        self.value = value.rem_euclid(core_isize) as u32;
    }

    /// Verify another offset has the same core size. Panics otherwise
    fn check_core_size(self, other: Self) {
        assert_eq!(
            self.core_size, other.core_size,
            "attempt to add mismatching core sizes: {} != {}",
            self.core_size, other.core_size,
        );
    }
}

impl std::fmt::Display for Offset {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value.fmt(f)
    }
}

/// Implement a `std::ops` operation for `Offset`.
macro_rules! impl_offset_op {
    (
        $op_trait:ident :: $op:ident ,
        $assign_trait:ident :: $assign:ident $(,)?
    ) => {
        impl $op_trait for Offset {
            type Output = Self;

            // Note $-expansion doesn't happen in doc comments. If needed there
            // is a workaround in https://github.com/rust-lang/rust/issues/52607

            /// Panics if the  right-hand side has a different `core_size`
            /// than the left-hand side.
            fn $op(self, rhs: Self) -> Self {
                self.check_core_size(rhs);
                let mut result = Self::new(0, self.core_size);
                result.set_value((self.value as i32).$op(rhs.value as i32));
                result
            }
        }

        impl $assign_trait for Offset {
            fn $assign(&mut self, rhs: Self) {
                // check_core_size is called by $op_trait::$op
                *self = self.$op(rhs)
            }
        }
    };
}

impl_offset_op! { Add::add, AddAssign::add_assign }
impl_offset_op! { Sub::sub, SubAssign::sub_assign }
impl_offset_op! { Mul::mul, MulAssign::mul_assign }
impl_offset_op! { Div::div, DivAssign::div_assign }
impl_offset_op! { Rem::rem, RemAssign::rem_assign }

/// Implement a `std::ops` operation for `Offset` and another type
macro_rules! impl_op {
    (
        $rhs:ty,
        $op_trait:ident :: $op:ident ,
        $assign_trait:ident :: $assign:ident $(,)?
    ) => {
        impl $op_trait<$rhs> for Offset {
            type Output = Self;

            fn $op(self, rhs: $rhs) -> Self::Output {
                self.$op(Self::new(rhs as i32, self.core_size))
            }
        }

        impl $assign_trait<$rhs> for Offset {
            fn $assign(&mut self, rhs: $rhs) {
                self.set_value((self.$op(rhs)).value as _)
            }
        }
    };
}

impl_op! { i32, Add::add, AddAssign::add_assign }
impl_op! { u32, Add::add, AddAssign::add_assign }
impl_op! { i32, Div::div, DivAssign::div_assign }
impl_op! { u32, Div::div, DivAssign::div_assign }
impl_op! { i32, Mul::mul, MulAssign::mul_assign }
impl_op! { u32, Mul::mul, MulAssign::mul_assign }
impl_op! { i32, Rem::rem, RemAssign::rem_assign }
impl_op! { u32, Rem::rem, RemAssign::rem_assign }
impl_op! { i32, Sub::sub, SubAssign::sub_assign }
impl_op! { u32, Sub::sub, SubAssign::sub_assign }

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn create_offset() {
        let offset = Offset::new(1234, 12);
        assert_eq!(offset.value(), 10);
    }

    #[test]
    fn set_offset_value() {
        let mut offset = Offset::new(1234, 12);
        offset.set_value(20);
        assert_eq!(offset.value(), 8);
    }

    #[test]
    fn add_offset() {
        let mut offset = Offset::new(0, 12);

        assert_eq!(offset + 17_i32, Offset::new(5, 12));
        assert_eq!(offset + -17_i32, Offset::new(7, 12));
        assert_eq!(offset + Offset::new(17, 12), Offset::new(5, 12));
        assert_eq!(offset + Offset::new(-17, 12), Offset::new(7, 12));
        assert_eq!(offset + 17_u32, Offset::new(5, 12));

        offset += 17_i32;
        assert_eq!(offset, Offset::new(5, 12));
        offset = Offset::new(0, 12);

        offset += -17_i32;
        assert_eq!(offset, Offset::new(7, 12));
        offset = Offset::new(0, 12);

        offset += Offset::new(17, 12);
        assert_eq!(offset, Offset::new(5, 12));
        offset = Offset::new(0, 12);

        offset += Offset::new(-17, 12);
        assert_eq!(offset, Offset::new(7, 12));
        offset = Offset::new(0, 12);

        offset += 17_u32;
        assert_eq!(offset, Offset::new(5, 12));
    }

    #[test]
    fn sub_offset() {
        let mut offset = Offset::new(0, 12);

        assert_eq!(offset - 17_i32, Offset::new(7, 12));
        assert_eq!(offset - -17_i32, Offset::new(5, 12));
        assert_eq!(offset - Offset::new(17, 12), Offset::new(7, 12));
        assert_eq!(offset - Offset::new(-17, 12), Offset::new(5, 12));
        assert_eq!(offset - 17_u32, Offset::new(7, 12));

        offset -= 17_i32;
        assert_eq!(offset, Offset::new(7, 12));

        offset = Offset::new(0, 12);
        offset -= -17_i32;
        assert_eq!(offset, Offset::new(5, 12));

        offset = Offset::new(0, 12);
        offset -= Offset::new(17, 12);
        assert_eq!(offset, Offset::new(7, 12));

        offset = Offset::new(0, 12);
        offset -= Offset::new(-17, 12);
        assert_eq!(offset, Offset::new(5, 12));

        offset = Offset::new(0, 12);
        offset -= 17_u32;
        assert_eq!(offset, Offset::new(7, 12));
    }

    #[test]
    fn mul_offset() {
        let mut offset = Offset::new(2, 12);

        assert_eq!(offset * 5_i32, Offset::new(10, 12));
        assert_eq!(offset * -5_i32, Offset::new(2, 12));
        assert_eq!(offset * Offset::new(5, 12), Offset::new(10, 12));
        assert_eq!(offset * Offset::new(-5, 12), Offset::new(2, 12));
        assert_eq!(offset * 5_u32, Offset::new(10, 12));

        offset *= 5_i32;
        assert_eq!(offset, Offset::new(10, 12));

        offset = Offset::new(2, 12);
        offset *= -5_i32;
        assert_eq!(offset, Offset::new(2, 12));

        offset = Offset::new(2, 12);
        offset *= Offset::new(5, 12);
        assert_eq!(offset, Offset::new(10, 12));

        offset = Offset::new(2, 12);
        offset *= Offset::new(-5, 12);
        assert_eq!(offset, Offset::new(2, 12));

        offset = Offset::new(2, 12);
        offset *= 5_u32;
        assert_eq!(offset, Offset::new(10, 12));
    }

    #[test]
    fn div_offset() {
        let mut offset = Offset::new(10, 12);

        assert_eq!(offset / 5_i32, Offset::new(2, 12));
        assert_eq!(offset / -5_i32, Offset::new(1, 12));
        assert_eq!(offset / Offset::new(5, 12), Offset::new(2, 12));
        assert_eq!(offset / Offset::new(-5, 12), Offset::new(1, 12));
        assert_eq!(offset / 5_u32, Offset::new(2, 12));

        offset /= 5_i32;
        assert_eq!(offset, Offset::new(2, 12));

        offset = Offset::new(10, 12);
        offset /= -5_i32;
        assert_eq!(offset, Offset::new(1, 12));

        offset = Offset::new(10, 12);
        offset /= Offset::new(5, 12);
        assert_eq!(offset, Offset::new(2, 12));

        offset = Offset::new(10, 12);
        offset /= Offset::new(-5, 12);
        assert_eq!(offset, Offset::new(1, 12));

        offset = Offset::new(10, 12);
        offset /= 5_u32;
        assert_eq!(offset, Offset::new(2, 12));
    }

    #[test]
    fn rem_offset() {
        let mut offset = Offset::new(8, 12);

        assert_eq!(offset % 5_i32, Offset::new(3, 12));
        assert_eq!(offset % -5_i32, Offset::new(1, 12));
        assert_eq!(offset % Offset::new(5, 12), Offset::new(3, 12));
        assert_eq!(offset % Offset::new(-5, 12), Offset::new(1, 12));
        assert_eq!(offset % 5_u32, Offset::new(3, 12));

        offset %= 5_i32;
        assert_eq!(offset, Offset::new(3, 12));

        offset = Offset::new(8, 12);
        offset %= -5_i32;
        assert_eq!(offset, Offset::new(1, 12));

        offset = Offset::new(8, 12);
        offset %= Offset::new(5, 12);
        assert_eq!(offset, Offset::new(3, 12));

        offset = Offset::new(8, 12);
        offset %= Offset::new(-5, 12);
        assert_eq!(offset, Offset::new(1, 12));

        offset = Offset::new(8, 12);
        offset %= 5_u32;
        assert_eq!(offset, Offset::new(3, 12));
    }
}