@@ -13,7 +13,7 @@ use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
13
13
14
14
// Maximum buffer size allowed in `Crypto.getRandomValuesSize` is 65536 bytes.
15
15
// See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
16
- const MAX_BUFFER_SIZE : u16 = 256 ;
16
+ const MAX_BUFFER_SIZE : u32 = 65536 ;
17
17
18
18
pub fn fill_inner ( dest : & mut [ MaybeUninit < u8 > ] ) -> Result < ( ) , Error > {
19
19
CRYPTO . with ( |crypto| {
@@ -24,7 +24,7 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
24
24
25
25
#[ cfg( not( target_feature = "atomics" ) ) ]
26
26
fn inner ( crypto : & Crypto , dest : & mut [ MaybeUninit < u8 > ] ) -> Result < ( ) , Error > {
27
- for chunk in dest. chunks_mut ( MAX_BUFFER_SIZE . into ( ) ) {
27
+ for chunk in dest. chunks_mut ( MAX_BUFFER_SIZE as usize ) {
28
28
if crypto. get_random_values ( chunk) . is_err ( ) {
29
29
return Err ( Error :: WEB_GET_RANDOM_VALUES ) ;
30
30
}
@@ -36,15 +36,19 @@ fn inner(crypto: &Crypto, dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
36
36
fn inner ( crypto : & Crypto , dest : & mut [ MaybeUninit < u8 > ] ) -> Result < ( ) , Error > {
37
37
// getRandomValues does not work with all types of WASM memory,
38
38
// so we initially write to browser memory to avoid exceptions.
39
- let buf = Uint8Array :: new_with_length ( MAX_BUFFER_SIZE . into ( ) ) ;
40
- for chunk in dest. chunks_mut ( MAX_BUFFER_SIZE . into ( ) ) {
39
+ let buf_len = u32:: min (
40
+ dest. len ( ) . try_into ( ) . unwrap_or ( MAX_BUFFER_SIZE ) ,
41
+ MAX_BUFFER_SIZE ,
42
+ ) ;
43
+ let buf = Uint8Array :: new_with_length ( buf_len) ;
44
+ for chunk in dest. chunks_mut ( buf_len as usize ) {
41
45
let chunk_len: u32 = chunk
42
46
. len ( )
43
47
. try_into ( )
44
48
. expect ( "chunk length is bounded by MAX_BUFFER_SIZE" ) ;
45
49
// The chunk can be smaller than buf's length, so we call to
46
50
// JS to create a smaller view of buf without allocation.
47
- let sub_buf = if chunk_len == u32 :: from ( MAX_BUFFER_SIZE ) {
51
+ let sub_buf = if chunk_len == buf_len {
48
52
& buf
49
53
} else {
50
54
& buf. subarray ( 0 , chunk_len)
0 commit comments