Skip to content

Commit

Permalink
Fix indexOf tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Soremwar committed Nov 29, 2021
1 parent 9261f4b commit 1a0948f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
1 change: 1 addition & 0 deletions node/_tools/config.json
Expand Up @@ -18,6 +18,7 @@
"test-buffer-arraybuffer.js",
"test-buffer-bytelength.js",
"test-buffer-from.js",
"test-buffer-indexof.js",
"test-dns-lookup.js",
"test-dns.js",
"test-event-emitter-errors.js",
Expand Down
2 changes: 2 additions & 0 deletions node/_tools/suites/parallel/test-buffer-indexof.js
Expand Up @@ -601,6 +601,8 @@ pattern = reallyLong.slice(0, 2000000); // first 2/5ths.
assert.strictEqual(reallyLong.lastIndexOf(pattern), 0);

// Test truncation of Number arguments to uint8
// TODO(Soremwar)
// Enable once multi byte number search is available
// {
// const buf = Buffer.from('this is a test');
// assert.strictEqual(buf.indexOf(0x6973), 3);
Expand Down
30 changes: 22 additions & 8 deletions node/internal_binding/buffer.ts
@@ -1,6 +1,18 @@
import { Encodings } from "./_node.ts";
import { indexOf } from "../../bytes/mod.ts";

export function numberToBytes(n: number): Uint8Array {
if (n === 0) return new Uint8Array([0]);

const bytes = [];
bytes.unshift(n & 255);
while (n >= 256) {
n = n >>> 8;
bytes.unshift(n & 255);
}
return new Uint8Array(bytes);
}

// TODO(Soremwar)
// Check if offset or buffer can be transform in order to just use std's lastIndexOf directly
// This implementation differs from std's lastIndexOf in the fact that
Expand Down Expand Up @@ -88,24 +100,26 @@ function indexOfBuffer(
return indexOf(targetBuffer, buffer, byteOffset);
}

// TODO(Soremwar)
// Node's implementation is a very obscure algorithm that I haven't been able to crack just yet
function indexOfNumber(
targetBuffer: Uint8Array,
number: number,
byteOffset: number,
forwardDirection: boolean,
) {
if (!forwardDirection) {
return Uint8Array.prototype.lastIndexOf.call(
targetBuffer,
number,
byteOffset,
);
const bytes = numberToBytes(number);

if (bytes.length > 1) {
throw new Error("Multi byte number search is not supported");
}

return Uint8Array.prototype.indexOf.call(
return indexOfBuffer(
targetBuffer,
number,
numberToBytes(number),
byteOffset,
Encodings.UTF8,
forwardDirection,
);
}

Expand Down

0 comments on commit 1a0948f

Please sign in to comment.