(buffer, val, byteOffset, encoding, dir)
| 10348 | // - encoding - an optional encoding, relevant is val is a string |
| 10349 | // - dir - true for indexOf, false for lastIndexOf |
| 10350 | function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { |
| 10351 | // Empty buffer means no match |
| 10352 | if (buffer.length === 0) return -1 |
| 10353 | |
| 10354 | // Normalize byteOffset |
| 10355 | if (typeof byteOffset === 'string') { |
| 10356 | encoding = byteOffset |
| 10357 | byteOffset = 0 |
| 10358 | } else if (byteOffset > 0x7fffffff) { |
| 10359 | byteOffset = 0x7fffffff |
| 10360 | } else if (byteOffset < -0x80000000) { |
| 10361 | byteOffset = -0x80000000 |
| 10362 | } |
| 10363 | byteOffset = +byteOffset // Coerce to Number. |
| 10364 | if (isNaN(byteOffset)) { |
| 10365 | // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer |
| 10366 | byteOffset = dir ? 0 : (buffer.length - 1) |
| 10367 | } |
| 10368 | |
| 10369 | // Normalize byteOffset: negative offsets start from the end of the buffer |
| 10370 | if (byteOffset < 0) byteOffset = buffer.length + byteOffset |
| 10371 | if (byteOffset >= buffer.length) { |
| 10372 | if (dir) return -1 |
| 10373 | else byteOffset = buffer.length - 1 |
| 10374 | } else if (byteOffset < 0) { |
| 10375 | if (dir) byteOffset = 0 |
| 10376 | else return -1 |
| 10377 | } |
| 10378 | |
| 10379 | // Normalize val |
| 10380 | if (typeof val === 'string') { |
| 10381 | val = Buffer.from(val, encoding) |
| 10382 | } |
| 10383 | |
| 10384 | // Finally, search either indexOf (if dir is true) or lastIndexOf |
| 10385 | if (Buffer.isBuffer(val)) { |
| 10386 | // Special case: looking for empty string/buffer always fails |
| 10387 | if (val.length === 0) { |
| 10388 | return -1 |
| 10389 | } |
| 10390 | return arrayIndexOf(buffer, val, byteOffset, encoding, dir) |
| 10391 | } else if (typeof val === 'number') { |
| 10392 | val = val & 0xFF // Search for a byte value [0-255] |
| 10393 | if (Buffer.TYPED_ARRAY_SUPPORT && |
| 10394 | typeof Uint8Array.prototype.indexOf === 'function') { |
| 10395 | if (dir) { |
| 10396 | return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) |
| 10397 | } else { |
| 10398 | return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) |
| 10399 | } |
| 10400 | } |
| 10401 | return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) |
| 10402 | } |
| 10403 | |
| 10404 | throw new TypeError('val must be string, number or Buffer') |
| 10405 | } |
| 10406 | |
| 10407 | function arrayIndexOf (arr, val, byteOffset, encoding, dir) { |
no test coverage detected