No Description

flate.js 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  3. var pako = require("pako");
  4. var utils = require("./utils");
  5. var GenericWorker = require("./stream/GenericWorker");
  6. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  7. exports.magic = "\x08\x00";
  8. /**
  9. * Create a worker that uses pako to inflate/deflate.
  10. * @constructor
  11. * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  12. * @param {Object} options the options to use when (de)compressing.
  13. */
  14. function FlateWorker(action, options) {
  15. GenericWorker.call(this, "FlateWorker/" + action);
  16. this._pako = null;
  17. this._pakoAction = action;
  18. this._pakoOptions = options;
  19. // the `meta` object from the last chunk received
  20. // this allow this worker to pass around metadata
  21. this.meta = {};
  22. }
  23. utils.inherits(FlateWorker, GenericWorker);
  24. /**
  25. * @see GenericWorker.processChunk
  26. */
  27. FlateWorker.prototype.processChunk = function (chunk) {
  28. this.meta = chunk.meta;
  29. if (this._pako === null) {
  30. this._createPako();
  31. }
  32. this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  33. };
  34. /**
  35. * @see GenericWorker.flush
  36. */
  37. FlateWorker.prototype.flush = function () {
  38. GenericWorker.prototype.flush.call(this);
  39. if (this._pako === null) {
  40. this._createPako();
  41. }
  42. this._pako.push([], true);
  43. };
  44. /**
  45. * @see GenericWorker.cleanUp
  46. */
  47. FlateWorker.prototype.cleanUp = function () {
  48. GenericWorker.prototype.cleanUp.call(this);
  49. this._pako = null;
  50. };
  51. /**
  52. * Create the _pako object.
  53. * TODO: lazy-loading this object isn't the best solution but it's the
  54. * quickest. The best solution is to lazy-load the worker list. See also the
  55. * issue #446.
  56. */
  57. FlateWorker.prototype._createPako = function () {
  58. this._pako = new pako[this._pakoAction]({
  59. raw: true,
  60. level: this._pakoOptions.level || -1 // default compression
  61. });
  62. var self = this;
  63. this._pako.onData = function(data) {
  64. self.push({
  65. data : data,
  66. meta : self.meta
  67. });
  68. };
  69. };
  70. exports.compressWorker = function (compressionOptions) {
  71. return new FlateWorker("Deflate", compressionOptions);
  72. };
  73. exports.uncompressWorker = function () {
  74. return new FlateWorker("Inflate", {});
  75. };