0
Fork 0
mirror of https://github.com/penpot/penpot.git synced 2025-02-13 02:28:18 -05:00

🎉 Add fill method to rng-impl ns.

This commit is contained in:
Andrey Antukh 2019-12-12 01:01:12 +01:00
parent 4c5b41b6b2
commit 17b91b9368

View file

@ -19,6 +19,11 @@ goog.scope(function() {
if (cljs.core._STAR_target_STAR_ === "nodejs") { if (cljs.core._STAR_target_STAR_ === "nodejs") {
const crypto = require("crypto"); const crypto = require("crypto");
self.fill = function(buf) {
crypto.randomFillSync(buf);
return buf;
};
self.getBytes = function(n) { self.getBytes = function(n) {
return crypto.randomBytes(n); return crypto.randomBytes(n);
}; };
@ -27,6 +32,12 @@ goog.scope(function() {
// Check if whatwg rng is available (high quality); // Check if whatwg rng is available (high quality);
else if (global.crypto !== undefined && else if (global.crypto !== undefined &&
global.crypto.getRandomValues !== undefined) { global.crypto.getRandomValues !== undefined) {
self.fill = function(buf) {
global.crypto.getRandomValues(buf);
return buf;
};
self.getBytes = function(n) { self.getBytes = function(n) {
const buf = new Uint8Array(16); const buf = new Uint8Array(16);
global.crypto.getRandomValues(buf); global.crypto.getRandomValues(buf);
@ -37,6 +48,16 @@ goog.scope(function() {
// Switch Back to the Math.random (low quality); // Switch Back to the Math.random (low quality);
else { else {
console.warn("No high quality RNG available, switching back to Math.random."); console.warn("No high quality RNG available, switching back to Math.random.");
self.fill = function(buf) {
for (let i = 0, r; i < buf.length; i++) {
if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; }
buf[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return buf;
};
self.getBytes = function(n) { self.getBytes = function(n) {
const buf = new Array(n); const buf = new Array(n);
for (let i = 0, r; i < n; i++) { for (let i = 0, r; i < n; i++) {