Commit | Line | Data |
---|---|---|
f45b29bf | 1 | import { randomInt } from 'node:crypto' |
0c01f51c | 2 | |
4676a95c | 3 | import { bench, group, run } from 'tatami-ng' |
0c01f51c | 4 | |
f522d7b9 | 5 | import { |
99d76a65 | 6 | secureRandom, |
ebf80fe4 | 7 | secureRandomWithRandomValues, |
95d31631 | 8 | } from './benchmark-utils.mjs' |
aa697b2f | 9 | |
1b7c76c1 | 10 | const maximum = 281474976710655 |
aa697b2f | 11 | |
aa697b2f JB |
12 | /** |
13 | * @param max | |
14 | * @param min | |
7fd91296 | 15 | * @returns |
aa697b2f | 16 | */ |
f10b1da0 | 17 | function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) { |
7e861288 JB |
18 | if (max < min || max < 0 || min < 0) { |
19 | throw new RangeError('Invalid interval') | |
20 | } | |
aa697b2f | 21 | max = Math.floor(max) |
4cc567bb | 22 | if (min !== 0) { |
aa697b2f JB |
23 | min = Math.ceil(min) |
24 | return Math.floor(secureRandom() * (max - min + 1)) + min | |
25 | } | |
26 | return Math.floor(secureRandom() * (max + 1)) | |
27 | } | |
28 | ||
99d76a65 JB |
29 | /** |
30 | * @param max | |
31 | * @param min | |
32 | * @returns | |
33 | */ | |
34 | function getSecureRandomIntegerWithRandomValues ( | |
35 | max = Number.MAX_SAFE_INTEGER, | |
36 | min = 0 | |
37 | ) { | |
38 | if (max < min || max < 0 || min < 0) { | |
39 | throw new RangeError('Invalid interval') | |
40 | } | |
41 | max = Math.floor(max) | |
4cc567bb | 42 | if (min !== 0) { |
99d76a65 JB |
43 | min = Math.ceil(min) |
44 | return Math.floor(secureRandomWithRandomValues() * (max - min + 1)) + min | |
45 | } | |
46 | return Math.floor(secureRandomWithRandomValues() * (max + 1)) | |
47 | } | |
48 | ||
aa697b2f JB |
49 | /** |
50 | * @param max | |
51 | * @param min | |
7fd91296 | 52 | * @returns |
aa697b2f | 53 | */ |
f10b1da0 | 54 | function getRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) { |
7e861288 JB |
55 | if (max < min || max < 0 || min < 0) { |
56 | throw new RangeError('Invalid interval') | |
57 | } | |
aa697b2f | 58 | max = Math.floor(max) |
4cc567bb | 59 | if (min !== 0) { |
aa697b2f JB |
60 | min = Math.ceil(min) |
61 | return Math.floor(Math.random() * (max - min + 1)) + min | |
62 | } | |
63 | return Math.floor(Math.random() * (max + 1)) | |
64 | } | |
65 | ||
ab9a08f3 JB |
66 | group('Random Integer Generator', () => { |
67 | bench('Secure random integer generator', () => { | |
aa697b2f | 68 | getSecureRandomInteger(maximum) |
ab9a08f3 JB |
69 | }) |
70 | bench('Secure random with getRandomValues() integer generator', () => { | |
71 | getSecureRandomIntegerWithRandomValues(maximum) | |
72 | }) | |
73 | bench('Crypto random integer generator', () => { | |
1b7c76c1 | 74 | randomInt(maximum) |
ab9a08f3 JB |
75 | }) |
76 | bench('Math random integer generator', () => { | |
aa697b2f | 77 | getRandomInteger(maximum) |
fb341cfe | 78 | }) |
ab9a08f3 JB |
79 | }) |
80 | ||
81 | await run({ | |
ebf80fe4 | 82 | units: true, |
ab9a08f3 | 83 | }) |