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
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![allow(unknown_lints)]
#![allow(clippy::manual_let_else)]
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![warn(missing_copy_implementations)]
#![warn(rust_2018_idioms)]
#![warn(rust_2021_compatibility)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unused_qualifications)]
#![warn(variant_size_differences)]
#![forbid(unsafe_code)]
// Enable feature callouts in generated documentation:
// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
//
// This approach is borrowed from tokio.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_alias))]

//! An implementation of [Ruby's pseudo-random number generator][ruby-random],
//! or PRNG.
//!
//! The PRNG produces a deterministic sequence of bits which approximate true
//! randomness. The sequence may be represented by integers, floats, or binary
//! strings.
//!
//! The generator may be initialized with either a system-generated or
//! user-supplied seed value.
//!
//! PRNGs are currently implemented as a modified Mersenne Twister with a period
//! of 2**19937-1.
//!
//! # Implementation notes
//!
//! This RNG reproduces the same random bytes and floats as MRI. It may differ
//! when returning elements confined to a distribution.
//!
//! # Examples
//!
//! Generate integers:
//!
//! ```
//! use spinoso_random::Random;
//!
//! let seed = [627457_u32, 697550, 16438, 41926];
//! let mut random = Random::with_array_seed(seed);
//! let rand = random.next_int32();
//! ```
//!
//! Generate random numbers in a range:
//!
//! ```
//! # #[cfg(feature = "rand-method")]
//! # fn example() -> Result<(), spinoso_random::Error> {
//! use spinoso_random::{rand, Max, Rand, Random};
//!
//! let mut random = Random::new()?;
//! let max = Max::Integer(10);
//! let mut rand = rand(&mut random, max)?;
//! assert!(matches!(rand, Rand::Integer(x) if x < 10));
//! # Ok(())
//! # }
//! # #[cfg(feature = "rand-method")]
//! # example().unwrap();
//! ```
//!
//! # `no_std`
//!
//! This crate is `no_std` compatible when built without the `std` feature. This
//! crate does not depend on [`alloc`].
//!
//! # Crate features
//!
//! All features are enabled by default.
//!
//! - **rand-method** - Enables range sampling methods for the [`rand()`]
//!   function. Activating this feature also activates the **rand_core**
//!   feature. Dropping this feature removes the [`rand`] dependency.
//! - **rand_core** - Enables implementations of [`RngCore`] on the [`Random`]
//!   type. Dropping this feature removes the [`rand_core`] dependency.
//! - **std** - Enables a dependency on the Rust Standard Library. Activating
//!   this feature enables [`std::error::Error`] impls on error types in this
//!   crate.
//!
#![cfg_attr(
    not(feature = "std"),
    doc = "[`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html"
)]
#![cfg_attr(feature = "rand_core", doc = "[`RngCore`]: rand_core::RngCore")]
#![cfg_attr(
    not(feature = "rand_core"),
    doc = "[`RngCore`]: https://docs.rs/rand_core/latest/rand_core/trait.RngCore.html"
)]
#![cfg_attr(feature = "rand_core", doc = "[`rand_core`]: ::rand_core")]
#![cfg_attr(
    not(feature = "rand_core"),
    doc = "[`rand_core`]: https://docs.rs/rand_core/latest/rand_core/"
)]
#![cfg_attr(feature = "rand-method", doc = "[`rand`]: ::rand")]
#![cfg_attr(not(feature = "rand-method"), doc = "[`rand`]: https://docs.rs/rand/latest/rand/")]
#![cfg_attr(
    not(feature = "rand-method"),
    doc = "[`rand()`]: https://artichoke.github.io/artichoke/spinoso_random/fn.rand.html"
)]
//! [ruby-random]: https://ruby-doc.org/core-3.1.2/Random.html
//! [`alloc`]: https://doc.rust-lang.org/alloc/

#![no_std]

// Ensure code blocks in `README.md` compile
#[cfg(all(feature = "rand-method", doctest))]
#[doc = include_str!("../README.md")]
mod readme {}

extern crate alloc;

#[cfg(any(feature = "std", test, doctest))]
extern crate std;

use core::fmt;
#[cfg(feature = "std")]
use std::error;

#[cfg(feature = "rand-method")]
mod rand;
mod random;
mod urandom;

pub use random::{new_seed, seed_to_key, Random};
pub use urandom::urandom;

#[cfg(feature = "rand-method")]
pub use self::rand::{rand, Max, Rand};

/// Sum type of all errors possibly returned from `Random` functions.
///
/// Random functions in `spinoso-random` return errors in the following
/// conditions:
///
/// - The platform source of cryptographic randomness is unavailable.
/// - The platform source of cryptographic randomness does not have sufficient
///   entropy to return the requested bytes.
/// - Constraints for bounding random numbers are invalid.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum Error {
    #[cfg_attr(
        feature = "rand-method",
        doc = "Error that indicates [`rand()`] was passed an invalid constraint."
    )]
    ///
    /// See [`ArgumentError`].
    Argument(ArgumentError),
    /// Error that indicates that [`Random::new`] failed to generate a random
    /// seed.
    ///
    /// See [`InitializeError`].
    Initialize(InitializeError),
    /// Error that indicates that [`new_seed`] failed to generate a random seed.
    ///
    /// See [`NewSeedError`].
    NewSeed(NewSeedError),
    /// Error that indicates that [`urandom()`] failed to generate the requested
    /// random bytes from the platform source of randomness.
    ///
    /// See [`UrandomError`].
    Urandom(UrandomError),
}

impl From<ArgumentError> for Error {
    #[inline]
    fn from(err: ArgumentError) -> Self {
        Self::Argument(err)
    }
}

impl From<InitializeError> for Error {
    #[inline]
    fn from(err: InitializeError) -> Self {
        Self::Initialize(err)
    }
}

impl From<NewSeedError> for Error {
    #[inline]
    fn from(err: NewSeedError) -> Self {
        Self::NewSeed(err)
    }
}

impl From<UrandomError> for Error {
    #[inline]
    fn from(err: UrandomError) -> Self {
        Self::Urandom(err)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Random error")
    }
}

#[cfg(feature = "std")]
impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Self::Argument(ref err) => Some(err),
            Self::Initialize(ref err) => Some(err),
            Self::NewSeed(ref err) => Some(err),
            Self::Urandom(ref err) => Some(err),
        }
    }
}

/// Error that indicates a `Random` random number generator failed to
/// initialize.
///
/// When initializing an [`Random`] with a random seed, gathering entropy from
/// the host system can fail.
///
/// This error corresponds to the [Ruby `RuntimeError` Exception class].
///
/// # Examples
///
/// ```
/// use spinoso_random::InitializeError;
///
/// let err = InitializeError::new();
/// assert_eq!(err.message(), "failed to get urandom");
/// ```
///
/// [Ruby `RuntimeError` Exception class]: https://ruby-doc.org/core-3.1.2/RuntimeError.html
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct InitializeError {
    _private: (),
}

impl InitializeError {
    /// Construct a new, default initialize error.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::InitializeError;
    ///
    /// const ERR: InitializeError = InitializeError::new();
    /// assert_eq!(ERR.message(), "failed to get urandom");
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self { _private: () }
    }

    /// Retrieve the exception message associated with this initialization
    /// error.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::InitializeError;
    ///
    /// let err = InitializeError::new();
    /// assert_eq!(err.message(), "failed to get urandom");
    /// ```
    #[inline]
    #[must_use]
    pub const fn message(self) -> &'static str {
        "failed to get urandom"
    }
}

impl fmt::Display for InitializeError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())
    }
}

#[cfg(feature = "std")]
impl error::Error for InitializeError {}

/// Error that indicates the system source of cryptographically secure
/// randomness failed to read the requested bytes.
///
/// This can occur if the source is unknown or lacks sufficient entropy.
///
/// This error is returned by [`urandom()`]. See its documentation for more
/// details.
///
/// This error corresponds to the [Ruby `RuntimeError` Exception class].
///
/// # Examples
///
/// ```
/// use spinoso_random::UrandomError;
///
/// let err = UrandomError::new();
/// assert_eq!(err.message(), "failed to get urandom");
/// ```
///
/// [Ruby `RuntimeError` Exception class]: https://ruby-doc.org/core-3.1.2/RuntimeError.html
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct UrandomError {
    _private: (),
}

impl UrandomError {
    /// Construct a new, default urandom error.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::UrandomError;
    ///
    /// const ERR: UrandomError = UrandomError::new();
    /// assert_eq!(ERR.message(), "failed to get urandom");
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self { _private: () }
    }

    /// Retrieve the exception message associated with this urandom error.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::UrandomError;
    ///
    /// let err = UrandomError::new();
    /// assert_eq!(err.message(), "failed to get urandom");
    /// ```
    #[inline]
    #[must_use]
    pub const fn message(self) -> &'static str {
        "failed to get urandom"
    }
}

impl fmt::Display for UrandomError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())
    }
}

#[cfg(feature = "std")]
impl error::Error for UrandomError {}

/// Error that indicates the system source of cryptographically secure
/// randomness failed to read sufficient bytes to create a new seed.
///
/// This can occur if the source is unknown or lacks sufficient entropy.
///
/// This error is returned by [`new_seed`]. See its documentation for more
/// details.
///
/// This error corresponds to the [Ruby `RuntimeError` Exception class].
///
/// # Examples
///
/// ```
/// use spinoso_random::NewSeedError;
///
/// let err = NewSeedError::new();
/// assert_eq!(err.message(), "failed to get urandom");
/// ```
///
/// [Ruby `RuntimeError` Exception class]: https://ruby-doc.org/core-3.1.2/RuntimeError.html
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct NewSeedError {
    _private: (),
}

impl NewSeedError {
    /// Construct a new, default new seed error.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::NewSeedError;
    ///
    /// const ERR: NewSeedError = NewSeedError::new();
    /// assert_eq!(ERR.message(), "failed to get urandom");
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self { _private: () }
    }

    /// Retrieve the exception message associated with this new seed error.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::NewSeedError;
    ///
    /// let err = NewSeedError::new();
    /// assert_eq!(err.message(), "failed to get urandom");
    /// ```
    #[inline]
    #[must_use]
    pub const fn message(self) -> &'static str {
        "failed to get urandom"
    }
}

impl fmt::Display for NewSeedError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())
    }
}

#[cfg(feature = "std")]
impl error::Error for NewSeedError {}

/// Error that indicates a random number could not be generated with the given
/// bounds.
///
#[cfg_attr(
    feature = "rand-method",
    doc = "This error is returned by [`rand()`]. See its documentation for more details."
)]
///
/// This error corresponds to the [Ruby `ArgumentError` Exception class].
///
/// # Examples
///
/// ```
/// use spinoso_random::ArgumentError;
///
/// let err = ArgumentError::new();
/// assert_eq!(err.message(), "ArgumentError");
/// ```
///
/// [Ruby `ArgumentError` Exception class]: https://ruby-doc.org/core-3.1.2/ArgumentError.html
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct ArgumentError(ArgumentErrorInner);

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
enum ArgumentErrorInner {
    Default,
    DomainError,
    #[cfg(feature = "rand-method")]
    #[cfg_attr(docsrs, doc(cfg(feature = "rand-method")))]
    Rand(Max),
}

impl ArgumentError {
    /// Construct a new, default argument error.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::ArgumentError;
    ///
    /// const ERR: ArgumentError = ArgumentError::new();
    /// assert_eq!(ERR.message(), "ArgumentError");
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self(ArgumentErrorInner::Default)
    }

    /// Construct a new domain error.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::ArgumentError;
    ///
    /// const ERR: ArgumentError = ArgumentError::domain_error();
    /// assert_eq!(ERR.message(), "Numerical argument out of domain");
    /// ```
    #[inline]
    #[must_use]
    pub const fn domain_error() -> Self {
        Self(ArgumentErrorInner::DomainError)
    }

    /// Construct a new argument error from an invalid [`Max`] constraint.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::{ArgumentError, Max};
    ///
    /// const ERR: ArgumentError = ArgumentError::with_rand_max(Max::Integer(-1));
    /// assert_eq!(ERR.message(), "invalid argument");
    /// ```
    #[inline]
    #[must_use]
    #[cfg(feature = "rand-method")]
    #[cfg_attr(docsrs, doc(cfg(feature = "rand-method")))]
    pub const fn with_rand_max(max: Max) -> Self {
        Self(ArgumentErrorInner::Rand(max))
    }

    /// Retrieve the exception message associated with this new seed error.
    ///
    #[cfg_attr(feature = "rand-method", doc = "# Implementation notes")]
    #[cfg_attr(
        feature = "rand-method",
        doc = "Argument errors constructed with [`ArgumentError::with_rand_max`] return"
    )]
    #[cfg_attr(
        feature = "rand-method",
        doc = "an incomplete error message. Prefer to use the [`Display`] impl to"
    )]
    #[cfg_attr(feature = "rand-method", doc = "retrieve error messages from [`ArgumentError`].")]
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::ArgumentError;
    ///
    /// let err = ArgumentError::new();
    /// assert_eq!(err.message(), "ArgumentError");
    /// let err = ArgumentError::domain_error();
    /// assert_eq!(err.message(), "Numerical argument out of domain");
    /// ```
    ///
    /// [`Display`]: fmt::Display
    #[inline]
    #[must_use]
    pub const fn message(self) -> &'static str {
        match self.0 {
            ArgumentErrorInner::Default => "ArgumentError",
            ArgumentErrorInner::DomainError => "Numerical argument out of domain",
            #[cfg(feature = "rand-method")]
            ArgumentErrorInner::Rand(_) => "invalid argument",
        }
    }

    /// Return whether this argument error is a domain error.
    ///
    /// Domain errors are typically reported as `Errno::EDOM` in MRI.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::ArgumentError;
    ///
    /// let err = ArgumentError::domain_error();
    /// assert!(err.is_domain_error());
    /// let err = ArgumentError::new();
    /// assert!(!err.is_domain_error());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_domain_error(self) -> bool {
        matches!(self.0, ArgumentErrorInner::DomainError)
    }
}

impl fmt::Display for ArgumentError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            ArgumentErrorInner::Default | ArgumentErrorInner::DomainError => f.write_str(self.message()),
            #[cfg(feature = "rand-method")]
            ArgumentErrorInner::Rand(max) => write!(f, "invalid argument - {max}"),
        }
    }
}

#[cfg(feature = "std")]
impl error::Error for ArgumentError {}