西藏巴青项目

crc32.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. };