Skip to content

Commit

Permalink
feat(random): add opt start/end for randomBytes()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 13, 2021
1 parent d6205d7 commit 4d095da
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions packages/random/src/random-bytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,16 @@ import { SYSTEM } from "./system";
*
* @param rnd -
* @param buf -
* @param start -
* @param end -
*/
export const randomBytesFrom = (rnd: IRandom, buf: Uint8Array) => {
for (let i = buf.length; --i >= 0; ) {
export const randomBytesFrom = (
rnd: IRandom,
buf: Uint8Array,
start = 0,
end = buf.length
) => {
for (let i = end; --i >= start; ) {
buf[i] = rnd.int() & 0xff;
}
return buf;
Expand All @@ -20,7 +27,14 @@ export const randomBytesFrom = (rnd: IRandom, buf: Uint8Array) => {
* Fills given byte array with random values. Wrapper for
* `crypto.getRandomValues()` with automatic fallback to using `Math.random` if
* platform doesn't provide global crypto instance.
*
* @param buf -
* @param start -
* @param end -
*/
export const randomBytes = hasCrypto()
? (buf: Uint8Array) => window.crypto.getRandomValues(buf)
: (buf: Uint8Array) => randomBytesFrom(SYSTEM, buf);
? (buf: Uint8Array, start = 0, end = buf.length) => (
window.crypto.getRandomValues(buf.subarray(start, end)), buf
)
: (buf: Uint8Array, start?: number, end?: number) =>
randomBytesFrom(SYSTEM, buf, start, end);

0 comments on commit 4d095da

Please sign in to comment.