(buffer, val, byteOffset, encoding, dir)
| 2514 | // - encoding - an optional encoding, relevant is val is a string |
| 2515 | // - dir - true for indexOf, false for lastIndexOf |
| 2516 | function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { |
| 2517 | // Empty buffer means no match |
| 2518 | if (buffer.length === 0) return -1 |
| 2519 | |
| 2520 | // Normalize byteOffset |
| 2521 | if (typeof byteOffset === 'string') { |
| 2522 | encoding = byteOffset; |
| 2523 | byteOffset = 0; |
| 2524 | } else if (byteOffset > 0x7fffffff) { |
| 2525 | byteOffset = 0x7fffffff; |
| 2526 | } else if (byteOffset < -0x80000000) { |
| 2527 | byteOffset = -0x80000000; |
| 2528 | } |
| 2529 | byteOffset = +byteOffset; // Coerce to Number. |
| 2530 | if (isNaN(byteOffset)) { |
| 2531 | // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer |
| 2532 | byteOffset = dir ? 0 : (buffer.length - 1); |
| 2533 | } |
| 2534 | |
| 2535 | // Normalize byteOffset: negative offsets start from the end of the buffer |
| 2536 | if (byteOffset < 0) byteOffset = buffer.length + byteOffset; |
| 2537 | if (byteOffset >= buffer.length) { |
| 2538 | if (dir) return -1 |
| 2539 | else byteOffset = buffer.length - 1; |
| 2540 | } else if (byteOffset < 0) { |
| 2541 | if (dir) byteOffset = 0; |
| 2542 | else return -1 |
| 2543 | } |
| 2544 | |
| 2545 | // Normalize val |
| 2546 | if (typeof val === 'string') { |
| 2547 | val = Buffer.from(val, encoding); |
| 2548 | } |
| 2549 | |
| 2550 | // Finally, search either indexOf (if dir is true) or lastIndexOf |
| 2551 | if (internalIsBuffer(val)) { |
| 2552 | // Special case: looking for empty string/buffer always fails |
| 2553 | if (val.length === 0) { |
| 2554 | return -1 |
| 2555 | } |
| 2556 | return arrayIndexOf(buffer, val, byteOffset, encoding, dir) |
| 2557 | } else if (typeof val === 'number') { |
| 2558 | val = val & 0xFF; // Search for a byte value [0-255] |
| 2559 | if (Buffer.TYPED_ARRAY_SUPPORT && |
| 2560 | typeof Uint8Array.prototype.indexOf === 'function') { |
| 2561 | if (dir) { |
| 2562 | return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) |
| 2563 | } else { |
| 2564 | return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) |
| 2565 | } |
| 2566 | } |
| 2567 | return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) |
| 2568 | } |
| 2569 | |
| 2570 | throw new TypeError('val must be string, number or Buffer') |
| 2571 | } |
| 2572 | |
| 2573 | function arrayIndexOf (arr, val, byteOffset, encoding, dir) { |
no test coverage detected