highroller 0.1.0

A simple, high-level rolling index that is thread-safe and guarantees cheap runtime-unique IDs.
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/", "README.md"))]

use std::sync::Mutex;

use lazy_static::lazy_static;

macro_rules! declare_rolling_idx {
    ($t:ty, $max_val:expr) => {
        lazy_static! {
            /// The rolling index. This is increased with each call to `rolling_idx`.
            static ref _ROLLING_IDX: Mutex<$t> = Mutex::new(0);
        }

        /// Returns the current rolling index and then increases it by 1.
        ///
        /// The rolling index is ephemeral and runtime-specific,
        /// meaning it is reset every time the application starts.
        ///
        #[cfg(all(feature = "strict"))]
        /// NOTE: The feature flag `strict` *is* enabled, so on overflow, this will panic.
        pub fn rolling_idx() -> $t {
            #[cfg(not(feature = "strict"))]
            panic!(
                "This should not be able to be called, flags set incorrectly (inform the \
            maintainer)"
            );

            let val: $t = {
                let mut this = crate::_ROLLING_IDX.lock().unwrap();
                if *this == $max_val {
                    panic!("Overflow detected");
                }
                let _val = *this;
                *this += 1;
                _val
            };
            val
        }

        #[cfg(not(feature = "strict"))]
        /// NOTE: The feature flag `strict` is *not* enabled, so on overflow, this will wrap.
        pub fn rolling_idx() -> $t {
            #[cfg(all(feature = "strict"))]
            panic!(
                "This should not be able to be called, flags set incorrectly (inform the \
            maintainer)"
            );

            let val: $t = {
                let mut this = crate::_ROLLING_IDX.lock().unwrap();
                if *this == $max_val {
                    *this = 0;
                }
                let _val = *this;
                *this += 1;
                _val
            };
            val
        }

        #[cfg(all(feature = "ruid_type"))]
        use std::clone::Clone;
        #[cfg(all(feature = "ruid_type"))]
        use std::cmp::{Eq, Ord, PartialEq, PartialOrd};
        #[cfg(all(feature = "ruid_type"))]
        use std::convert::{From, Into};
        #[cfg(all(feature = "ruid_type"))]
        use std::fmt;
        #[cfg(all(feature = "ruid_type"))]
        use std::fmt::{Debug, Display};
        #[cfg(all(feature = "ruid_type"))]
        use std::marker::Copy;

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        use std::ops::{Add, Div, Mul /*, Neg*/, Rem, Sub};
        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        use std::ops::{AddAssign, DivAssign, MulAssign, RemAssign, SubAssign};

        #[cfg(all(feature = "ruid_type"))]
        pub struct RUID {
            __value: $t,
        }

        #[cfg(all(feature = "ruid_type"))]
        impl RUID {
            pub fn new() -> Self {
                RUID {
                    __value: $crate::rolling_idx(),
                }
            }
        }

        #[cfg(all(feature = "ruid_type"))]
        impl Copy for RUID {}

        #[cfg(all(feature = "ruid_type"))]
        impl Clone for RUID {
            fn clone(&self) -> Self {
                *self
            }
        }

        #[cfg(all(feature = "ruid_type"))]
        impl PartialEq for RUID {
            fn eq(&self, other: &Self) -> bool {
                self.__value == other.__value
            }
        }

        #[cfg(all(feature = "ruid_type"))]
        impl Eq for RUID {}

        #[cfg(all(feature = "ruid_type"))]
        impl PartialOrd for RUID {
            fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
                self.__value.partial_cmp(&other.__value)
            }
        }

        #[cfg(all(feature = "ruid_type"))]
        impl Ord for RUID {
            fn cmp(&self, other: &Self) -> std::cmp::Ordering {
                self.__value.cmp(&other.__value)
            }
        }

        #[cfg(all(feature = "ruid_type", not(feature = "strict")))]
        impl PartialEq<$t> for RUID {
            fn eq(&self, other: &$t) -> bool {
                self.__value == *other
            }
        }

        #[cfg(all(feature = "ruid_type", not(feature = "strict")))]
        impl PartialOrd<$t> for RUID {
            fn partial_cmp(&self, other: &$t) -> Option<std::cmp::Ordering> {
                self.__value.partial_cmp(other)
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl Add for RUID {
            type Output = Self;

            fn add(self, other: Self) -> Self {
                RUID {
                    __value: self.__value + other.__value,
                }
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl Sub for RUID {
            type Output = Self;

            fn sub(self, other: Self) -> Self {
                RUID {
                    __value: self.__value - other.__value,
                }
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl Mul for RUID {
            type Output = Self;

            fn mul(self, other: Self) -> Self {
                RUID {
                    __value: self.__value * other.__value,
                }
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl Div for RUID {
            type Output = Self;

            fn div(self, other: Self) -> Self {
                RUID {
                    __value: self.__value / other.__value,
                }
            }
        }

        // #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        // impl std::ops::Neg for RUID {
        //     type Output = Self;
        //
        //     fn neg(self) -> Self::Output {
        //         RUID {
        //             __value: -self.__value,
        //         }
        //     }
        // }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl std::ops::Rem for RUID {
            type Output = Self;

            fn rem(self, other: Self) -> Self {
                RUID {
                    __value: self.__value % other.__value,
                }
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl std::ops::AddAssign for RUID {
            fn add_assign(&mut self, other: Self) {
                self.__value += other.__value;
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl std::ops::SubAssign for RUID {
            fn sub_assign(&mut self, other: Self) {
                self.__value -= other.__value;
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl std::ops::MulAssign for RUID {
            fn mul_assign(&mut self, other: Self) {
                self.__value *= other.__value;
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl std::ops::DivAssign for RUID {
            fn div_assign(&mut self, other: Self) {
                self.__value /= other.__value;
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
        impl std::ops::RemAssign for RUID {
            fn rem_assign(&mut self, other: Self) {
                self.__value %= other.__value;
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl Add<$t> for RUID {
            type Output = Self;

            fn add(self, other: $t) -> Self {
                RUID {
                    __value: self.__value + other,
                }
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl Sub<$t> for RUID {
            type Output = Self;

            fn sub(self, other: $t) -> Self {
                RUID {
                    __value: self.__value - other,
                }
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl Mul<$t> for RUID {
            type Output = Self;

            fn mul(self, other: $t) -> Self {
                RUID {
                    __value: self.__value * other,
                }
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl Div<$t> for RUID {
            type Output = Self;

            fn div(self, other: $t) -> Self {
                RUID {
                    __value: self.__value / other,
                }
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl Rem<$t> for RUID {
            type Output = Self;

            fn rem(self, other: $t) -> Self {
                RUID {
                    __value: self.__value % other,
                }
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl AddAssign<$t> for RUID {
            fn add_assign(&mut self, other: $t) {
                self.__value += other;
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl SubAssign<$t> for RUID {
            fn sub_assign(&mut self, other: $t) {
                self.__value -= other;
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl MulAssign<$t> for RUID {
            fn mul_assign(&mut self, other: $t) {
                self.__value *= other;
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl DivAssign<$t> for RUID {
            fn div_assign(&mut self, other: $t) {
                self.__value /= other;
            }
        }

        #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
        impl RemAssign<$t> for RUID {
            fn rem_assign(&mut self, other: $t) {
                self.__value %= other;
            }
        }

        #[cfg(all(feature = "ruid_type"))]
        impl Display for RUID {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "{}", self.__value)
            }
        }

        #[cfg(all(feature = "ruid_type"))]
        impl Debug for RUID {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_struct("RUID")
                    .field("value", &self.__value)
                    .finish()
            }
        }

        #[cfg(all(feature = "ruid_type"))]
        impl From<$t> for RUID {
            fn from(value: $t) -> Self {
                RUID {
                    __value: value,
                }
            }
        }

        #[cfg(all(feature = "ruid_type"))]
        impl Into<$t> for RUID {
            fn into(self) -> $t {
                self.__value
            }
        }
    };
}

#[cfg(feature = "u8_index")]
declare_rolling_idx!(u8, u8::MAX);

#[cfg(feature = "u16_index")]
declare_rolling_idx!(u16, u16::MAX);

#[cfg(feature = "u32_index")]
declare_rolling_idx!(u32, u32::MAX);

#[cfg(feature = "u64_index")]
declare_rolling_idx!(u64, u64::MAX);

#[cfg(feature = "u128_index")]
declare_rolling_idx!(u128, u128::MAX);

#[cfg(feature = "usize_index")]
declare_rolling_idx!(usize, usize::MAX);

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

    static RUN_LOCK: Mutex<bool> = Mutex::new(false);

    // NEED INPUT:
    // Re: the smelly poison clearings - My thinking is this:
    // If an earlier test panicked, it would fail that test, so it does not matter that much
    // if I clear the poison when starting another test. The RUN_LOCK should ensure that the tests
    // run sequentially, and while two of the tests do intentional race conditions and other
    // threading problems, the .join() call there should ensure that *IF* any of the threads
    // panicked, it would fail the test *before* we ever cleared the poison.
    // This correct?

    pub fn reset_rolling_idx() {
        _ROLLING_IDX.clear_poison();
        let mut index = _ROLLING_IDX.lock().unwrap();
        *index = 0;
    }

    #[test]
    fn test_rolling_index_generation() {
        let _lock_res = RUN_LOCK.lock();
        let test_fn = || {
            reset_rolling_idx();

            let id1 = rolling_idx();
            let id2 = rolling_idx();

            assert_ne!(id1, id2, "Newly generated IDs should not be the same");
        };

        match _lock_res {
            Ok(lock_guard) => {
                test_fn();
            },
            Err(poisoned_lock) => {
                RUN_LOCK.clear_poison();
                let lock_guard = poisoned_lock.into_inner();
                test_fn();
            },
        }
    }

    #[test]
    fn test_rolling_index_linearity() {
        let _lock_res = RUN_LOCK.lock();
        let test_fn = || {
            reset_rolling_idx();

            let count: usize = 254;
            let mut counts = Vec::new();
            for i in 0..count {
                counts.push(rolling_idx() as usize);
            }

            assert_eq!(
                counts.len(),
                count,
                "[vec len] {} == {} | Something is wrong with the rolling index stepping!",
                counts.len(),
                count
            );
        };

        match _lock_res {
            Ok(lock_guard) => {
                test_fn();
            },
            Err(poisoned_lock) => {
                RUN_LOCK.clear_poison();
                let lock_guard = poisoned_lock.into_inner();
                test_fn();
            },
        }
    }

    #[test]
    fn test_rolling_index_generation_multithreaded() {
        let _lock_res = RUN_LOCK.lock();
        let test_fn = || {
            reset_rolling_idx();

            use std::thread;
            use std::time::Duration;

            let sleep_delays = [0, 0, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90]; // in milliseconds
            let children: Vec<_> = (0..1000)
                .map(|i| {
                    let delay = sleep_delays[i % sleep_delays.len()];
                    thread::Builder::new()
                        .name(format!("test_thread_{}", i))
                        .spawn(move || {
                            thread::sleep(Duration::from_millis(delay as u64));
                            rolling_idx()
                        })
                        .unwrap()
                })
                .collect();

            let mut ids = Vec::new();
            for (i, child) in children.into_iter().enumerate() {
                match child.join() {
                    Ok(id) => {
                        assert!(
                            !ids.contains(&id),
                            "Newly generated ID was the same as a previous one"
                        );
                        ids.push(id);
                    },
                    Err(err) => {
                        println!("{:?}", err);
                        eprintln!("Thread {} panicked", i);
                        panic!();
                    },
                }
            }
        };

        match _lock_res {
            Ok(lock_guard) => {
                test_fn();
            },
            Err(poisoned_lock) => {
                RUN_LOCK.clear_poison();
                let lock_guard = poisoned_lock.into_inner();
                test_fn();
            },
        }
    }

    #[test]
    #[cfg(feature = "ruid_type")]
    fn test_ruid_generation() {
        let _lock_res = RUN_LOCK.lock();
        let test_fn = || {
            reset_rolling_idx();

            let id1 = RUID::new();
            let id2 = RUID::new();

            assert_ne!(id1, id2, "Newly generated IDs should not be the same");
        };

        match _lock_res {
            Ok(lock_guard) => {
                test_fn();
            },
            Err(poisoned_lock) => {
                RUN_LOCK.clear_poison();
                let lock_guard = poisoned_lock.into_inner();
                test_fn();
            },
        }
    }

    #[test]
    #[cfg(feature = "ruid_type")]
    fn test_ruid_generation_multithreaded() {
        let _lock_res = RUN_LOCK.lock();
        let test_fn = || {
            reset_rolling_idx();

            use std::thread;
            use std::time::Duration;

            let sleep_delays = [0, 0, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90]; // in milliseconds
            let children: Vec<_> = (0..1000)
                .map(|i| {
                    let delay = sleep_delays[i % sleep_delays.len()];
                    thread::spawn(move || {
                        thread::sleep(Duration::from_millis(delay as u64));
                        RUID::new()
                    })
                })
                .collect();

            let mut ids = Vec::new();
            for (i, child) in children.into_iter().enumerate() {
                match child.join() {
                    Ok(id) => {
                        assert!(
                            !ids.contains(&id),
                            "Newly generated ID was the same as a previous one"
                        );
                        ids.push(id);
                    },
                    Err(err) => {
                        println!("{:?}", err);
                        eprintln!("Thread {} panicked", i);
                        panic!();
                    },
                }
            }
        };

        match _lock_res {
            Ok(lock_guard) => {
                test_fn();
            },
            Err(poisoned_lock) => {
                RUN_LOCK.clear_poison();
                let lock_guard = poisoned_lock.into_inner();
                test_fn();
            },
        }
    }

    #[test]
    #[should_panic]
    #[cfg(all(feature = "strict", feature = "u8_index"))]
    fn test_u8_overflow_panic() {
        let _lock_res = RUN_LOCK.lock();
        let test_fn = || {
            reset_rolling_idx();
            for _ in 0..300 {
                let _ = rolling_idx();
            }
            RUN_LOCK.clear_poison();
        };

        match _lock_res {
            Ok(lock_guard) => {
                test_fn();
            },
            Err(poisoned_lock) => {
                RUN_LOCK.clear_poison();
                let lock_guard = poisoned_lock.into_inner();
                test_fn();
            },
        }
    }

    #[test]
    #[should_panic]
    #[cfg(all(feature = "strict", feature = "u16_index"))]
    fn test_u16_overflow_panic() {
        let _lock_res = RUN_LOCK.lock();
        let test_fn = || {
            reset_rolling_idx();
            for _ in 0..70_000 {
                let _ = rolling_idx();
            }
            RUN_LOCK.clear_poison();
        };

        match _lock_res {
            Ok(lock_guard) => {
                test_fn();
            },
            Err(poisoned_lock) => {
                RUN_LOCK.clear_poison();
                let lock_guard = poisoned_lock.into_inner();
                test_fn();
            },
        }
    }

    // #[test]
    // #[should_panic]
    // #[cfg(all(feature = "strict", feature = "u32_index"))]
    // fn test_u32_overflow_panic() {
    //     reset_rolling_idx();
    //     for _ in 0..5_000_000_000 {
    //         let _ = rolling_idx();
    //     }
    // }

    // #[test]
    // #[should_panic]
    // #[cfg(all(feature = "strict", feature = "u64_index"))]
    // fn test_u64_overflow_panic() {
    //     reset_rolling_idx();
    //     for _ in 0..18_000_000_000_000_000_000 {
    //         let _ = rolling_idx();
    //     }
    // }

    #[test]
    #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics"))]
    fn test_arithmetic_operations_ruids() {
        let _lock_res = RUN_LOCK.lock();
        let test_fn = || {
            reset_rolling_idx();

            let mut id1 = RUID::new();
            let mut id2 = RUID::new();

            id1.__value = 6; // Use fallback values for testing
            id2.__value = 3;

            let sum = id1 + id2;
            assert_eq!(sum.__value, 9, "Sum does not match");

            let diff = id1 - id2;
            assert_eq!(diff.__value, 3, "Difference does not match");

            let product = id1 * id2;
            assert_eq!(product.__value, 18, "Product does not match");

            let quotient = id1 / id2;
            assert_eq!(quotient.__value, 2, "Quotient does not match");

            let remainder = id1 % id2;
            assert_eq!(remainder.__value, 0, "Remainder does not match");
        };

        match _lock_res {
            Ok(lock_guard) => {
                test_fn();
            },
            Err(poisoned_lock) => {
                RUN_LOCK.clear_poison();
                let lock_guard = poisoned_lock.into_inner();
                test_fn();
            },
        }
    }

    #[test]
    #[cfg(all(feature = "ruid_type", feature = "allow_arithmetics", not(feature = "strict")))]
    fn test_arithmetic_operations_mixed() {
        let _lock_res = RUN_LOCK.lock();
        let test_fn = || {
            reset_rolling_idx();

            let mut id1 = RUID::new();
            let i = 2;

            id1.__value = 6; // Use fallback value for testing

            let sum = id1 + i;
            assert_eq!(sum.__value, 8, "Sum does not match");

            let diff = id1 - i;
            assert_eq!(diff.__value, 4, "Difference does not match");

            let product = id1 * i;
            assert_eq!(product.__value, 12, "Product does not match");

            let quotient = id1 / i;
            assert_eq!(quotient.__value, 3, "Quotient does not match");

            let remainder = id1 % i;
            assert_eq!(remainder.__value, 0, "Remainder does not match");
        };

        match _lock_res {
            Ok(lock_guard) => {
                test_fn();
            },
            Err(poisoned_lock) => {
                RUN_LOCK.clear_poison();
                let lock_guard = poisoned_lock.into_inner();
                test_fn();
            },
        }
    }
}