Improve conversion between typed arrays
This commit is contained in:
parent
5d035dff86
commit
5453d10572
2 changed files with 12 additions and 1 deletions
|
@ -35,7 +35,12 @@ export type EncryptedAttachment = {
|
||||||
|
|
||||||
// Generate a number between zero and 16383
|
// Generate a number between zero and 16383
|
||||||
export function generateRegistrationId(): number {
|
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
|
// eslint-disable-next-line no-bitwise
|
||||||
return id & 0x3fff;
|
return id & 0x3fff;
|
||||||
|
|
|
@ -165,12 +165,18 @@ describe('Crypto', () => {
|
||||||
|
|
||||||
describe('generateRegistrationId', () => {
|
describe('generateRegistrationId', () => {
|
||||||
it('generates an integer between 0 and 16383 (inclusive)', () => {
|
it('generates an integer between 0 and 16383 (inclusive)', () => {
|
||||||
|
let max = 0;
|
||||||
for (let i = 0; i < 100; i += 1) {
|
for (let i = 0; i < 100; i += 1) {
|
||||||
const id = generateRegistrationId();
|
const id = generateRegistrationId();
|
||||||
assert.isAtLeast(id, 0);
|
assert.isAtLeast(id, 0);
|
||||||
assert.isAtMost(id, 16383);
|
assert.isAtMost(id, 16383);
|
||||||
assert(Number.isInteger(id));
|
assert(Number.isInteger(id));
|
||||||
|
|
||||||
|
max = Math.max(max, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Probability of this being false is ~ 10^{-181}
|
||||||
|
assert.isAtLeast(max, 0x100);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue