Last change
on this file since b738035 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.5 KB
|
Rev | Line | |
---|
[6a3a178] | 1 | module.exports = function bufferIndexOf(buff, search, offset, encoding){
|
---|
| 2 | if (!Buffer.isBuffer(buff)) {
|
---|
| 3 | throw TypeError('buffer is not a buffer');
|
---|
| 4 | }
|
---|
| 5 |
|
---|
| 6 | // allow optional offset when providing an encoding
|
---|
| 7 | if (encoding === undefined && typeof offset === 'string') {
|
---|
| 8 | encoding = offset;
|
---|
| 9 | offset = undefined;
|
---|
| 10 | }
|
---|
| 11 |
|
---|
| 12 | if (typeof search === 'string') {
|
---|
| 13 | search = new Buffer(search, encoding || 'utf8');
|
---|
| 14 | } else if (typeof search === 'number' && !isNaN(search)) {
|
---|
| 15 | search = new Buffer([search])
|
---|
| 16 | } else if (!Buffer.isBuffer(search)) {
|
---|
| 17 | throw TypeError('search is not a bufferable object');
|
---|
| 18 | }
|
---|
| 19 |
|
---|
| 20 | if (search.length === 0) {
|
---|
| 21 | return -1;
|
---|
| 22 | }
|
---|
| 23 |
|
---|
| 24 | if (offset === undefined || (typeof offset === 'number' && isNaN(offset))) {
|
---|
| 25 | offset = 0;
|
---|
| 26 | } else if (typeof offset !== 'number') {
|
---|
| 27 | throw TypeError('offset is not a number');
|
---|
| 28 | }
|
---|
| 29 |
|
---|
| 30 | if (offset < 0) {
|
---|
| 31 | offset = buff.length + offset
|
---|
| 32 | }
|
---|
| 33 |
|
---|
| 34 | if (offset < 0) {
|
---|
| 35 | offset = 0;
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | var m = 0;
|
---|
| 39 | var s = -1;
|
---|
| 40 |
|
---|
| 41 | for (var i = offset; i < buff.length ; ++i) {
|
---|
| 42 | if(buff[i] != search[m]){
|
---|
| 43 | s = -1;
|
---|
| 44 | // <-- go back
|
---|
| 45 | // match abc to aabc
|
---|
| 46 | // 'aabc'
|
---|
| 47 | // 'aab'
|
---|
| 48 | // ^ no match
|
---|
| 49 | // a'abc'
|
---|
| 50 | // ^ set index here now and look at these again.
|
---|
| 51 | // 'abc' yay!
|
---|
| 52 | i -= m-1
|
---|
| 53 | m = 0;
|
---|
| 54 | }
|
---|
| 55 |
|
---|
| 56 | if(buff[i] == search[m]) {
|
---|
| 57 | if(s == -1) {
|
---|
| 58 | s = i;
|
---|
| 59 | }
|
---|
| 60 | ++m;
|
---|
| 61 | if(m == search.length) {
|
---|
| 62 | break;
|
---|
| 63 | }
|
---|
| 64 | }
|
---|
| 65 | }
|
---|
| 66 |
|
---|
| 67 | if (s > -1 && buff.length - s < search.length) {
|
---|
| 68 | return -1;
|
---|
| 69 | }
|
---|
| 70 | return s;
|
---|
| 71 | }
|
---|
| 72 |
|
---|
| 73 |
|
---|
Note:
See
TracBrowser
for help on using the repository browser.