Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util: add inspect suffix to BigInt64Array elements #21499

Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,10 @@ function formatNumber(fn, value) {
return fn(`${value}`, 'number');
}

function formatBigInt(fn, value) {
return fn(`${value}n`, 'bigint');
}

function formatPrimitive(fn, value, ctx) {
if (typeof value === 'string') {
if (ctx.compact === false &&
Expand Down Expand Up @@ -761,7 +765,7 @@ function formatPrimitive(fn, value, ctx) {
return formatNumber(fn, value);
// eslint-disable-next-line valid-typeof
if (typeof value === 'bigint')
return fn(`${value}n`, 'bigint');
return formatBigInt(fn, value);
if (typeof value === 'boolean')
return fn(`${value}`, 'boolean');
if (typeof value === 'undefined')
Expand Down Expand Up @@ -897,8 +901,11 @@ function formatTypedArray(ctx, value, recurseTimes, keys) {
const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), value.length);
const remaining = value.length - maxLength;
const output = new Array(maxLength + (remaining > 0 ? 1 : 0));
const elementFormatter = typeof value[0] === 'number' ?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please change it to:

const formatter = len !== 0 && typeof value[0] === 'number' ?
  formatNumber :
  formatBigInt;

Otherwise the OOB access for an empty TypedArray slows down all following calls.

formatNumber :
formatBigInt;
for (var i = 0; i < maxLength; ++i)
output[i] = formatNumber(ctx.stylize, value[i]);
output[i] = elementFormatter(ctx.stylize, value[i]);
if (remaining > 0)
output[i] = `... ${remaining} more item${remaining > 1 ? 's' : ''}`;
if (ctx.showHidden) {
Expand Down
2 changes: 2 additions & 0 deletions test/parallel/test-util-inspect-bigint.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ const { inspect } = require('util');
assert.strictEqual(inspect(1n), '1n');
assert.strictEqual(inspect(Object(-1n)), '[BigInt: -1n]');
assert.strictEqual(inspect(Object(13n)), '[BigInt: 13n]');
assert.strictEqual(inspect(new BigInt64Array([0n])), 'BigInt64Array [ 0n ]');
assert.strictEqual(inspect(new BigUint64Array([0n])), 'BigUint64Array [ 0n ]');