Permalink
Browse files

Make .indexOf() accept an index arg.

  • Loading branch information...
1 parent 02c9433 commit 35d70de58a1e8655342339c66c97a5998b7c8e82 @bnoordhuis committed Jun 23, 2012
Showing with 19 additions and 6 deletions.
  1. +3 −3 README.md
  2. +10 −2 buffertools.cc
  3. +1 −1 package.json
  4. +5 −0 test.js
View
@@ -73,10 +73,10 @@ Assumes this buffer contains hexadecimal data (packed, no whitespace)
and decodes it into binary data. Returns a new buffer with the decoded
content. Throws an exception if non-hexadecimal data is encountered.
-### Buffer.indexOf(buffer|string)
+### Buffer.indexOf(buffer|string, [start=0])
-Search this buffer for the first occurrence of the argument.
-Returns the zero-based index or -1 if there is no match.
+Search this buffer for the first occurrence of the argument, starting at
+offset `start`. Returns the zero-based index or -1 if there is no match.
### Buffer.reverse()
View
@@ -162,9 +162,17 @@ struct IndexOfAction: BinaryAction<IndexOfAction> {
const uint8_t* data = (const uint8_t*) Buffer::Data(buffer);
const size_t size = Buffer::Length(buffer);
- const uint8_t* p = boyermoore_search(data, size, data2, size2);
- const ptrdiff_t offset = p ? (p - data) : -1;
+ int32_t start = args[1]->Int32Value();
+
+ if (start < 0)
+ start = size - std::min<size_t>(size, -start);
+ else if (static_cast<size_t>(start) > size)
+ start = size;
+ const uint8_t* p = boyermoore_search(
+ data + start, size - start, data2, size2);
+
+ const ptrdiff_t offset = p ? (p - data) : -1;
return scope.Close(Integer::New(offset));
}
};
View
@@ -1,7 +1,7 @@
{
"name": "buffertools",
"main": "buffertools",
- "version": "1.0.9",
+ "version": "1.1.0",
"keywords": ["buffer", "buffers"],
"description": "Working with node.js buffers made easy.",
"homepage": "https://github.com/bnoordhuis/node-buffertools",
View
@@ -55,6 +55,11 @@ assert.equal(-1, b.indexOf('x'));
assert.equal(7, b.indexOf('w'));
assert.equal(0, b.indexOf('Hello, world!'));
assert.equal(-1, b.indexOf('Hello, world!1'));
+assert.equal(7, b.indexOf('world', 7));
+assert.equal(-1, b.indexOf('world', 8));
+assert.equal(7, b.indexOf('world', -256));
+assert.equal(7, b.indexOf('world', -6));
+assert.equal(-1, b.indexOf('world', -5));
b = new Buffer("\t \r\n");
assert.equal('09200d0a', b.toHex());

0 comments on commit 35d70de

Please sign in to comment.