-
-
Notifications
You must be signed in to change notification settings - Fork 443
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
118 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
// Copyright 2018 Developers of the Rand project. | ||
// | ||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | ||
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license | ||
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your | ||
// option. This file may not be copied, modified, or distributed | ||
// except according to those terms. | ||
|
||
//! Global random number generator | ||
use std::fmt; | ||
use std::sync::{Mutex, MutexGuard}; | ||
|
||
use super::std::Core; | ||
use crate::rngs::adapter::ReseedingRng; | ||
use crate::rngs::OsRng; | ||
use crate::{CryptoRng, Error, RngCore, SeedableRng}; | ||
|
||
// Number of generated bytes after which to reseed `GlobalRng`. | ||
const GLOBAL_RNG_RESEED_THRESHOLD: u64 = 1024 * 64; | ||
|
||
/// A reference to the global generator | ||
/// | ||
/// This locks the global generator until dropped. | ||
#[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))))] | ||
pub struct GlobalRng<'a> { | ||
lock: MutexGuard<'a, Option<ReseedingRng<Core, OsRng>>>, | ||
} | ||
|
||
/// Debug implementation does not leak internal state | ||
impl<'a> fmt::Debug for GlobalRng<'a> { | ||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||
write!(fmt, "GlobalRng {{ .. }}") | ||
} | ||
} | ||
|
||
static GLOBAL_RNG_KEY: Mutex<Option<ReseedingRng<Core, OsRng>>> = Mutex::new(None); | ||
|
||
/// Access the global generator | ||
/// | ||
/// Locks until release | ||
#[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))))] | ||
pub fn global_rng<'a>() -> GlobalRng<'a> { | ||
let mut lock = GLOBAL_RNG_KEY.lock().unwrap(); | ||
|
||
if lock.is_none() { | ||
let r = Core::from_rng(OsRng).unwrap_or_else(|err| | ||
panic!("could not initialize global_rng: {}", err)); | ||
let rng = ReseedingRng::new(r, GLOBAL_RNG_RESEED_THRESHOLD, OsRng); | ||
*lock = Some(rng); | ||
} | ||
|
||
assert!(lock.is_some()); | ||
GlobalRng { lock } | ||
} | ||
|
||
// impl<'a> Default for GlobalRng<'a> { | ||
// fn default() -> GlobalRng { | ||
// global_rng() | ||
// } | ||
// } | ||
|
||
impl<'a> RngCore for GlobalRng<'a> { | ||
#[inline(always)] | ||
fn next_u32(&mut self) -> u32 { | ||
// SAFETY: We ensure lock.is_some() before constructing GlobalRng | ||
let rng = unsafe { self.lock.as_mut().unwrap_unchecked() }; | ||
rng.next_u32() | ||
} | ||
|
||
#[inline(always)] | ||
fn next_u64(&mut self) -> u64 { | ||
// SAFETY: We ensure lock.is_some() before constructing GlobalRng | ||
let rng = unsafe { self.lock.as_mut().unwrap_unchecked() }; | ||
rng.next_u64() | ||
} | ||
|
||
fn fill_bytes(&mut self, dest: &mut [u8]) { | ||
// SAFETY: We ensure lock.is_some() before constructing GlobalRng | ||
let rng = unsafe { self.lock.as_mut().unwrap_unchecked() }; | ||
rng.fill_bytes(dest) | ||
} | ||
|
||
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { | ||
// SAFETY: We ensure lock.is_some() before constructing GlobalRng | ||
let rng = unsafe { self.lock.as_mut().unwrap_unchecked() }; | ||
rng.try_fill_bytes(dest) | ||
} | ||
} | ||
|
||
impl<'a> CryptoRng for GlobalRng<'a> {} | ||
|
||
|
||
#[cfg(test)] | ||
mod test { | ||
#[test] | ||
fn test_global_rng() { | ||
use crate::Rng; | ||
let mut r = crate::global_rng(); | ||
r.gen::<i32>(); | ||
assert_eq!(r.gen_range(0..1), 0); | ||
} | ||
|
||
#[test] | ||
fn test_debug_output() { | ||
// We don't care about the exact output here, but it must not include | ||
// private CSPRNG state or the cache stored by BlockRng! | ||
assert_eq!(std::format!("{:?}", crate::global_rng()), "GlobalRng { .. }"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters