light_ranged_integers 0.1.1

A Rust library similar to ranged_integers, a bit limited to work on stable rust
Documentation
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
Copyright © 2024 - Massimo Gismondi

This file is part of light-ranged-integers.

light-ranged-integers is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

light-ranged-integers is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with light-ranged-integers.  If not, see <http://www.gnu.org/licenses/>.
*/

use std::ops::{Add, Div, Rem, Sub};

use crate::op_mode::{BringInRange, Wrap};

use super::op_mode;
use crate::*;
use paste::paste;

impl<N> BringInRange<N> for Wrap
where
    N: Ord
        + Sub<Output = N>
        + TryFrom<u8>
        + Add<Output = N>
        + Div<Output = N>
        + Rem<Output = N>
        + Copy
{
    fn bring_in_range(v: N, min: N, max: N) -> N
    {
        let mut n = v;
        let one: N;
        unsafe {
            one = 1u8.try_into().unwrap_unchecked();
        }
        if n > max
        {
            let interval_size = max - min + one;
            n = ((n - min) % interval_size) + min;
        }
        else if n < min
        {
            // n < min
            let interval_size = max - min + one;
            let modulo = min % interval_size;
            // n = ((n+min) % interval_size) + min - (min%interval_size);
            // let times = min/interval_size;
            // let range_index = min%interval_size;
            // eprintln!("n: {}, times: {}, modulo:{modulo}, interval_size: {}, range_index: {range_index}", n, times, interval_size);
            n = min + (n + interval_size - modulo) % interval_size;
        }
        n
    }
}

// Wrapping reference implementation
#[cfg(test)]
fn wrap(n: u32, min: u32, max: u32) -> u32
{
    let mut n = n;
    if n > max
    {
        let interval_size = max - min + 1;
        n = ((n - min) % interval_size) + min;
    }
    else if n < min
    {
        // n < min
        let interval_size = max - min + 1;
        // n = ((n+min) % interval_size) + min - (min%interval_size);
        let times = min / interval_size;
        let modulo = min % interval_size;
        let range_index = min % interval_size;
        eprintln!(
            "n: {}, times: {}, modulo:{modulo}, interval_size: {}, range_index: {range_index}",
            n, times, interval_size
        );
        n = min + (n + interval_size - modulo) % interval_size;
    }
    n
}

macro_rules! gen_wrap_impl {
    ($i:ty, $bigger_type:ty) => {
    paste!{
        // Additions
        impl<const MIN: $i, const MAX: $i> std::ops::Add for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
        {
            type Output = Self;
            fn add(self, rhs: [<Ranged $i:upper>]<MIN,MAX, op_mode::Wrap>) -> Self::Output {
                self + rhs.inner()
            }
        }
        impl<const MIN: $i, const MAX: $i> std::ops::Add<$i> for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
        {
            type Output = Self;
            fn add(self, rhs: $i) -> Self::Output
            {
                let v1 = self.inner();
                let v2 = rhs;
                let delta: $i = (MIN - $i::MIN) + ($i::MAX - MAX);
                Self::new(
                    match v1.checked_add(v2)
                    {
                        Some(res) => res,
                        None => {
                            match v2
                            {
                                v2 if v2 > 0 => {
                                    let r1 = v1.wrapping_add(v2);
                                    match r1.checked_add(delta)
                                    {
                                        Some(res) => res,
                                        None => {r1.wrapping_add(delta).checked_add(delta).unwrap()}
                                    }
                                }
                                // equals sign just turns off a warning,
                                // but has no effect. v2 < 0 is correct
                                v2 if v2 <= 0 => {
                                    let r1 = v1.wrapping_add(v2);
                                    // v2 is negative, invert delta add/sub
                                    match r1.checked_sub(delta)
                                    {
                                        Some(res) => res,
                                        None => {r1.wrapping_sub(delta).checked_sub(delta).unwrap()}
                                    }
                                }
                                _ => {panic!("Can't get here, we're adding 0 and it should have been checked before")}
                            }
                        }
                    }
                )
            }
        }
        impl<const MIN: $i, const MAX: $i> std::ops::AddAssign for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
        {
            fn add_assign(&mut self, rhs: [<Ranged $i:upper>]<MIN,MAX, op_mode::Wrap>)
            {
                *self += rhs.inner();
            }
        }
        impl<const MIN: $i, const MAX: $i> std::ops::AddAssign<$i> for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
        {
            fn add_assign(&mut self, rhs: $i)
            {
                *self = *self + rhs;
            }
        }


        // Subtraction
        impl<const MIN: $i, const MAX: $i> std::ops::Sub for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
        {
            type Output = Self;
            fn sub(self, rhs: [<Ranged $i:upper>]<MIN,MAX, op_mode::Wrap>) -> Self::Output {
                self - rhs.inner()
            }
        }
        impl<const MIN: $i, const MAX: $i> std::ops::Sub<$i> for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
        {
            type Output = Self;
            fn sub(self, rhs: $i) -> Self::Output
            {
                let v1 = self.inner();
                let v2 = rhs;
                let delta: $i = (MIN - $i::MIN) + ($i::MAX - MAX);
                Self::new(
                    match v1.checked_sub(v2)
                    {
                        Some(res) => res,
                        None => {
                            match v2
                            {
                                v2 if v2 > 0 => {
                                    let r1 = v1.wrapping_sub(v2);
                                    match r1.checked_sub(delta)
                                    {
                                        Some(res) => res,
                                        None => {r1.wrapping_sub(delta).checked_sub(delta).unwrap()}
                                    }
                                }
                                // equals sign just turns off a warning,
                                // but has no effect. v2 < 0 is correct
                                v2 if v2 <= 0 => {
                                    let r1 = v1.wrapping_sub(v2);
                                    match r1.checked_add(delta)
                                    {
                                        Some(res) => res,
                                        None => {r1.wrapping_add(delta).checked_add(delta).unwrap()}
                                    }
                                }
                                _ => {panic!("Can't get here, we're adding 0 and it should have been checked before")}
                            }

                        }
                    }
                )
            }
        }
        impl<const MIN: $i, const MAX: $i> std::ops::SubAssign for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
        {
            fn sub_assign(&mut self, rhs: [<Ranged $i:upper>]<MIN,MAX, op_mode::Wrap>)
            {
                *self -= rhs.inner();
            }
        }
        impl<const MIN: $i, const MAX: $i> std::ops::SubAssign<$i> for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
        {
            fn sub_assign(&mut self, rhs: $i)
            {
                *self = *self - rhs;
            }
        }


        // Multiplication
    //     impl<const MIN: $i, const MAX: $i> std::ops::Mul for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
    //     {
    //         type Output = Self;
    //         fn mul(self, rhs: [<Ranged $i:upper>]<MIN,MAX, op_mode::Wrap>) -> Self::Output {
    //             self * rhs.inner()
    //         }
    //     }
    //     impl<const MIN: $i, const MAX: $i> std::ops::Mul<$i> for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
    //     {
    //         type Output = Self;
    //         fn mul(self, rhs: $i) -> Self::Output {
    //             Self::new(
    //                 wrapped_operation!(
    //                     checked_mul,
    //                     $i,
    //                     $bigger_type,
    //                     self.inner(),
    //                     rhs
    //                 )
    //             )
    //         }
    //     }
    //     impl<const MIN: $i, const MAX: $i> std::ops::MulAssign for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
    //     {
    //         fn mul_assign(&mut self, rhs: [<Ranged $i:upper>]<MIN,MAX, op_mode::Wrap>)
    //         {
    //             *self *= rhs.inner();
    //         }
    //     }
    //     impl<const MIN: $i, const MAX: $i> std::ops::MulAssign<$i> for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
    //     {
    //         fn mul_assign(&mut self, rhs: $i)
    //         {
    //             *self = Self::new(
    //                 wrapped_operation!(
    //                     checked_mul,
    //                     $i,
    //                     $bigger_type,
    //                     self.inner(),
    //                     rhs
    //                 )
    //             )
    //         }
    //     }

    //     // Division
    //     impl<const MIN: $i, const MAX: $i> std::ops::Div for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
    //     {
    //         type Output = Self;
    //         fn div(self, rhs: [<Ranged $i:upper>]<MIN,MAX, op_mode::Wrap>) -> Self::Output {
    //             self / rhs.inner()
    //         }
    //     }
    //     impl<const MIN: $i, const MAX: $i> std::ops::Div<$i> for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
    //     {
    //         type Output = Self;
    //         fn div(self, rhs: $i) -> Self::Output {
    //             Self::new(
    //                 wrapped_operation!(
    //                     checked_div,
    //                     $i,
    //                     $bigger_type,
    //                     self.inner(),
    //                     rhs
    //                 )
    //             )
    //         }
    //     }
    //     impl<const MIN: $i, const MAX: $i> std::ops::DivAssign for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
    //     {
    //         fn div_assign(&mut self, rhs: [<Ranged $i:upper>]<MIN,MAX, op_mode::Wrap>)
    //         {
    //             *self /=  rhs.inner();
    //         }
    //     }
    //     impl<const MIN: $i, const MAX: $i> std::ops::DivAssign<$i> for [<Ranged $i:upper>]<MIN, MAX, op_mode::Wrap>
    //     {
    //         fn div_assign(&mut self, rhs: $i)
    //         {
    //             *self =  Self::new(
    //                 wrapped_operation!(
    //                     checked_div,
    //                     $i,
    //                     $bigger_type,
    //                     self.inner(),
    //                     rhs
    //                 )
    //             );
    //         }
    //     }
    }
    };
    }

gen_wrap_impl!(u8, u16);
gen_wrap_impl!(i8, i16);
gen_wrap_impl!(u16, u32);
gen_wrap_impl!(i16, i32);
gen_wrap_impl!(u32, u64);
gen_wrap_impl!(i32, i64);
gen_wrap_impl!(u64, u128);
gen_wrap_impl!(i64, i128);

#[cfg(test)]
mod tests
{
    use crate::{op_mode::Wrap, RangedI8, RangedU8};

    use super::wrap;

    fn run_test(input: &[u32], output: &[u32], interval_min: u32, interval_max: u32)
    {
        for (i, o) in input.iter().zip(output)
        {
            println!("{} {}", wrap(*i, interval_min, interval_max), *o);
        }
        for (i, o) in input.iter().zip(output)
        {
            assert_eq!(wrap(*i, interval_min, interval_max), *o);
        }
    }

    #[test]
    fn test_against_stdlib()
    {
        assert_eq!(wrap(255 + 2, 0, 255), 255u8.wrapping_add(2).into());

        assert_eq!(
            wrap(255 + 255 + 2, 0, 255),
            255u8.wrapping_add(2).wrapping_add(255).into()
        );
        assert_eq!(wrap(255 + 2, 0, 255), 255u8.wrapping_add(2).into());

        assert_eq!(
            wrap(255 + 255 + 2, 0, 255),
            255u8.wrapping_add(2).wrapping_add(255).into()
        );
    }

    #[test]
    fn test_1()
    {
        assert_eq!(wrap(6, 0, 5), 0);
        assert_eq!(wrap(6, 1, 5), 1);
        assert_eq!(wrap(15, 0, 5), 15 % 6);
        // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
        // 0 1 2 3 4 5 0 1 2 3 4  5  0  1  2  3
        assert_eq!(wrap(15, 0, 5), 3);
    }

    #[test]
    fn test_2()
    {
        // Wrap around interval [2,4]
        // 0  1 [2  3  4] 5  6  7  8  9  10 11 12 13 14 15
        // 3  4  2  3  4  2  3  4  2  3  4  2  3  4  2  3
        const INPUTS: [u32; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        const OUTPUTS: [u32; 16] = [3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3];

        run_test(&INPUTS, &OUTPUTS, 2, 4);
    }

    #[test]
    fn test_3()
    {
        // Wrap around interval
        // 0  1  2  3  4  5 [6  7  8] 9  10 11 12 13 14 15
        // 6  7  8  6  7  8  6  7  8  6  7  8  6  7  8  6
        const INTERVAL: [u32; 2] = [6, 8];
        const INPUTS: [u32; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        const OUTPUTS: [u32; 16] = [6, 7, 8, 6, 7, 8, 6, 7, 8, 6, 7, 8, 6, 7, 8, 6];

        run_test(&INPUTS, &OUTPUTS, INTERVAL[0], INTERVAL[1]);
    }

    #[test]
    fn test_4()
    {
        //
        // Wrap around interval
        // 0  1  2  3  4  5  6  7  8  9  10[11 12 13 14 15]16 17 18
        // 15 11 12 14 14 15 11 12 13 14 15 11 12 13 14 15 11 12 13
        const INTERVAL: [u32; 2] = [11, 15];
        const INPUTS: [u32; 19] = [
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18
        ];
        const OUTPUTS: [u32; 19] = [
            15, 11, 12, 13, 14, 15, 11, 12, 13, 14, 15, 11, 12, 13, 14, 15, 11, 12, 13
        ];

        run_test(&INPUTS, &OUTPUTS, INTERVAL[0], INTERVAL[1]);
    }

    #[test]
    fn test_type_overflow()
    {
        let n1: RangedU8<10, 250, Wrap> = RangedU8::new(245);
        let n2: RangedU8<10, 250, Wrap> = RangedU8::new(13);
        assert_eq!(n1 + n2, 17);
        // -128,127
        let n1: RangedI8<-120, 100, Wrap> = RangedI8::new(-118);
        let n2: RangedI8<-120, 100, Wrap> = RangedI8::new(-13);
        let n3: RangedI8<-120, 100, Wrap> = RangedI8::new(13);
        assert_eq!(n1 + n2, 90);
        assert_eq!(n1 - n3, 90);

        let m = RangedU8::<5, 250, Wrap>::new(5);
        assert_eq!(m - 1, 250);
        assert_eq!(m - 10, 241);
    }
}