summaryrefslogtreecommitdiff
path: root/ext/node/crypto/mod.rs
diff options
context:
space:
mode:
authorLevente Kurusa <lkurusa@kernelstuff.org>2023-04-12 02:57:57 +0200
committerGitHub <noreply@github.com>2023-04-12 02:57:57 +0200
commit65b0d2316d9c05c12eccd4bb7821598af3085ad0 (patch)
tree8452365cbb20b3d9992afe9b2c7095a430e6b277 /ext/node/crypto/mod.rs
parent8820f6e922d3332d0fdd035b504897503d4cdf3a (diff)
refactor(node/crypto): port polyfill to Rust for randomInt, randomFill, randomFillSync (#18658)
Pretty much as per the title, I'd welcome some feedback especially around the array/buffer handling in the two randomFill functions.
Diffstat (limited to 'ext/node/crypto/mod.rs')
-rw-r--r--ext/node/crypto/mod.rs12
1 files changed, 12 insertions, 0 deletions
diff --git a/ext/node/crypto/mod.rs b/ext/node/crypto/mod.rs
index 55a7a5870..f818b96af 100644
--- a/ext/node/crypto/mod.rs
+++ b/ext/node/crypto/mod.rs
@@ -9,6 +9,8 @@ use deno_core::StringOrBuffer;
use deno_core::ZeroCopyBuf;
use hkdf::Hkdf;
use num_bigint::BigInt;
+use rand::distributions::Distribution;
+use rand::distributions::Uniform;
use rand::Rng;
use std::future::Future;
use std::rc::Rc;
@@ -478,3 +480,13 @@ pub async fn op_node_hkdf_async(
})
.await?
}
+
+#[op]
+pub fn op_node_random_int(min: i32, max: i32) -> Result<i32, AnyError> {
+ let mut rng = rand::thread_rng();
+ // Uniform distribution is required to avoid Modulo Bias
+ // https://en.wikipedia.org/wiki/Fisher–Yates_shuffle#Modulo_bias
+ let dist = Uniform::from(min..max);
+
+ Ok(dist.sample(&mut rng))
+}