turborand 0.10.1

Fast random number generators
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
use core::cell::UnsafeCell;

#[cfg(feature = "serialize")]
use crate::{Deserialize, Serialize, SerializeTuple, Visitor};

#[cfg_attr(feature = "fmt", derive(Debug))]
pub(crate) struct EntropyBuffer<const SIZE: usize> {
    buffer: UnsafeCell<[u64; SIZE]>,
    cursor: UnsafeCell<usize>,
}

impl<const SIZE: usize> EntropyBuffer<SIZE> {
    #[cfg(feature = "serialize")]
    #[inline]
    fn from_serde(buffer: [u64; SIZE], cursor: usize) -> Self {
        Self {
            buffer: UnsafeCell::new(buffer),
            cursor: UnsafeCell::new(cursor),
        }
    }

    /// Create a new [`EntropyBuffer`].
    #[inline]
    #[must_use]
    pub(crate) const fn new() -> Self {
        Self {
            buffer: UnsafeCell::new([0; SIZE]),
            cursor: UnsafeCell::new(Self::total_bytes()),
        }
    }

    /// Returns the total byte size of the [`EntropyBuffer`], indicating
    /// how much entropy it can store.
    #[inline(always)]
    const fn total_bytes() -> usize {
        SIZE * core::mem::size_of::<u64>()
    }

    /// Returns a reference to the buffer. Meant for avoiding extra copies
    /// from the underlying data.
    ///
    /// **WARNING**: No references should live while an update to the buffer
    /// is made.
    #[inline]
    #[must_use]
    fn get_buffer(&self) -> &[u64; SIZE] {
        // SAFETY: Data is always initialised and no mutable references
        // will exist during the liftime of the returned reference. This
        // can also cause data races if called from different threads, but
        // EntropyBuffer is not Sync, so this won't happen.
        unsafe { &*self.buffer.get() }
    }

    #[inline]
    fn get_cursor(&self) -> usize {
        // SAFETY: Data is always initialised and no mutable references
        // will exist during the liftime of the returned reference. This
        // can also cause data races if called from different threads, but
        // EntropyBuffer is not Sync, so this won't happen.
        unsafe { *self.cursor.get() }
    }

    /// Updates the buffer with a new array value.
    ///
    /// **Warning**: Must not be used while a reference to the buffer lives, else
    /// it won't be sound.
    #[inline]
    fn update_buffer(&self, buffer: [u64; SIZE]) {
        // SAFETY: Data is writable and does not need to be dropped, and
        // the pointer is always valid as it will never point to an allocation
        // nor will it be null. The pointer only lives long enough to perform
        // the write operation and is not exposed from this point. This can also
        // cause data races if called from different threads, but EntropyBuffer
        // is not Sync, so this won't happen.
        unsafe {
            self.buffer.get().write(buffer);
        }
    }

    #[inline]
    fn update_cursor(&self, val: usize) {
        // SAFETY: Data is writable and does not need to be dropped, and
        // the pointer is always valid as it will never point to an allocation
        // nor will it be null. The pointer only lives long enough to perform
        // the write operation and is not exposed from this point. This can also
        // cause data races if called from different threads, but EntropyBuffer
        // is not Sync, so this won't happen. There are no references of the
        // underlying value ever, only returned/copied values, so this is always
        // safe to do.
        unsafe {
            self.cursor.get().write(val);
        }
    }

    /// Checks if the stored entropy has been exhausted, by
    /// seeing if the cursor is the same value as the total
    /// number of bytes available in the buffer.
    #[inline]
    fn is_empty(&self) -> bool {
        Self::total_bytes() == self.get_cursor()
    }

    /// Returns the remaining amount of entropy left in the
    /// buffer, by subtracting the total amount of bytes in
    /// the buffer by the value of the cursor. A zero value
    /// indicates an empty buffer.
    #[inline]
    fn remaining_buffer(&self) -> usize {
        Self::total_bytes() - self.get_cursor()
    }

    /// Updates the [`EntropyBuffer`] with a new buffer state, and
    /// reset the cursor to 0.
    ///
    /// **WARNING**: Must not be used while a reference to buffer is
    /// alive, else this operation will be unsound.
    #[inline]
    fn update_entropy(&self, buffer: [u64; SIZE]) {
        self.update_buffer(buffer);
        self.update_cursor(0);
    }

    /// Fills the incoming mutable byte slice with the available
    /// stored entropy in the internal buffer. Returns the filled
    /// length, which can either be the entire length of the mutable
    /// slice, or the amount filled by the remaining buffer.
    #[inline]
    fn fill_from_buffer(&self, output: &mut [u8], amount: usize) {
        let cursor = self.get_cursor();
        let to = cursor + amount;
        let buffer = bytemuck::cast_slice(self.get_buffer());

        output.copy_from_slice(&buffer[cursor..to]);

        self.update_cursor(to);
    }

    #[inline(always)]
    fn fill_from_source(&self, output: &mut [u8], buffer: [u64; SIZE]) {
        let input: &[u8] = bytemuck::cast_slice(&buffer);

        output.copy_from_slice(input);
    }

    /// Resets the internal buffer and cursor state, clearing any entropy
    /// stored.
    #[inline]
    pub(crate) fn empty_buffer(&self) {
        self.update_buffer([0; SIZE]);
        self.update_cursor(Self::total_bytes());
    }

    /// Fills the incoming mutable byte source with available entropy, consuming
    /// the entropy stored in the buffer until it is exhausted and then pulling in
    /// more entropy when required to refill the buffer and finish filling the input
    /// byte slice.
    #[inline]
    pub(crate) fn fill_bytes_with_source<B: AsMut<[u8]>, S: Fn() -> [u64; SIZE]>(
        &self,
        mut output: B,
        source: S,
    ) {
        let mut output = output.as_mut();

        if output.len() <= self.remaining_buffer() {
            self.fill_from_buffer(output, output.len());
        } else {
            while output.len() >= Self::total_bytes() {
                if self.is_empty() {
                    let (target, remainder) = output.split_at_mut(Self::total_bytes());

                    output = remainder;

                    self.fill_from_source(target, source());
                } else {
                    let length = self.remaining_buffer();

                    let (target, remainder) = output.split_at_mut(length);

                    output = remainder;

                    self.fill_from_buffer(target, length);
                }
            }

            while !output.is_empty() {
                if self.is_empty() {
                    self.update_entropy(source());
                }

                let length = output.len().min(self.remaining_buffer());

                let (target, remainder) = output.split_at_mut(length);

                output = remainder;

                self.fill_from_buffer(target, length);
            }
        }
    }
}

impl<const SIZE: usize> Default for EntropyBuffer<SIZE> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<const SIZE: usize> Clone for EntropyBuffer<SIZE> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            buffer: UnsafeCell::new(*self.get_buffer()),
            cursor: UnsafeCell::new(self.get_cursor()),
        }
    }
}

impl<const SIZE: usize> PartialEq for EntropyBuffer<SIZE> {
    fn eq(&self, other: &Self) -> bool {
        self.get_buffer() == other.get_buffer() && self.get_cursor() == other.get_cursor()
    }
}

impl<const SIZE: usize> Eq for EntropyBuffer<SIZE> {}

#[cfg(feature = "serialize")]
impl<const SIZE: usize> Serialize for EntropyBuffer<SIZE> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut buf = serializer.serialize_tuple(SIZE + 1)?;

        // Insert the buffer as tuple elements
        for val in self.get_buffer().iter() {
            buf.serialize_element(val)?;
        }

        // Add the cursor as the last element of the tuple
        buf.serialize_element(&self.get_cursor())?;

        buf.end()
    }
}

#[cfg(feature = "serialize")]
impl<'de, const SIZE: usize> Deserialize<'de> for EntropyBuffer<SIZE> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct EntropyVisitor<const LENGTH: usize>;

        impl<'de, const LENGTH: usize> Visitor<'de> for EntropyVisitor<LENGTH> {
            type Value = EntropyBuffer<LENGTH>;

            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                write!(formatter, "struct EntropyBuffer<{LENGTH}>")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                let mut buf = [0; LENGTH];
                let mut len: usize = 0;

                for slot in buf.iter_mut() {
                    *slot = seq
                        .next_element()?
                        .ok_or_else(|| serde::de::Error::invalid_length(len, &self))?;
                    len += 1;
                }

                let cursor = seq
                    .next_element()?
                    .ok_or_else(|| serde::de::Error::invalid_length(len, &self))?;

                Ok(EntropyBuffer::from_serde(buf, cursor))
            }
        }

        deserializer.deserialize_tuple(SIZE + 1, EntropyVisitor::<SIZE>)
    }
}

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

    #[test]
    fn initialises_as_empty() {
        let buffer = EntropyBuffer::<8>::new();

        assert!(buffer.is_empty(), "Buffer should be empty on init");
    }

    #[test]
    fn fills_byte_slices() {
        let buffer = EntropyBuffer::<1>::new();

        let source = || [(2 << 32) | 1];

        let mut output = [0u8; 4];

        buffer.fill_bytes_with_source(&mut output, source);

        assert_eq!(&output, &[1, 0, 0, 0]);
        assert_eq!(&buffer.get_cursor(), &4);
        assert!(!buffer.is_empty());

        let mut output = [0u8; 6];

        buffer.fill_bytes_with_source(&mut output, source);

        assert_eq!(&output, &[2, 0, 0, 0, 1, 0]);
        assert_eq!(&buffer.get_cursor(), &2);
        assert!(!buffer.is_empty());
    }

    #[test]
    fn fills_large_byte_slices() {
        let buffer = EntropyBuffer::<4>::new();

        let source = || [1u64, 2, 3, u64::MAX];

        let mut output = [0u8; 40];

        buffer.fill_bytes_with_source(&mut output, source);

        assert_eq!(
            &output,
            &[
                1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 255, 255,
                255, 255, 255, 255, 255, 255, 1, 0, 0, 0, 0, 0, 0, 0
            ]
        );
        assert_eq!(&buffer.get_cursor(), &8);
        assert!(!buffer.is_empty());

        let mut output = [0u8; 40];

        buffer.fill_bytes_with_source(&mut output, source);

        assert_eq!(
            &output,
            &[
                2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255,
                255, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0
            ]
        );
        assert_eq!(&buffer.get_cursor(), &16);
        assert!(!buffer.is_empty());
    }

    #[test]
    fn clone_buffer() {
        let buffer = EntropyBuffer::<1>::new();

        let source = || [(2 << 32) | 1];

        let mut output = [0u8; 4];

        // Modify the buffer to have a new state.
        buffer.fill_bytes_with_source(&mut output, source);

        // Clone the buffer
        let cloned = buffer.clone();

        // Check if the cloned buffer has the same state as the original
        assert_eq!(&buffer, &cloned);
    }

    #[cfg(feature = "serialize")]
    #[test]
    fn serde_tokens() {
        use serde_test::{assert_tokens, Token};

        let buffer = EntropyBuffer::<8>::new();

        assert_tokens(
            &buffer,
            &[
                Token::Tuple { len: 9 },
                Token::U64(0),
                Token::U64(0),
                Token::U64(0),
                Token::U64(0),
                Token::U64(0),
                Token::U64(0),
                Token::U64(0),
                Token::U64(0),
                Token::U64(64),
                Token::TupleEnd,
            ],
        );

        buffer.update_entropy([1, 2, 3, 4, 5, 6, 7, 8]);

        assert_tokens(
            &buffer,
            &[
                Token::Tuple { len: 9 },
                Token::U64(1),
                Token::U64(2),
                Token::U64(3),
                Token::U64(4),
                Token::U64(5),
                Token::U64(6),
                Token::U64(7),
                Token::U64(8),
                Token::U64(0),
                Token::TupleEnd,
            ],
        );
    }
}