mirror of
https://github.com/nodejs/node.git
synced 2026-11-30 11:55:44 -05:00
util: add fast path to stripVTControlCharacters
PR-URL: https://github.com/nodejs/node/pull/61833 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Chemi Atlow <chemi@atlow.co.il> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
This commit is contained in:
1 parent
ec33dd9178
commit
febcecdaaf
3 files changed
+53
No files matched your search
@@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
|
||||
const common = require('../common.js');
|
||||
|
||||
const { stripVTControlCharacters } = require('node:util');
|
||||
const assert = require('node:assert');
|
||||
|
||||
const bench = common.createBenchmark(main, {
|
||||
input: ['noAnsi-short', 'noAnsi-long', 'ansi-short', 'ansi-long'],
|
||||
n: [1e6],
|
||||
});
|
||||
|
||||
function main({ input, n }) {
|
||||
let str;
|
||||
switch (input) {
|
||||
case 'noAnsi-short':
|
||||
str = 'This is a plain text string without any ANSI codes';
|
||||
break;
|
||||
case 'noAnsi-long':
|
||||
str = 'Long plain text without ANSI. '.repeat(333);
|
||||
break;
|
||||
case 'ansi-short':
|
||||
str = '\u001B[31mHello\u001B[39m';
|
||||
break;
|
||||
case 'ansi-long':
|
||||
str = ('\u001B[31m' + 'colored text '.repeat(10) + '\u001B[39m').repeat(10);
|
||||
break;
|
||||
}
|
||||
|
||||
bench.start();
|
||||
for (let i = 0; i < n; i++) {
|
||||
const result = stripVTControlCharacters(str);
|
||||
assert.ok(typeof result === 'string');
|
||||
}
|
||||
bench.end(n);
|
||||
}
|
||||
@@ -3036,6 +3036,13 @@ if (internalBinding('config').hasIntl) {
|
||||
function stripVTControlCharacters(str) {
|
||||
validateString(str, 'str');
|
||||
|
||||
// Short-circuit: all ANSI escape sequences start with either
|
||||
// ESC (\u001B, 7-bit) or CSI (\u009B, 8-bit) introducer.
|
||||
// If neither is present, the string has no VT control characters.
|
||||
if (StringPrototypeIndexOf(str, '\u001B') === -1 &&
|
||||
StringPrototypeIndexOf(str, '\u009B') === -1)
|
||||
return str;
|
||||
|
||||
return RegExpPrototypeSymbolReplace(ansi, str, '');
|
||||
}
|
||||
|
||||
|
||||
@@ -87,3 +87,13 @@ assert.throws(() => {
|
||||
message: 'The "str" argument must be of type string.' +
|
||||
common.invalidArgTypeHelper({})
|
||||
});
|
||||
|
||||
// stripVTControlCharacters: fast path returns input when no ANSI codes
|
||||
assert.strictEqual(util.stripVTControlCharacters('hello'), 'hello');
|
||||
assert.strictEqual(util.stripVTControlCharacters(''), '');
|
||||
|
||||
// stripVTControlCharacters: strips 7-bit ESC sequences
|
||||
assert.strictEqual(util.stripVTControlCharacters('\u001B[31mfoo\u001B[39m'), 'foo');
|
||||
|
||||
// stripVTControlCharacters: strips 8-bit CSI sequences
|
||||
assert.strictEqual(util.stripVTControlCharacters('\u009B31mfoo\u009B39m'), 'foo');
|
||||
Reference in new issue
Block a user