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
//! Random provides an interface to Ruby's pseudo-random number generator, 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.
//!
//! This module implements the [`Random`] singleton object from Ruby Core.
//!
//! In Artichoke, `Random` is implemented using a modified Mersenne Twister that
//! reproduces the same byte and float sequences as the MRI implementation.
//!
//! You can use this class in your application by accessing it directly. As a
//! Core API, it is globally available:
//!
//! ```ruby
//! Random::DEFAULT.bytes(16)
//! r = Random.new(33)
//! r.rand
//! ```
//!
//! [`Random`]: https://ruby-doc.org/core-2.6.3/Random.html

use core::convert::TryFrom;
use core::ops::{Deref, DerefMut};
use spinoso_random::{
    ArgumentError as RandomArgumentError, InitializeError, NewSeedError, Random as SpinosoRandom, UrandomError,
};

use crate::convert::HeapAllocatedData;
use crate::extn::prelude::*;

#[doc(inline)]
pub use spinoso_random::{Max, Rand};

pub mod mruby;
pub mod trampoline;

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
enum Rng {
    Global,
    Value(Box<Random>),
}

impl HeapAllocatedData for Rng {
    const RUBY_TYPE: &'static str = "Random";
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum Seed {
    New(Int),
    None,
}

impl Default for Seed {
    fn default() -> Self {
        Self::new()
    }
}

impl From<Int> for Seed {
    fn from(seed: Int) -> Seed {
        Seed::New(seed)
    }
}

impl Seed {
    /// Construct a an empty seed.
    #[must_use]
    pub const fn new() -> Self {
        Self::None
    }

    #[must_use]
    #[allow(clippy::cast_sign_loss)]
    #[allow(clippy::cast_possible_wrap)]
    pub fn to_mt_seed(self) -> Option<[u32; 4]> {
        if let Self::New(seed) = self {
            let seed = u128::from(seed as u64);
            let seed = seed.to_le_bytes();
            let seed = spinoso_random::seed_to_key(seed);
            Some(seed)
        } else {
            None
        }
    }
}

impl TryConvertMut<Value, Seed> for Artichoke {
    type Error = TypeError;

    fn try_convert_mut(&mut self, value: Value) -> Result<Seed, Self::Error> {
        let seed = value.implicitly_convert_to_int(self)?;
        Ok(Seed::New(seed))
    }
}

impl TryConvertMut<Option<Value>, Seed> for Artichoke {
    type Error = TypeError;

    fn try_convert_mut(&mut self, value: Option<Value>) -> Result<Seed, Self::Error> {
        if let Some(value) = value {
            let seed = self.try_convert_mut(value)?;
            Ok(seed)
        } else {
            Ok(Seed::None)
        }
    }
}

#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_wrap)]
pub fn new_seed() -> Result<Int, Error> {
    // TODO: return a bignum instead of truncating.
    let [a, b, _, _] = spinoso_random::new_seed()?;
    let seed = u64::from(a) << 32 | u64::from(b);
    let seed = seed as Int;
    Ok(seed)
}

pub fn srand(interp: &mut Artichoke, seed: Seed) -> Result<Int, Error> {
    let old_seed = interp.prng()?.seed();
    let new_random = Random::with_array_seed(seed.to_mt_seed())?;
    // "Reseed" by replacing the RNG with a newly seeded one.
    let prng = interp.prng_mut()?;
    *prng = new_random;
    Ok(old_seed)
}

pub fn urandom(size: Int) -> Result<Vec<u8>, Error> {
    match usize::try_from(size) {
        Ok(0) => Ok(Vec::new()),
        Ok(len) => {
            let mut buf = vec![0; len];
            spinoso_random::urandom(&mut buf)?;
            Ok(buf)
        }
        Err(_) => Err(ArgumentError::with_message("negative string size (or size too big)").into()),
    }
}

#[derive(Default, Debug, Clone, Hash, PartialEq, Eq)]
pub struct Random(SpinosoRandom);

impl AsRef<SpinosoRandom> for Random {
    fn as_ref(&self) -> &SpinosoRandom {
        &self.0
    }
}

impl AsMut<SpinosoRandom> for Random {
    fn as_mut(&mut self) -> &mut SpinosoRandom {
        &mut self.0
    }
}

impl Deref for Random {
    type Target = SpinosoRandom;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Random {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl Random {
    pub fn new() -> Result<Self, Error> {
        let random = SpinosoRandom::new()?;
        Ok(Self(random))
    }

    pub fn with_seed(seed: Option<u64>) -> Result<Self, Error> {
        let random = if let Some(seed) = seed {
            if let Ok(seed) = u32::try_from(seed) {
                SpinosoRandom::with_seed(seed)
            } else {
                let seed = u128::from(seed);
                let seed = seed.to_le_bytes();
                SpinosoRandom::with_byte_array_seed(seed)
            }
        } else {
            SpinosoRandom::new()?
        };
        Ok(Self(random))
    }

    pub fn with_array_seed(seed: Option<[u32; 4]>) -> Result<Self, Error> {
        let random = if let Some(seed) = seed {
            SpinosoRandom::with_array_seed(seed)
        } else {
            SpinosoRandom::new()?
        };
        Ok(Self(random))
    }

    pub fn bytes(&mut self, size: Int) -> Result<Vec<u8>, Error> {
        match usize::try_from(size) {
            Ok(0) => Ok(Vec::new()),
            Ok(len) => {
                let mut buf = vec![0; len];
                self.fill_bytes(&mut buf);
                Ok(buf)
            }
            Err(_) => Err(ArgumentError::with_message("negative string size (or size too big)").into()),
        }
    }

    pub fn rand(&mut self, constraint: Max) -> Result<Rand, Error> {
        let rand = spinoso_random::rand(self, constraint)?;
        Ok(rand)
    }

    #[must_use]
    #[allow(clippy::cast_sign_loss)]
    #[allow(clippy::cast_possible_wrap)]
    pub fn seed(&self) -> Int {
        // TODO: return a bignum instead of truncating.
        let [a, b, _, _] = self.as_ref().seed();
        let seed = u64::from(a) << 32 | u64::from(b);
        seed as Int
    }
}

impl TryConvertMut<Value, Max> for Artichoke {
    type Error = Error;

    fn try_convert_mut(&mut self, max: Value) -> Result<Max, Self::Error> {
        let optional: Option<Value> = self.try_convert(max)?;
        self.try_convert_mut(optional)
    }
}

impl TryConvertMut<Option<Value>, Max> for Artichoke {
    type Error = Error;

    fn try_convert_mut(&mut self, max: Option<Value>) -> Result<Max, Self::Error> {
        if let Some(max) = max {
            match max.ruby_type() {
                Ruby::Fixnum => {
                    let max = max.try_into(self)?;
                    Ok(Max::Integer(max))
                }
                Ruby::Float => {
                    let max = max.try_into(self)?;
                    Ok(Max::Float(max))
                }
                _ => {
                    let max = max.implicitly_convert_to_int(self).map_err(|_| {
                        let mut message = b"invalid argument - ".to_vec();
                        message.extend(max.inspect(self));
                        ArgumentError::from(message)
                    })?;
                    Ok(Max::Integer(max))
                }
            }
        } else {
            Ok(Max::None)
        }
    }
}

impl ConvertMut<Rand, Value> for Artichoke {
    fn convert_mut(&mut self, from: Rand) -> Value {
        match from {
            Rand::Integer(num) => self.convert(num),
            Rand::Float(num) => self.convert_mut(num),
        }
    }
}

impl From<RandomArgumentError> for Error {
    fn from(err: RandomArgumentError) -> Self {
        let err = RuntimeError::from(err.to_string());
        err.into()
    }
}

impl From<InitializeError> for Error {
    fn from(err: InitializeError) -> Self {
        let err = RuntimeError::from(err.message());
        err.into()
    }
}

impl From<NewSeedError> for Error {
    fn from(err: NewSeedError) -> Self {
        let err = RuntimeError::from(err.message());
        err.into()
    }
}

impl From<UrandomError> for Error {
    fn from(err: UrandomError) -> Self {
        let err = RuntimeError::from(err.message());
        err.into()
    }
}