index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use strict";
  2. var initBuffer = require("./init-buffer");
  3. if (!Buffer.prototype.indexOf) {
  4. Buffer.prototype.indexOf = function (value, offset) {
  5. offset = offset || 0;
  6. // Always wrap the input as a Buffer so that this method will support any
  7. // data type such as array octet, string or buffer.
  8. if (typeof value === "string" || value instanceof String) {
  9. value = initBuffer(value);
  10. } else if (typeof value === "number" || value instanceof Number) {
  11. value = initBuffer([ value ]);
  12. }
  13. var len = value.length;
  14. for (var i = offset; i <= this.length - len; i++) {
  15. var mismatch = false;
  16. for (var j = 0; j < len; j++) {
  17. if (this[i + j] != value[j]) {
  18. mismatch = true;
  19. break;
  20. }
  21. }
  22. if (!mismatch) {
  23. return i;
  24. }
  25. }
  26. return -1;
  27. };
  28. }
  29. function bufferLastIndexOf (value, offset) {
  30. // Always wrap the input as a Buffer so that this method will support any
  31. // data type such as array octet, string or buffer.
  32. if (typeof value === "string" || value instanceof String) {
  33. value = initBuffer(value);
  34. } else if (typeof value === "number" || value instanceof Number) {
  35. value = initBuffer([ value ]);
  36. }
  37. var len = value.length;
  38. offset = offset || this.length - len;
  39. for (var i = offset; i >= 0; i--) {
  40. var mismatch = false;
  41. for (var j = 0; j < len; j++) {
  42. if (this[i + j] != value[j]) {
  43. mismatch = true;
  44. break;
  45. }
  46. }
  47. if (!mismatch) {
  48. return i;
  49. }
  50. }
  51. return -1;
  52. }
  53. if (Buffer.prototype.lastIndexOf) {
  54. // check Buffer#lastIndexOf is usable: https://github.com/nodejs/node/issues/4604
  55. if (initBuffer("ABC").lastIndexOf ("ABC") === -1)
  56. Buffer.prototype.lastIndexOf = bufferLastIndexOf;
  57. } else {
  58. Buffer.prototype.lastIndexOf = bufferLastIndexOf;
  59. }