optional_rng.rs
1 // Copyright (c) 2025-2026 ACDC Network 2 // This file is part of the alphavm library. 3 // 4 // Alpha Chain | Delta Chain Protocol 5 // International Monetary Graphite. 6 // 7 // Derived from Aleo (https://aleo.org) and ProvableHQ (https://provable.com). 8 // They built world-class ZK infrastructure. We installed the EASY button. 9 // Their cryptography: elegant. Our modifications: bureaucracy-compatible. 10 // Original brilliance: theirs. Robert's Rules: ours. Bugs: definitely ours. 11 // 12 // Original Aleo/ProvableHQ code subject to Apache 2.0 https://www.apache.org/licenses/LICENSE-2.0 13 // All modifications and new work: CC0 1.0 Universal Public Domain Dedication. 14 // No rights reserved. No permission required. No warranty. No refunds. 15 // 16 // https://creativecommons.org/publicdomain/zero/1.0/ 17 // SPDX-License-Identifier: CC0-1.0 18 19 use core::num::NonZeroU32; 20 use rand::RngCore; 21 22 /// `OptionalRng` is a hack that is necessary because `Option<&mut R>` is not 23 /// implicitly reborrowed like `&mut R` is. This causes problems when a variable 24 /// of type `Option<&mut R>` is moved (eg, in a loop). 25 /// 26 /// To overcome this, we define the wrapper `OptionalRng` here that can be 27 /// borrowed mutably, without fear of being moved. 28 pub struct OptionalRng<R>(pub Option<R>); 29 30 impl<R: RngCore> RngCore for OptionalRng<R> { 31 #[inline] 32 fn next_u32(&mut self) -> u32 { 33 self.0.as_mut().map(|r| r.next_u32()).expect("Rng was invoked in a non-hiding context") 34 } 35 36 #[inline] 37 fn next_u64(&mut self) -> u64 { 38 self.0.as_mut().map(|r| r.next_u64()).expect("Rng was invoked in a non-hiding context") 39 } 40 41 #[inline] 42 fn fill_bytes(&mut self, dest: &mut [u8]) { 43 self.0.as_mut().map(|r| r.fill_bytes(dest)).expect("Rng was invoked in a non-hiding context") 44 } 45 46 #[inline] 47 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { 48 match &mut self.0 { 49 Some(r) => r.try_fill_bytes(dest), 50 None => Err(NonZeroU32::new(rand::Error::CUSTOM_START).unwrap().into()), 51 } 52 } 53 } 54 55 impl<R: RngCore> From<R> for OptionalRng<R> { 56 fn from(other: R) -> Self { 57 Self(Some(other)) 58 } 59 }