From 7bfa302b75c2450a872dc6b5de0002a9c7959ea9 Mon Sep 17 00:00:00 2001 From: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com> Date: Wed, 14 Sep 2022 04:12:32 -0700 Subject: Make `crypto.getRandomValues()` faster + fix > 1 byte/element typed arrays Fix crypto.getRandomValues() with > 1 byte element typed arrays Fixes https://github.com/oven-sh/bun/issues/1237 --- test/bun.js/web-globals.test.js | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) (limited to 'test/bun.js/web-globals.test.js') diff --git a/test/bun.js/web-globals.test.js b/test/bun.js/web-globals.test.js index ac7c22e84..178f5dd00 100644 --- a/test/bun.js/web-globals.test.js +++ b/test/bun.js/web-globals.test.js @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, it, test } from "bun:test"; test("exists", () => { expect(typeof URL !== "undefined").toBe(true); @@ -44,3 +44,39 @@ test("MessageEvent", () => { target.dispatchEvent(event); expect(called).toBe(true); }); + +it("crypto.getRandomValues", () => { + var foo = new Uint8Array(32); + + // run it once + var array = crypto.getRandomValues(foo); + expect(array).toBe(foo); + expect(array.reduce((sum, a) => (sum += a === 0), 0) != foo.length).toBe( + true + ); + + // run it again to check that the fast path works + for (var i = 0; i < 9000; i++) { + var array = crypto.getRandomValues(foo); + expect(array).toBe(foo); + } +}); + +it("crypto.randomUUID", () => { + var uuid = crypto.randomUUID(); + expect(uuid.length).toBe(36); + expect(uuid[8]).toBe("-"); + expect(uuid[13]).toBe("-"); + expect(uuid[18]).toBe("-"); + expect(uuid[23]).toBe("-"); + + // check that the fast path works + for (let i = 0; i < 9000; i++) { + var uuid2 = crypto.randomUUID(); + expect(uuid2.length).toBe(36); + expect(uuid2[8]).toBe("-"); + expect(uuid2[13]).toBe("-"); + expect(uuid2[18]).toBe("-"); + expect(uuid2[23]).toBe("-"); + } +}); -- cgit v1.2.3