暫無描述

crc32.js 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. var utils = require('./utils');
  3. /**
  4. * The following functions come from pako, from pako/lib/zlib/crc32.js
  5. * released under the MIT license, see pako https://github.com/nodeca/pako/
  6. */
  7. // Use ordinary array, since untyped makes no boost here
  8. function makeTable() {
  9. var c, table = [];
  10. for(var n =0; n < 256; n++){
  11. c = n;
  12. for(var k =0; k < 8; k++){
  13. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  14. }
  15. table[n] = c;
  16. }
  17. return table;
  18. }
  19. // Create table on load. Just 255 signed longs. Not a problem.
  20. var crcTable = makeTable();
  21. function crc32(crc, buf, len, pos) {
  22. var t = crcTable, end = pos + len;
  23. crc = crc ^ (-1);
  24. for (var i = pos; i < end; i++ ) {
  25. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  26. }
  27. return (crc ^ (-1)); // >>> 0;
  28. }
  29. // That's all for the pako functions.
  30. /**
  31. * Compute the crc32 of a string.
  32. * This is almost the same as the function crc32, but for strings. Using the
  33. * same function for the two use cases leads to horrible performances.
  34. * @param {Number} crc the starting value of the crc.
  35. * @param {String} str the string to use.
  36. * @param {Number} len the length of the string.
  37. * @param {Number} pos the starting position for the crc32 computation.
  38. * @return {Number} the computed crc32.
  39. */
  40. function crc32str(crc, str, len, pos) {
  41. var t = crcTable, end = pos + len;
  42. crc = crc ^ (-1);
  43. for (var i = pos; i < end; i++ ) {
  44. crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
  45. }
  46. return (crc ^ (-1)); // >>> 0;
  47. }
  48. module.exports = function crc32wrapper(input, crc) {
  49. if (typeof input === "undefined" || !input.length) {
  50. return 0;
  51. }
  52. var isArray = utils.getTypeOf(input) !== "string";
  53. if(isArray) {
  54. return crc32(crc|0, input, input.length, 0);
  55. } else {
  56. return crc32str(crc|0, input, input.length, 0);
  57. }
  58. };