From c88f10bac2b9d0ea056d5a4e40db959969dc6e61 Mon Sep 17 00:00:00 2001 From: automated-signal <37887102+automated-signal@users.noreply.github.com> Date: Tue, 22 Feb 2022 18:39:03 -0800 Subject: [PATCH] Improve conversion between typed arrays Co-authored-by: Fedor Indutny <79877362+indutny-signal@users.noreply.github.com> --- ts/Crypto.ts | 7 ++++++- ts/test-electron/Crypto_test.ts | 6 ++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/ts/Crypto.ts b/ts/Crypto.ts index ab4c0d1c9..3a4008d46 100644 --- a/ts/Crypto.ts +++ b/ts/Crypto.ts @@ -35,7 +35,12 @@ export type EncryptedAttachment = { // Generate a number between zero and 16383 export function generateRegistrationId(): number { - const id = new Uint16Array(getRandomBytes(2))[0]; + const bytes = getRandomBytes(2); + const id = new Uint16Array( + bytes.buffer, + bytes.byteOffset, + bytes.byteLength / 2 + )[0]; // eslint-disable-next-line no-bitwise return id & 0x3fff; diff --git a/ts/test-electron/Crypto_test.ts b/ts/test-electron/Crypto_test.ts index 79162fafc..8c6d1f464 100644 --- a/ts/test-electron/Crypto_test.ts +++ b/ts/test-electron/Crypto_test.ts @@ -165,12 +165,18 @@ describe('Crypto', () => { describe('generateRegistrationId', () => { it('generates an integer between 0 and 16383 (inclusive)', () => { + let max = 0; for (let i = 0; i < 100; i += 1) { const id = generateRegistrationId(); assert.isAtLeast(id, 0); assert.isAtMost(id, 16383); assert(Number.isInteger(id)); + + max = Math.max(max, id); } + + // Probability of this being false is ~ 10^{-181} + assert.isAtLeast(max, 0x100); }); });