inflate.js 11 KB

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