inflate.js 12 KB

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