Skip to content

Commit

Permalink
fix(ext/node): use primordials in ext\node\polyfills\internal\crypto\…
Browse files Browse the repository at this point in the history
…_randomInt.ts (#26534)

Towards #24236
  • Loading branch information
mayank-Pareek authored and bartlomieju committed Oct 29, 2024
1 parent b54a46b commit 16f3c31
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions ext/node/polyfills/internal/crypto/_randomInt.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

// TODO(petamoriken): enable prefer-primordials for node polyfills
// deno-lint-ignore-file prefer-primordials

import { op_node_random_int } from "ext:core/ops";
import { primordials } from "ext:core/mod.js";
const {
Error,
MathCeil,
MathFloor,
MathPow,
NumberIsSafeInteger,
RangeError,
} = primordials;

export default function randomInt(max: number): number;
export default function randomInt(min: number, max: number): number;
Expand All @@ -23,7 +29,9 @@ export default function randomInt(
cb?: (err: Error | null, n?: number) => void,
): number | void {
if (typeof max === "number" && typeof min === "number") {
[max, min] = [min, max];
const temp = max;
max = min;
min = temp;
}
if (min === undefined) min = 0;
else if (typeof min === "function") {
Expand All @@ -32,22 +40,22 @@ export default function randomInt(
}

if (
!Number.isSafeInteger(min) ||
typeof max === "number" && !Number.isSafeInteger(max)
!NumberIsSafeInteger(min) ||
typeof max === "number" && !NumberIsSafeInteger(max)
) {
throw new Error("max or min is not a Safe Number");
}

if (max - min > Math.pow(2, 48)) {
if (max - min > MathPow(2, 48)) {
throw new RangeError("max - min should be less than 2^48!");
}

if (min >= max) {
throw new Error("Min is bigger than Max!");
}

min = Math.ceil(min);
max = Math.floor(max);
min = MathCeil(min);
max = MathFloor(max);
const result = op_node_random_int(min, max);

if (cb) {
Expand Down

0 comments on commit 16f3c31

Please sign in to comment.