buffer: fix negative index for large buffers

Fix incorrect negative index results for large buffers.
Add tests for number, Buffer and string searches beyond 2 GiB.

Fixes: https://github.com/nodejs/node/issues/66294

Signed-off-by: dansatch <dansatch98@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/66325
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
This commit is contained in:
Hilary Asogwa authored and Antoine du Hamel committed 2026-11-11 17:27:50 +01:00
1 parent 0522aaebdd
commit db67deb34a
2 files changed
+34 -7

No files matched your search

+7 -7
View File
@@ -1098,8 +1098,8 @@ void IndexOfString(const FunctionCallbackInfo<Value>& args) {
is_forward);
}
args.GetReturnValue().Set(result >= search_end ? -1
: static_cast<int>(result));
args.GetReturnValue().Set(
result >= search_end ? -1 : static_cast<int64_t>(result));
}
void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
@@ -1186,11 +1186,11 @@ void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
is_forward);
}
args.GetReturnValue().Set(result >= search_end ? -1
: static_cast<int>(result));
args.GetReturnValue().Set(
result >= search_end ? -1 : static_cast<int64_t>(result));
}
int32_t IndexOfNumberImpl(Local<Value> buffer_obj,
int64_t IndexOfNumberImpl(Local<Value> buffer_obj,
const uint32_t needle,
const int64_t offset_i64,
const int64_t end_i64,
@@ -1217,7 +1217,7 @@ int32_t IndexOfNumberImpl(Local<Value> buffer_obj,
ptr = nbytes::stringsearch::MemrchrFill(buffer_data, needle, backward_end);
}
const uint8_t* ptr_uint8 = static_cast<const uint8_t*>(ptr);
return ptr != nullptr ? static_cast<int32_t>(ptr_uint8 - buffer_data) : -1;
return ptr != nullptr ? static_cast<int64_t>(ptr_uint8 - buffer_data) : -1;
}
void SlowIndexOfNumber(const FunctionCallbackInfo<Value>& args) {
@@ -1238,7 +1238,7 @@ void SlowIndexOfNumber(const FunctionCallbackInfo<Value>& args) {
IndexOfNumberImpl(buffer_obj, needle, offset_i64, end_i64, is_forward));
}
int32_t FastIndexOfNumber(Local<Value>,
int64_t FastIndexOfNumber(Local<Value>,
Local<Value> buffer_obj,
uint32_t needle,
int64_t offset_i64,
+27
View File
@@ -0,0 +1,27 @@
'use strict';
const common = require('../common');
const assert = require('assert');
common.skipIf32Bits();
const match = 2 ** 31 + 100;
let buffer;
try {
buffer = Buffer.allocUnsafe(match + 1);
} catch (error) {
if (error.code === 'ERR_MEMORY_ALLOCATION_FAILED' ||
/Array buffer allocation failed/.test(error.message)) {
common.skip('insufficient space for Buffer.allocUnsafe');
}
throw error;
}
buffer[match] = 0x0a;
assert.strictEqual(buffer.indexOf(0x0a, -1), match);
assert.strictEqual(buffer.indexOf(Buffer.from([0x0a]), -1), match);
assert.strictEqual(buffer.indexOf('\n', -1), match);
assert.strictEqual(buffer.lastIndexOf(0x0a, -1), match);
assert.strictEqual(buffer.lastIndexOf(Buffer.from([0x0a]), -1), match);
assert.strictEqual(buffer.lastIndexOf('\n', -1), match);