(buffer, val, byteOffset, encoding, dir)
| 617 | // - encoding - an optional encoding, relevant is val is a string |
| 618 | // - dir - true for indexOf, false for lastIndexOf |
| 619 | function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { |
| 620 | // Empty buffer means no match |
| 621 | if (buffer.length === 0) return -1; |
| 622 | |
| 623 | // Normalize byteOffset |
| 624 | if (typeof byteOffset === 'string') { |
| 625 | encoding = byteOffset; |
| 626 | byteOffset = 0; |
| 627 | } else if (byteOffset > 0x7fffffff) { |
| 628 | byteOffset = 0x7fffffff; |
| 629 | } else if (byteOffset < -0x80000000) { |
| 630 | byteOffset = -0x80000000; |
| 631 | } |
| 632 | byteOffset = +byteOffset; // Coerce to Number. |
| 633 | if (numberIsNaN(byteOffset)) { |
| 634 | // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer |
| 635 | byteOffset = dir ? 0 : buffer.length - 1; |
| 636 | } |
| 637 | |
| 638 | // Normalize byteOffset: negative offsets start from the end of the buffer |
| 639 | if (byteOffset < 0) byteOffset = buffer.length + byteOffset; |
| 640 | if (byteOffset >= buffer.length) { |
| 641 | if (dir) return -1;else byteOffset = buffer.length - 1; |
| 642 | } else if (byteOffset < 0) { |
| 643 | if (dir) byteOffset = 0;else return -1; |
| 644 | } |
| 645 | |
| 646 | // Normalize val |
| 647 | if (typeof val === 'string') { |
| 648 | val = Buffer.from(val, encoding); |
| 649 | } |
| 650 | |
| 651 | // Finally, search either indexOf (if dir is true) or lastIndexOf |
| 652 | if (Buffer.isBuffer(val)) { |
| 653 | // Special case: looking for empty string/buffer always fails |
| 654 | if (val.length === 0) { |
| 655 | return -1; |
| 656 | } |
| 657 | return arrayIndexOf(buffer, val, byteOffset, encoding, dir); |
| 658 | } else if (typeof val === 'number') { |
| 659 | val = val & 0xFF; // Search for a byte value [0-255] |
| 660 | if (typeof Uint8Array.prototype.indexOf === 'function') { |
| 661 | if (dir) { |
| 662 | return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); |
| 663 | } else { |
| 664 | return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); |
| 665 | } |
| 666 | } |
| 667 | return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); |
| 668 | } |
| 669 | throw new TypeError('val must be string, number or Buffer'); |
| 670 | } |
| 671 | function arrayIndexOf(arr, val, byteOffset, encoding, dir) { |
| 672 | var indexSize = 1; |
| 673 | var arrLength = arr.length; |
no test coverage detected
searching dependent graphs…