stdrandom 0.3.0-alpha.6

Generate random numbers using only Rust standard library
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! # stdrandom
//!
//! Random numbers generator using only Rust standard library.
//!
//! This library have two types of generators:
//!
//! 1. *fast_* - these generators are fast but less random. They have
//!    progressively lowering entropy because they are based on incrementing
//!    seed. This is weakness of standard Rust library. Better is use one of
//!    these random numbers as seed for more reliable random number generator,
//!    even MCG will do better job.
//! 2. *random_* - these generators needs to spawn a new thread to obtain high
//!    quality randomness. This randomness is pretty good and passes benchmarks
//!    for random number generators with a good score. While it is still not
//!    crypto secure random for using in things like generating key material
//!    it will resist common attacks well.

/*
SPDX-License-Identifier: CC0-1.0 OR Unlicense

This code is released under a "No Copyright" license.

You may use, modify, distribute, and contribute to this code without restriction.
To the extent possible under law, the author(s) of this work waive all copyright and related rights.

Licensed under CC0-1.0 OR Unlicense.

See:
- https://creativecommons.org/publicdomain/zero/1.0/
- https://unlicense.org/
*/

use std::collections::hash_map::RandomState;
use std::hash::BuildHasher;
use std::hash::Hasher;

/// Fills buffer with random bytes generated by the provided function.
///
/// This function splits the buffer into chunks of up to 8 bytes and fills each chunk
/// with bytes derived from a `u64` value generated by `rng()`.
///
/// # Parameters
///
/// - `buffer`: A mutable reference to a slice of bytes (`&mut [u8]`) that will be filled with random data.
/// - `rng`: A mutable function (`FnMut() -> u64`) that generates random `u64` values.
///
/// # Examples
///
/// ```
/// let mut data = [0u8; 16];
/// stdrandom::fill_bytes(&mut data, stdrandom::fast_u64);
///
/// println!("{:?}", data); // Randomized output
/// ```
///
/// ## Safety Notes
///
/// - The randomness depends on the quality of the provided `rng()` function.
pub fn fill_bytes<F>(buffer: &mut [u8], mut rng: F)
where
    F: FnMut() -> u64,
{
    if buffer.is_empty() {
        return; // No need to process an empty slice
    }

    for chunk in buffer.chunks_mut(8) {
        let random_bytes = rng().to_le_bytes();
        chunk.copy_from_slice(&random_bytes[..chunk.len()]);
    }
}

/// Converts a value of type `S` into type `T`.
///
/// Safe conversion is ensured using `TryFrom` trait.
///
/// # Parameters
/// - `input`: The value to be converted.
///
/// # Returns
/// - The successfully converted value of type `T`.
///
/// # Panics
/// - If TryFrom conversion fails, a panic occurs with a detailed error message.
///
#[track_caller]
fn convert_to_t<S, T>(input: S) -> T
where
    T: TryFrom<S>,
    S: std::fmt::Debug + Copy,
{
    match T::try_from(input) {
        Ok(value) => value,
        Err(_) => panic!(
            "Conversion failed: Cannot convert value {:?} of {} type into target type {}",
            input,
            std::any::type_name::<S>(),
            std::any::type_name::<T>()
        ),
    }
}

use std::convert::TryFrom;

/// Fills a slice with generated numbers using the provided generator function.
///
/// This function is **generic** and supports **safe type conversion** via `TryFrom`.
///
/// # Parameters
/// - `buffer`: A mutable slice of type `T` (target type) that will be filled.
/// - `rng`: A function that generates values of type `S` (source type).
///
/// # Example
/// ```
/// fn generate_random() -> u64 { stdrandom::fast_u64() & u32::MAX as u64}
///
/// let mut data = [0u32; 5];
/// stdrandom::fill_numbers(&mut data, generate_random);
/// println!("{:?}", data);
/// ```
#[track_caller]
pub fn fill_numbers<S, T, F>(buffer: &mut [T], mut rng: F)
where
    F: FnMut() -> S,
    T: Copy + TryFrom<S>,
    S: std::fmt::Debug + Copy,
{
    if buffer.is_empty() {
        return; // No need to process an empty slice
    }

    for item in buffer.iter_mut() {
        *item = convert_to_t(rng()); // Ensures safe conversion
    }
}

use std::ops::{Bound, RangeBounds};

/**
  Generates random number in specified range using supplied generator.

  Requested range must fit into target type.
*/
#[track_caller]
pub fn gen_range<R, F, T>(range: R, mut rng: F) -> T
where
    R: RangeBounds<u64>,
    F: FnMut() -> u64,
    T: TryFrom<u64> + 'static, // Enables conversion from `u64` to any smaller integer type (`u32`, `u16`, etc.)
{
    let start = match range.start_bound() {
        Bound::Included(s) => *s,
        _ => panic!("Invalid range: Start must be included."),
    };

    let (end, is_inclusive) = match range.end_bound() {
        Bound::Included(e) => (*e, true),
        Bound::Excluded(e) => (*e, false),
        _ => panic!("Invalid range: End must be bounded."),
    };

    if end < start {
        panic!("Invalid range: End must be greater than or equal to start.");
    }

    let range_size = if is_inclusive {
        if end == u64::MAX {
            if start == 0 {
                u64::MAX
            } else {
                u64::MAX - start + 1
            }
        } else {
            end - start + 1
        }
    } else {
        end - start
    };

    if range_size == 0 {
        panic!("Invalid range: Cannot generate a number from an empty range.");
    }

    let raw_random = rng();
    let mapped_to_zero_based_range = raw_random % range_size;
    let final_result = start + mapped_to_zero_based_range;

    convert_to_t(final_result)
}

/// Fills a mutable slice with random numbers in the specified range using the supplied generator.
///
/// The requested range must fit into the target type of the slice elements.
///
/// # Arguments
///
/// * `slice`: A mutable slice (`&mut [T]`) to be filled with random numbers.
/// * `range`: A range (`R`) specifying the inclusive start and exclusive end for the random numbers.
/// * `rng`: A mutable closure or function (`F`) that generates a `u64` random number.
///
/// # Panics
///
/// This function will panic if:
///
/// * The start of the range is not inclusive.
/// * The end of the range is not bounded (inclusive or exclusive).
/// * The end of the range is less than the start.
/// * The range is empty (start >= end).
/// * A generated `u64` cannot be converted to the target type `T`.
///
/// # Example
///
/// ```
/// use std::collections::hash_map::RandomState;
/// use std::hash::{BuildHasher, Hasher};
/// use std::ops::Range;
///
/// fn fast_u64() -> u64 {
///     let s = RandomState::new();
///     let hasher = s.build_hasher();
///     hasher.finish()
/// }
///
/// fn main() {
///     let mut data = [0u32; 10];
///     let range = 10..20; // Generates numbers from 10 (inclusive) to 20 (exclusive)
///     stdrandom::fill_range(&mut data, range, || fast_u64());
///     println!("Filled data: {:?}", data);
/// }
/// ```
#[track_caller]
pub fn fill_range<R, F, T>(slice: &mut [T], range: R, mut rng: F)
where
    R: RangeBounds<u64>,
    F: FnMut() -> u64,
    T: TryFrom<u64> + Copy,
{
    let start = match range.start_bound() {
        Bound::Included(s) => *s,
        _ => panic!("Invalid range: Start must be included."),
    };

    let (end, is_inclusive) = match range.end_bound() {
        Bound::Included(e) => (*e, true),
        Bound::Excluded(e) => (*e, false),
        _ => panic!("Invalid range: End must be bounded."),
    };

    if end < start {
        panic!("Invalid range: End must be greater than or equal to start.");
    }

    let range_size = if is_inclusive {
        if end == u64::MAX {
            if start == 0 {
                u64::MAX
            } else {
                u64::MAX - start + 1
            }
        } else {
            end - start + 1
        }
    } else {
        end - start
    };

    if range_size == 0 {
        panic!("Invalid range: Cannot generate a number from an empty range.");
    }

    for i in 0..slice.len() {
        let raw_random = rng();
        let mapped_to_zero_based_range = raw_random % range_size;
        let final_result = start + mapped_to_zero_based_range;

        slice[i] = convert_to_t(final_result);
    }
}

/*   fast random numbers   */

/// Generates a `u128` random number using the current thread's `RandomState`s.
///
/// The first number generated in the current thread is more **random**.
/// Subsequent numbers are derived from an **incremented seed**, leading to progressively
/// lower randomness.
///
/// # Returns
/// - A pseudo-random `u128` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_u128();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_u128() -> u128 {
    let low = RandomState::new().build_hasher().finish(); // First random `u64`
    let high = RandomState::new().build_hasher().finish(); // Second random `u64`

    ((high as u128) << 64) | (low as u128) // Combine two `u64` values into a full `u128`
}

/// Generates a `u64` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**. Subsequent numbers
/// are derived from an **incremented seed**, leading to progressively
/// lower randomness.
///
/// # Returns
/// - A pseudo-random `u64` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_u64();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_u64() -> u64 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    hasher.finish()
}

/// Generates a `u32` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**. Subsequent numbers
/// are derived from an **incremented seed**, leading to progressively
/// lower randomness.
///
/// # Returns
/// - A pseudo-random `u32` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_u32();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_u32() -> u32 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() & 0xFFFFFFFF) as u32
}

/// Generates a `u16` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**. Subsequent numbers
/// are derived from an **incremented seed**, leading to progressively
/// lower randomness.
///
/// # Returns
/// - A pseudo-random `u16` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_u16();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_u16() -> u16 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() & 0xFFFF) as u16
}

/// Generates a `u8` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**. Subsequent numbers
/// are derived from an **incremented seed**, leading to progressively
/// lower randomness.
///
/// # Returns
/// - A pseudo-random `u8` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_u8();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_u8() -> u8 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() & 0xFF) as u8
}

/// Generates a `usize` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**. Subsequent numbers
/// are derived from an **incremented seed**, leading to progressively
/// lower randomness.
///
/// # Returns
/// - A pseudo-random `usize` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_usize();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_usize() -> usize {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    hasher.finish() as usize
}

/// Generates a **non-negative** `i128` random number using two separate instances of `RandomState`.
///
/// The first number generated in the thread is more **random**.
/// Subsequent numbers are derived from an **incremented seed**, leading to progressively
/// lower randomness.
///
/// # Returns
/// - A **non-negative** pseudo-random `i128` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_i128();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_i128() -> i128 {
    let low = RandomState::new().build_hasher().finish() as i128; // First random `i64`
    let high = RandomState::new().build_hasher().finish() as i128; // Second random `i64`

    let full_value = (high << 64) | low; // Combine two `i64` values into a full `i128`

    full_value.abs() // Ensure non-negative result
}

/// Generates a **non-negative** `i64` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**, while subsequent numbers
/// are derived from an **incremented seed**, leading to progressively lower randomness.
///
/// # Returns
/// - A **non-negative** pseudo-random `i64` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_i64();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_i64() -> i64 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() & 0x7FFFFFFFFFFFFFFF) as i64 // Mask to ensure non-negative `i64`
}

/// Generates a **non-negative** `i32` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**, while subsequent numbers
/// are derived from an **incremented seed**, leading to progressively lower randomness.
///
/// # Returns
/// - A **non-negative** pseudo-random `i32` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_i32();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_i32() -> i32 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() & 0x7FFFFFFF) as i32 // Mask to ensure non-negative `i32`
}

/// Generates a **non-negative** `i16` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**, while subsequent numbers
/// are derived from an **incremented seed**, leading to progressively lower randomness.
///
/// # Returns
/// - A **non-negative** pseudo-random `i16` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_i16();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_i16() -> i16 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() & 0x7FFF) as i16 // Mask to ensure non-negative `i16`
}

/// Generates a **non-negative** `i8` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**, while subsequent numbers
/// are derived from an **incremented seed**, leading to progressively lower randomness.
///
/// # Returns
/// - A **non-negative** pseudo-random `i8` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_i8();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_i8() -> i8 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() & 0x7F) as i8 // Mask to ensure non-negative `i8`
}

/// Generates a **non-negative** `isize` random number using the current thread's `RandomState`.
///
/// The first number generated in the thread is **random**, while subsequent numbers
/// are derived from an **incremented seed**, leading to progressively lower randomness.
///
/// # Returns
/// - A **non-negative** pseudo-random `isize` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_isize();
/// println!("Generated: {}", random_value);
/// ```
pub fn fast_isize() -> isize {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() & (isize::MAX as u64)) as isize // Mask ensures non-negative `isize`
}

/*   floating point randoms   */

/// Generates a **fast** but lower-entropy `f64` pseudo-random number in the range `[0.0, 1.0)`.
///
/// This function leverages the current thread's `RandomState` to create a hasher.
/// The first number generated in the thread is typically **random**, while subsequent numbers
/// are derived from an **incremented internal seed** within `RandomState`, potentially
/// leading to progressively lower statistical randomness or predictability.
///
/// # Returns
/// - A **non-negative** pseudo-random `f64` number within the half-open interval `[0.0, 1.0)`.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_f64();
/// println!("Generated f64: {}", random_value);
/// ```
pub fn fast_f64() -> f64 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() as f64) / (u64::MAX as f64)
}

/// Generates a **fast** but lower-entropy `f32` pseudo-random number in the range `[0.0, 1.0)`.
///
/// This function leverages the current thread's `RandomState` to create a hasher.
/// The first number generated in the thread is typically **random**, while subsequent numbers
/// are derived from an **incremented internal seed** within `RandomState`, potentially
/// leading to progressively lower statistical randomness or predictability.
///
/// # Returns
/// - A **non-negative** pseudo-random `f32` number within the half-open interval `[0.0, 1.0)`.
///
/// # Example
/// ```
/// let random_value = stdrandom::fast_f32();
/// println!("Generated f32: {}", random_value);
/// ```
pub fn fast_f32() -> f32 {
    let s = RandomState::new();
    let hasher = s.build_hasher();
    (hasher.finish() as f32) / (u64::MAX as f32)
}

/// Generates a **higher entropy** `f64` pseudo-random number in the range `[0.0, 1.0)`.
///
/// This function achieves higher randomness by leveraging a source like `random_u64()`,
/// which is designed to provide better statistical properties and less predictability
/// by generating values in a separate thread.
/// It results in numbers with **significantly higher entropy** compared to `fast_f64()`.
///
/// # Returns
/// - A **non-negative** pseudo-random `f64` number within the half-open interval `[0.0, 1.0)`.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_f64();
/// println!("Generated higher entropy f64: {}", random_value);
/// ```
pub fn random_f64() -> f64 {
    (random_u64() as f64) / (u64::MAX as f64)
}

/// Generates a **higher entropy** `f32` pseudo-random number in the range `[0.0, 1.0)`.
///
/// This function achieves higher randomness by leveraging a source like `random_u64()`,
/// which is designed to provide better statistical properties and less predictability
/// by generating values in a separate thread.
/// It results in numbers with **significantly higher entropy** compared to `fast_f32()`.
///
/// # Returns
/// - A **non-negative** pseudo-random `f32` number within the half-open interval `[0.0, 1.0)`.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_f32();
/// println!("Generated higher entropy f32: {}", random_value);
/// ```
pub fn random_f32() -> f32 {
    (random_u64() as f32) / (u64::MAX as f32)
}

/*   High entropy random numbers   */

/// Generates a higher entropy **random `u128`** number using two separate threads.
///
/// Each thread independently generates a **random `u64`** using `fast_u64()`, ensuring that
/// both the upper and lower halves of the `u128` number are truly randomized.
///
/// # Returns
/// - A high entropy **pseudo-random `u128`** number.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_u128();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_u128() -> u128 {
    // Spawn two independent threads to generate `u64` values separately
    let lower_thread = std::thread::spawn(|| fast_u64());
    let upper_thread = std::thread::spawn(|| fast_u64());

    // Handle potential thread failures
    let low = match lower_thread.join() {
        Ok(value) => value,
        Err(_) => fast_u64(), // Fallback: Generate in the main thread
    };

    let high = match upper_thread.join() {
        Ok(value) => value,
        Err(_) => fast_u64(), // Fallback: Generate in the main thread
    };

    // Combine the two `u64` values into a full `u128`
    ((high as u128) << 64) | (low as u128)
}

/// Generates a **higher entropy** pseudo-random `u64` number.
///
/// This function generates a `u64` pseudo-random number with **higher entropy**
/// compared to `fast_u64()`. It typically achieves this by performing the
/// generation in a separate thread, similar to `random_u32()`.
///
/// The randomness is distributed uniformly across all 64 bits of the generated
/// number, meaning both the lower and upper 32-bit halves of the `u64` are
/// considered equally random.
///
/// # Returns
/// - A pseudo-random `u64` number with higher entropy.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_u64();
/// println!("Generated higher entropy u64: {}", random_value);
/// ```
pub fn random_u64() -> u64 {
    // Generate random number inside the new thread to get unique RandomState
    let handle = std::thread::spawn(|| fast_u64());

    // Handle potential thread failure
    match handle.join() {
        Ok(randomness) => randomness, // Successfully got randomness from the spawned thread
        Err(_) => {
            // eprintln!("Error joining thread, using less random number from current thread.");
            // Fallback: Generate randomness in the main thread
            fast_u64()
        }
    }
}

/// Generates a higher entropy **random `u32` number** in a separate thread.
///
/// The generated number will have **higher randomness** compared to subsequent
/// calls to `fast_u32()` in the same thread.
///
/// # Returns
/// - A **pseudo-random `u32`** number.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_u32();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_u32() -> u32 {
    // Spawn a thread to generate a random `u32`
    let handle = std::thread::spawn(|| fast_u32());

    // Handle potential thread failure
    match handle.join() {
        Ok(randomness) => randomness, // Successfully retrieved randomness
        Err(_) => {
            // eprintln!("Error joining thread, using less random number from current thread.");
            fast_u32() // Fallback: Generate in the main thread
        }
    }
}

/// Generates a higher entropy **random `u16` number** in a separate thread.
///
/// The generated number will have **higher randomness** compared to subsequent
/// calls to `fast_u16()` in the same thread.
///
/// # Returns
/// - A **pseudo-random `u16`** number.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_u16();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_u16() -> u16 {
    let handle = std::thread::spawn(|| fast_u16());

    match handle.join() {
        Ok(randomness) => randomness,
        Err(_) => fast_u16(), // Fallback in case the thread fails
    }
}

/// Generates a higher entropy **random `u8` number** in a separate thread.
///
/// The generated number will have **higher randomness** compared to subsequent
/// calls to `fast_u8()` in the same thread.
///
/// # Returns
/// - A **pseudo-random `u8`** number.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_u8();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_u8() -> u8 {
    let handle = std::thread::spawn(|| fast_u8());

    match handle.join() {
        Ok(randomness) => randomness,
        Err(_) => fast_u8(), // Fallback in case the thread fails
    }
}

/// Generates a **higher entropy** pseudo-random `usize` number.
///
/// This function generates a `usize` pseudo-random number with **higher entropy**
/// compared to `fast_usize()`. It achieves this by performing the generation
/// in a separate thread, which can help mitigate the issues of predictable
/// or lower randomness often associated with sequential calls within the same thread
/// (as seen with `fast_usize()` using `RandomState`).
///
/// In case the thread fails to spawn or join, it gracefully falls back to
/// generating a `usize` number in the current thread using `fast_usize()`,
/// which will have lower entropy.
///
/// # Returns
/// - A pseudo-random `usize` number with higher entropy, or a lower-entropy fallback.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_usize();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_usize() -> usize {
    let handle = std::thread::spawn(|| fast_usize());

    match handle.join() {
        Ok(randomness) => randomness,
        Err(_) => {
            // eprintln!("Error joining thread, using less random number from current thread.");
            fast_usize() // Fallback: Generate in the main thread
        }
    }
}

/// Generates a **higher entropy** pseudo-random `i128` number using two separate threads.
///
/// This function creates a `i128` pseudo-random number with **significantly higher entropy**
/// compared to single-threaded generation methods. It achieves this by concurrently
/// generating the upper 64 bits and lower 64 bits of the `i128` in two distinct threads.
///
/// Each thread independently utilizes a `RandomState` based generator,
/// reducing the predictability and potential for patterns that might emerge from repeated calls
/// to a single-threaded generator within the same thread.
///
/// In case either thread fails to spawn or join, the respective value
/// is generated as a fallback directly in the current thread, which would result in lower entropy.
///
/// # Returns
/// - A **non-negative** pseudo-random `i128` number.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_i128();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_i128() -> i128 {
    // lower thread is using u64 to get full range of values
    let lower_thread = std::thread::spawn(|| fast_u64());
    let upper_thread = std::thread::spawn(|| fast_i64());

    let low = match lower_thread.join() {
        Ok(value) => value as i128,
        Err(_) => fast_u64() as i128,
    };

    let high = match upper_thread.join() {
        Ok(value) => value as i128,
        Err(_) => fast_i64() as i128,
    };

    (high << 64) | low
}

/// Generates a **higher entropy** pseudo-random `i64` number.
///
/// This function generates an `i64` pseudo-random number with **higher entropy**
/// compared to `fast_i64()`. It achieves this by performing the generation
/// in a separate thread, which can help mitigate the issues of predictable
/// or lower randomness often associated with sequential calls within the same thread
/// (as seen with `fast_i64()` using `RandomState`).
///
/// In case the thread fails to spawn or join, it gracefully falls back to
/// generating an `i64` number in the current thread using `fast_i64()`,
/// which will have lower entropy.
///
/// # Returns
/// - A **non-negative** pseudo-random `i64` number with higher entropy, or a lower-entropy fallback.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_i64();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_i64() -> i64 {
    let handle = std::thread::spawn(|| fast_i64());

    match handle.join() {
        Ok(randomness) => randomness,
        Err(_) => fast_i64(),
    }
}

/// Generates a **higher entropy** pseudo-random `i32` number.
///
/// This function generates an `i32` pseudo-random number with **higher entropy**
/// compared to `fast_i32()`. It achieves this by performing the generation
/// in a separate thread, which can help mitigate the issues of predictable
/// or lower randomness often associated with sequential calls within the same thread
/// (as seen with `fast_i32()` using `RandomState`).
///
/// In case the thread fails to spawn or join, it gracefully falls back to
/// generating an `i32` number in the current thread using `fast_i32()`,
/// which will have lower entropy.
///
/// # Returns
/// - A **non-negative** pseudo-random `i32` number with higher entropy, or a lower-entropy fallback.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_i32();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_i32() -> i32 {
    let handle = std::thread::spawn(|| fast_i32());

    match handle.join() {
        Ok(randomness) => randomness,
        Err(_) => fast_i32(),
    }
}

/// Generates a **higher entropy** pseudo-random `i16` number.
///
/// This function generates an `i16` pseudo-random number with **higher entropy**
/// compared to `fast_i16()`. It achieves this by performing the generation
/// in a separate thread, which can help mitigate the issues of predictable
/// or lower randomness often associated with sequential calls within the same thread
/// (as seen with `fast_i16()` using `RandomState`).
///
/// In case the thread fails to spawn or join, it gracefully falls back to
/// generating an `i16` number in the current thread using `fast_i16()`,
/// which will have lower entropy.
///
/// # Returns
/// - A **non-negative** pseudo-random `i16` number with higher entropy, or a lower-entropy fallback.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_i16();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_i16() -> i16 {
    let handle = std::thread::spawn(|| fast_i16());

    match handle.join() {
        Ok(randomness) => randomness,
        Err(_) => fast_i16(),
    }
}

/// Generates a **higher entropy** pseudo-random `i8` number.
///
/// This function generates an `i8` pseudo-random number with **higher entropy**
/// compared to `fast_i8()`. It achieves this by performing the generation
/// in a separate thread, which can help mitigate the issues of predictable
/// or lower randomness often associated with sequential calls within the same thread
/// (as seen with `fast_i8()` using `RandomState`).
///
/// In case the thread fails to spawn or join, it gracefully falls back to
/// generating an `i8` number in the current thread using `fast_i8()`,
/// which will have lower entropy.
///
/// # Returns
/// - A **non-negative** pseudo-random `i8` number with higher entropy, or a lower-entropy fallback.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_i8();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_i8() -> i8 {
    let handle = std::thread::spawn(|| fast_i8());

    match handle.join() {
        Ok(randomness) => randomness,
        Err(_) => fast_i8(),
    }
}

/// Generates a **higher entropy** pseudo-random `isize` number.
///
/// This function generates an `isize` pseudo-random number with **higher entropy**
/// compared to `fast_isize()`. It achieves this by performing the generation
/// in a separate thread, which can help mitigate the issues of predictable
/// or lower randomness often associated with sequential calls within the same thread
/// (as seen with `fast_isize()` using `RandomState`).
///
/// In case the thread fails to spawn or join, it gracefully falls back to
/// generating an `isize` number in the current thread using `fast_isize()`,
/// which will have lower entropy.
///
/// # Returns
/// - A **non-negative** pseudo-random `isize` number with higher entropy, or a lower-entropy fallback.
///
/// # Example
/// ```
/// let random_value = stdrandom::random_isize();
/// println!("Generated: {}", random_value);
/// ```
pub fn random_isize() -> isize {
    let handle = std::thread::spawn(|| fast_isize());

    match handle.join() {
        Ok(randomness) => randomness,
        Err(_) => fast_isize(),
    }
}


#[cfg(test)]
mod basic_tests;

#[cfg(test)]
mod generator_tests;

#[cfg(test)]
mod fillrange_tests;

#[cfg(test)]
mod overflow_tests;

#[cfg(test)]
mod closure_tests;