deflate.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. 'use strict';
  2. var zlib_deflate = require('./zlib/deflate');
  3. var utils = require('./utils/common');
  4. var strings = require('./utils/strings');
  5. var msg = require('./zlib/messages');
  6. var ZStream = require('./zlib/zstream');
  7. var toString = Object.prototype.toString;
  8. /* Public constants ==========================================================*/
  9. /* ===========================================================================*/
  10. var Z_NO_FLUSH = 0;
  11. var Z_FINISH = 4;
  12. var Z_OK = 0;
  13. var Z_STREAM_END = 1;
  14. var Z_SYNC_FLUSH = 2;
  15. var Z_DEFAULT_COMPRESSION = -1;
  16. var Z_DEFAULT_STRATEGY = 0;
  17. var Z_DEFLATED = 8;
  18. /* ===========================================================================*/
  19. /**
  20. * class Deflate
  21. *
  22. * Generic JS-style wrapper for zlib calls. If you don't need
  23. * streaming behaviour - use more simple functions: [[deflate]],
  24. * [[deflateRaw]] and [[gzip]].
  25. **/
  26. /* internal
  27. * Deflate.chunks -> Array
  28. *
  29. * Chunks of output data, if [[Deflate#onData]] not overriden.
  30. **/
  31. /**
  32. * Deflate.result -> Uint8Array|Array
  33. *
  34. * Compressed result, generated by default [[Deflate#onData]]
  35. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  36. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  37. * push a chunk with explicit flush (call [[Deflate#push]] with
  38. * `Z_SYNC_FLUSH` param).
  39. **/
  40. /**
  41. * Deflate.err -> Number
  42. *
  43. * Error code after deflate finished. 0 (Z_OK) on success.
  44. * You will not need it in real life, because deflate errors
  45. * are possible only on wrong options or bad `onData` / `onEnd`
  46. * custom handlers.
  47. **/
  48. /**
  49. * Deflate.msg -> String
  50. *
  51. * Error message, if [[Deflate.err]] != 0
  52. **/
  53. /**
  54. * new Deflate(options)
  55. * - options (Object): zlib deflate options.
  56. *
  57. * Creates new deflator instance with specified params. Throws exception
  58. * on bad params. Supported options:
  59. *
  60. * - `level`
  61. * - `windowBits`
  62. * - `memLevel`
  63. * - `strategy`
  64. * - `dictionary`
  65. *
  66. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  67. * for more information on these.
  68. *
  69. * Additional options, for internal needs:
  70. *
  71. * - `chunkSize` - size of generated data chunks (16K by default)
  72. * - `raw` (Boolean) - do raw deflate
  73. * - `gzip` (Boolean) - create gzip wrapper
  74. * - `to` (String) - if equal to 'string', then result will be "binary string"
  75. * (each char code [0..255])
  76. * - `header` (Object) - custom header for gzip
  77. * - `text` (Boolean) - true if compressed data believed to be text
  78. * - `time` (Number) - modification time, unix timestamp
  79. * - `os` (Number) - operation system code
  80. * - `extra` (Array) - array of bytes with extra data (max 65536)
  81. * - `name` (String) - file name (binary string)
  82. * - `comment` (String) - comment (binary string)
  83. * - `hcrc` (Boolean) - true if header crc should be added
  84. *
  85. * ##### Example:
  86. *
  87. * ```javascript
  88. * var pako = require('pako')
  89. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  90. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  91. *
  92. * var deflate = new pako.Deflate({ level: 3});
  93. *
  94. * deflate.push(chunk1, false);
  95. * deflate.push(chunk2, true); // true -> last chunk
  96. *
  97. * if (deflate.err) { throw new Error(deflate.err); }
  98. *
  99. * console.log(deflate.result);
  100. * ```
  101. **/
  102. function Deflate(options) {
  103. if (!(this instanceof Deflate)) return new Deflate(options);
  104. this.options = utils.assign({
  105. level: Z_DEFAULT_COMPRESSION,
  106. method: Z_DEFLATED,
  107. chunkSize: 16384,
  108. windowBits: 15,
  109. memLevel: 8,
  110. strategy: Z_DEFAULT_STRATEGY,
  111. to: ''
  112. }, options || {});
  113. var opt = this.options;
  114. if (opt.raw && (opt.windowBits > 0)) {
  115. opt.windowBits = -opt.windowBits;
  116. }
  117. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  118. opt.windowBits += 16;
  119. }
  120. this.err = 0; // error code, if happens (0 = Z_OK)
  121. this.msg = ''; // error message
  122. this.ended = false; // used to avoid multiple onEnd() calls
  123. this.chunks = []; // chunks of compressed data
  124. this.strm = new ZStream();
  125. this.strm.avail_out = 0;
  126. var status = zlib_deflate.deflateInit2(
  127. this.strm,
  128. opt.level,
  129. opt.method,
  130. opt.windowBits,
  131. opt.memLevel,
  132. opt.strategy
  133. );
  134. if (status !== Z_OK) {
  135. throw new Error(msg[status]);
  136. }
  137. if (opt.header) {
  138. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  139. }
  140. if (opt.dictionary) {
  141. var dict;
  142. // Convert data if needed
  143. if (typeof opt.dictionary === 'string') {
  144. // If we need to compress text, change encoding to utf8.
  145. dict = strings.string2buf(opt.dictionary);
  146. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  147. dict = new Uint8Array(opt.dictionary);
  148. } else {
  149. dict = opt.dictionary;
  150. }
  151. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  152. if (status !== Z_OK) {
  153. throw new Error(msg[status]);
  154. }
  155. this._dict_set = true;
  156. }
  157. }
  158. /**
  159. * Deflate#push(data[, mode]) -> Boolean
  160. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  161. * converted to utf8 byte sequence.
  162. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  163. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  164. *
  165. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  166. * new compressed chunks. Returns `true` on success. The last data block must have
  167. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  168. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  169. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  170. *
  171. * On fail call [[Deflate#onEnd]] with error code and return false.
  172. *
  173. * We strongly recommend to use `Uint8Array` on input for best speed (output
  174. * array format is detected automatically). Also, don't skip last param and always
  175. * use the same type in your code (boolean or number). That will improve JS speed.
  176. *
  177. * For regular `Array`-s make sure all elements are [0..255].
  178. *
  179. * ##### Example
  180. *
  181. * ```javascript
  182. * push(chunk, false); // push one of data chunks
  183. * ...
  184. * push(chunk, true); // push last chunk
  185. * ```
  186. **/
  187. Deflate.prototype.push = function (data, mode) {
  188. var strm = this.strm;
  189. var chunkSize = this.options.chunkSize;
  190. var status, _mode;
  191. if (this.ended) { return false; }
  192. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  193. // Convert data if needed
  194. if (typeof data === 'string') {
  195. // If we need to compress text, change encoding to utf8.
  196. strm.input = strings.string2buf(data);
  197. } else if (toString.call(data) === '[object ArrayBuffer]') {
  198. strm.input = new Uint8Array(data);
  199. } else {
  200. strm.input = data;
  201. }
  202. strm.next_in = 0;
  203. strm.avail_in = strm.input.length;
  204. do {
  205. if (strm.avail_out === 0) {
  206. strm.output = new utils.Buf8(chunkSize);
  207. strm.next_out = 0;
  208. strm.avail_out = chunkSize;
  209. }
  210. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  211. if (status !== Z_STREAM_END && status !== Z_OK) {
  212. this.onEnd(status);
  213. this.ended = true;
  214. return false;
  215. }
  216. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  217. if (this.options.to === 'string') {
  218. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  219. } else {
  220. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  221. }
  222. }
  223. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  224. // Finalize on the last chunk.
  225. if (_mode === Z_FINISH) {
  226. status = zlib_deflate.deflateEnd(this.strm);
  227. this.onEnd(status);
  228. this.ended = true;
  229. return status === Z_OK;
  230. }
  231. // callback interim results if Z_SYNC_FLUSH.
  232. if (_mode === Z_SYNC_FLUSH) {
  233. this.onEnd(Z_OK);
  234. strm.avail_out = 0;
  235. return true;
  236. }
  237. return true;
  238. };
  239. /**
  240. * Deflate#onData(chunk) -> Void
  241. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  242. * on js engine support. When string output requested, each chunk
  243. * will be string.
  244. *
  245. * By default, stores data blocks in `chunks[]` property and glue
  246. * those in `onEnd`. Override this handler, if you need another behaviour.
  247. **/
  248. Deflate.prototype.onData = function (chunk) {
  249. this.chunks.push(chunk);
  250. };
  251. /**
  252. * Deflate#onEnd(status) -> Void
  253. * - status (Number): deflate status. 0 (Z_OK) on success,
  254. * other if not.
  255. *
  256. * Called once after you tell deflate that the input stream is
  257. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  258. * or if an error happened. By default - join collected chunks,
  259. * free memory and fill `results` / `err` properties.
  260. **/
  261. Deflate.prototype.onEnd = function (status) {
  262. // On success - join
  263. if (status === Z_OK) {
  264. if (this.options.to === 'string') {
  265. this.result = this.chunks.join('');
  266. } else {
  267. this.result = utils.flattenChunks(this.chunks);
  268. }
  269. }
  270. this.chunks = [];
  271. this.err = status;
  272. this.msg = this.strm.msg;
  273. };
  274. /**
  275. * deflate(data[, options]) -> Uint8Array|Array|String
  276. * - data (Uint8Array|Array|String): input data to compress.
  277. * - options (Object): zlib deflate options.
  278. *
  279. * Compress `data` with deflate algorithm and `options`.
  280. *
  281. * Supported options are:
  282. *
  283. * - level
  284. * - windowBits
  285. * - memLevel
  286. * - strategy
  287. * - dictionary
  288. *
  289. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  290. * for more information on these.
  291. *
  292. * Sugar (options):
  293. *
  294. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  295. * negative windowBits implicitly.
  296. * - `to` (String) - if equal to 'string', then result will be "binary string"
  297. * (each char code [0..255])
  298. *
  299. * ##### Example:
  300. *
  301. * ```javascript
  302. * var pako = require('pako')
  303. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  304. *
  305. * console.log(pako.deflate(data));
  306. * ```
  307. **/
  308. function deflate(input, options) {
  309. var deflator = new Deflate(options);
  310. deflator.push(input, true);
  311. // That will never happens, if you don't cheat with options :)
  312. if (deflator.err) { throw deflator.msg; }
  313. return deflator.result;
  314. }
  315. /**
  316. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  317. * - data (Uint8Array|Array|String): input data to compress.
  318. * - options (Object): zlib deflate options.
  319. *
  320. * The same as [[deflate]], but creates raw data, without wrapper
  321. * (header and adler32 crc).
  322. **/
  323. function deflateRaw(input, options) {
  324. options = options || {};
  325. options.raw = true;
  326. return deflate(input, options);
  327. }
  328. /**
  329. * gzip(data[, options]) -> Uint8Array|Array|String
  330. * - data (Uint8Array|Array|String): input data to compress.
  331. * - options (Object): zlib deflate options.
  332. *
  333. * The same as [[deflate]], but create gzip wrapper instead of
  334. * deflate one.
  335. **/
  336. function gzip(input, options) {
  337. options = options || {};
  338. options.gzip = true;
  339. return deflate(input, options);
  340. }
  341. exports.Deflate = Deflate;
  342. exports.deflate = deflate;
  343. exports.deflateRaw = deflateRaw;
  344. exports.gzip = gzip;