From 0740e4827a162a492978587c49e95ccd067e5011 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCrg=C3=BCn=20Day=C4=B1o=C4=9Flu?= Date: Sat, 16 Mar 2024 22:59:45 +0100 Subject: [PATCH] perf: refactor parts of StreamSearch (#148) * move to class * format * small refactor * simplify check * space * simplify check * simplify check * refactor * simplify * put back license * remove duplicate subtraction * refactor * readability * revert class refactor * remove unnecessary subtraction * simplify * imports --- deps/streamsearch/sbmh.js | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/deps/streamsearch/sbmh.js b/deps/streamsearch/sbmh.js index b90c0e8..b967365 100644 --- a/deps/streamsearch/sbmh.js +++ b/deps/streamsearch/sbmh.js @@ -26,8 +26,9 @@ * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool */ -const EventEmitter = require('node:events').EventEmitter -const inherits = require('node:util').inherits + +const { EventEmitter } = require('node:events') +const { inherits } = require('node:util') function SBMH (needle) { if (typeof needle === 'string') { @@ -154,9 +155,8 @@ SBMH.prototype._sbmh_feed = function (data) { this.emit('info', false, this._lookbehind, 0, bytesToCutOff) } - this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, - this._lookbehind_size - bytesToCutOff) this._lookbehind_size -= bytesToCutOff + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, this._lookbehind_size) data.copy(this._lookbehind, this._lookbehind_size) this._lookbehind_size += len @@ -166,20 +166,18 @@ SBMH.prototype._sbmh_feed = function (data) { } } - pos += (pos >= 0) * this._bufpos - // Lookbehind buffer is now empty. We only need to check if the // needle is in the haystack. - if (data.indexOf(needle, pos) !== -1) { - pos = data.indexOf(needle, pos) + pos = data.indexOf(needle, pos + ((pos >= 0) * this._bufpos)) + + if (pos !== -1) { ++this.matches if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } - return (this._bufpos = pos + needleLength) - } else { - pos = len - needleLength } + pos = len - needleLength + // There was no match. If there's trailing haystack data that we cannot // match yet using the Boyer-Moore-Horspool algorithm (because the trailing // data is less than the needle size) then match using a modified @@ -190,12 +188,10 @@ SBMH.prototype._sbmh_feed = function (data) { pos < len && ( data[pos] !== needle[0] || - ( - (Buffer.compare( - data.subarray(pos, pos + len - pos), - needle.subarray(0, len - pos) - ) !== 0) - ) + Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0 ) ) { ++pos @@ -213,7 +209,7 @@ SBMH.prototype._sbmh_feed = function (data) { } SBMH.prototype._sbmh_lookup_char = function (data, pos) { - return (pos < 0) + return pos < 0 ? this._lookbehind[this._lookbehind_size + pos] : data[pos] }