Improve conversion between typed arrays

Co-authored-by: Fedor Indutny <79877362+indutny-signal@users.noreply.github.com>
This commit is contained in:
automated-signal 2022-02-22 18:39:03 -08:00 committed by GitHub
parent 733fc56742
commit c88f10bac2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 1 deletions

View File

@ -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;

View File

@ -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);
});
});