crc32.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. (function () {
  2. 'use strict';
  3. var table = [],
  4. poly = 0xEDB88320; // reverse polynomial
  5. // build the table
  6. function makeTable() {
  7. var c, n, k;
  8. for (n = 0; n < 256; n += 1) {
  9. c = n;
  10. for (k = 0; k < 8; k += 1) {
  11. if (c & 1) {
  12. c = poly ^ (c >>> 1);
  13. } else {
  14. c = c >>> 1;
  15. }
  16. }
  17. table[n] = c >>> 0;
  18. }
  19. }
  20. function strToArr(str) {
  21. // sweet hack to turn string into a 'byte' array
  22. return Array.prototype.map.call(str, function (c) {
  23. return c.charCodeAt(0);
  24. });
  25. }
  26. /*
  27. * Compute CRC of array directly.
  28. *
  29. * This is slower for repeated calls, so append mode is not supported.
  30. */
  31. function crcDirect(arr) {
  32. var crc = -1, // initial contents of LFBSR
  33. i, j, l, temp;
  34. for (i = 0, l = arr.length; i < l; i += 1) {
  35. temp = (crc ^ arr[i]) & 0xff;
  36. // read 8 bits one at a time
  37. for (j = 0; j < 8; j += 1) {
  38. if ((temp & 1) === 1) {
  39. temp = (temp >>> 1) ^ poly;
  40. } else {
  41. temp = (temp >>> 1);
  42. }
  43. }
  44. crc = (crc >>> 8) ^ temp;
  45. }
  46. // flip bits
  47. return crc ^ -1;
  48. }
  49. /*
  50. * Compute CRC with the help of a pre-calculated table.
  51. *
  52. * This supports append mode, if the second parameter is set.
  53. */
  54. function crcTable(arr, append) {
  55. var crc, i, l;
  56. // if we're in append mode, don't reset crc
  57. // if arr is null or undefined, reset table and return
  58. if (typeof crcTable.crc === 'undefined' || !append || !arr) {
  59. crcTable.crc = 0 ^ -1;
  60. if (!arr) {
  61. return;
  62. }
  63. }
  64. // store in temp variable for minor speed gain
  65. crc = crcTable.crc;
  66. for (i = 0, l = arr.length; i < l; i += 1) {
  67. crc = (crc >>> 8) ^ table[(crc ^ arr[i]) & 0xff];
  68. }
  69. crcTable.crc = crc;
  70. return crc ^ -1;
  71. }
  72. // build the table
  73. // this isn't that costly, and most uses will be for table assisted mode
  74. makeTable();
  75. module.exports = function (val, direct) {
  76. var val = (typeof val === 'string') ? strToArr(val) : val,
  77. ret = direct ? crcDirect(val) : crcTable(val);
  78. // convert to 2's complement hex
  79. return (ret >>> 0).toString(16);
  80. };
  81. module.exports.direct = crcDirect;
  82. module.exports.table = crcTable;
  83. }());