index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. module.exports = function bufferIndexOf(buff, search, offset, encoding){
  2. if (!Buffer.isBuffer(buff)) {
  3. throw TypeError('buffer is not a buffer');
  4. }
  5. // allow optional offset when providing an encoding
  6. if (encoding === undefined && typeof offset === 'string') {
  7. encoding = offset;
  8. offset = undefined;
  9. }
  10. if (typeof search === 'string') {
  11. search = new Buffer(search, encoding || 'utf8');
  12. } else if (typeof search === 'number' && !isNaN(search)) {
  13. search = new Buffer([search])
  14. } else if (!Buffer.isBuffer(search)) {
  15. throw TypeError('search is not a bufferable object');
  16. }
  17. if (search.length === 0) {
  18. return -1;
  19. }
  20. if (offset === undefined || (typeof offset === 'number' && isNaN(offset))) {
  21. offset = 0;
  22. } else if (typeof offset !== 'number') {
  23. throw TypeError('offset is not a number');
  24. }
  25. if (offset < 0) {
  26. offset = buff.length + offset
  27. }
  28. if (offset < 0) {
  29. offset = 0;
  30. }
  31. var m = 0;
  32. var s = -1;
  33. for (var i = offset; i < buff.length ; ++i) {
  34. if(buff[i] != search[m]){
  35. s = -1;
  36. // <-- go back
  37. // match abc to aabc
  38. // 'aabc'
  39. // 'aab'
  40. // ^ no match
  41. // a'abc'
  42. // ^ set index here now and look at these again.
  43. // 'abc' yay!
  44. i -= m-1
  45. m = 0;
  46. }
  47. if(buff[i] == search[m]) {
  48. if(s == -1) {
  49. s = i;
  50. }
  51. ++m;
  52. if(m == search.length) {
  53. break;
  54. }
  55. }
  56. }
  57. if (s > -1 && buff.length - s < search.length) {
  58. return -1;
  59. }
  60. return s;
  61. }