Skip to content

Commit

Permalink
perf: always check data when looking for last char of needle (#180)
Browse files Browse the repository at this point in the history
* perf: always check data when looking for last char of needle

* add another test

* fix typo
  • Loading branch information
gurgunday authored Dec 10, 2024
1 parent 77cab92 commit fb4d05a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
2 changes: 1 addition & 1 deletion deps/streamsearch/sbmh.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ SBMH.prototype._sbmh_feed = function (data) {
// or until
// the character to look at lies outside the haystack.
while (pos < 0 && pos <= len - needleLength) {
ch = this._sbmh_lookup_char(data, pos + needleLastCharIndex)
ch = data[pos + needleLastCharIndex]

if (
ch === needleLastChar &&
Expand Down
30 changes: 29 additions & 1 deletion test/streamsearch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { test } = require('node:test')
const Streamsearch = require('../deps/streamsearch/sbmh')

test('streamsearch', async t => {
t.plan(18)
t.plan(19)

await t.test('should throw an error if the needle is not a String or Buffer', t => {
t.plan(1)
Expand Down Expand Up @@ -239,6 +239,34 @@ test('streamsearch', async t => {
s.push(chunks[1])
})

await t.test('should process two chunks with an overflowing needle /2', t => {
t.plan(9)
const expected = [
[false, Buffer.from('t\0\0'), 0, 1],
[false, Buffer.from('eshello'), 0, 7]
]
const needle = 'test'
const s = new Streamsearch(needle)
const chunks = [
Buffer.from('t'),
Buffer.from('eshello')
]
let i = 0
s.on('info', (isMatched, data, start, end) => {
t.assert.deepStrictEqual(isMatched, expected[i][0])
t.assert.deepStrictEqual(data, expected[i][1])
t.assert.deepStrictEqual(start, expected[i][2])
t.assert.deepStrictEqual(end, expected[i][3])
i++
if (i >= 2) {
t.assert.ok('pass')
}
})

s.push(chunks[0])
s.push(chunks[1])
})

await t.test('should process two chunks with a potentially overflowing needle', t => {
t.plan(13)

Expand Down

0 comments on commit fb4d05a

Please sign in to comment.