Skip to content

Commit 7e44e40

Browse files
committed
Fix buffer length problem
1 parent 5e217a2 commit 7e44e40

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

src/wasm-bindgen.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ use crate::Error;
1010
extern crate std;
1111
use std::thread_local;
1212

13-
use wasm_bindgen::prelude::*;
1413
use js_sys::Uint8Array;
14+
use wasm_bindgen::prelude::*;
1515

1616
// Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
1717
const BROWSER_CRYPTO_BUFFER_SIZE: usize = 256;
@@ -45,10 +45,14 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
4545
}
4646
RngSource::Browser(ctx) => {
4747
for chunk in dest.chunks_mut(BROWSER_CRYPTO_BUFFER_SIZE) {
48-
if ctx.crypto.get_random_values(&ctx.buf).is_err() {
48+
// chunk can be smaller than buf length
49+
// this creates a smaller view to the buf memory without allocation
50+
let sub_buf = ctx.buf.subarray(0, chunk.len() as u32);
51+
52+
if ctx.crypto.get_random_values(&sub_buf).is_err() {
4953
return Err(Error::WEB_GET_RANDOM_VALUES);
5054
}
51-
ctx.buf.copy_to(chunk);
55+
sub_buf.copy_to(chunk);
5256
}
5357
}
5458
};
@@ -71,10 +75,7 @@ fn getrandom_init() -> Result<RngSource, Error> {
7175

7276
let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32);
7377

74-
let ctx = BrowserCryptoContext {
75-
crypto,
76-
buf,
77-
};
78+
let ctx = BrowserCryptoContext { crypto, buf };
7879

7980
return Ok(RngSource::Browser(ctx));
8081
}

0 commit comments

Comments
 (0)