Skip to content
Browse files

issue #7 : load a zip file

  • Loading branch information...
1 parent 5adf03b commit f02df57ccae7e91914c28b425e6a87ee3d2b6f46 @dduponchel dduponchel committed Oct 29, 2011
Showing with 1,218 additions and 14 deletions.
  1. +8 −6 jszip-deflate.js
  2. +775 −0 jszip-inflate.js
  3. +396 −0 jszip-load.js
  4. +24 −3 jszip.js
  5. +15 −5 test/index.html
View
14 jszip-deflate.js
@@ -5,7 +5,7 @@
* main function to JSZip (DEFLATE compression method).
* Everything else was written by M. Izumo.
*
- * Original code can be found here: http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt
+ * Original code can be found here: http://www.onicos.com/staff/iz/amuse/javascript/expert/deflate.txt
*/
if(!JSZip)
@@ -1683,11 +1683,13 @@ var zip_deflate = function(str, level) {
//
// we add the compression method for JSZip
-JSZip.compressions["DEFLATE"] = {
- magic : "\x08\x00",
- compress : function (content) {
- return zip_deflate(content);
- }
+if(!JSZip.compressions["DEFLATE"]) {
+ JSZip.compressions["DEFLATE"] = {
+ magic : "\x08\x00",
+ compress : zip_deflate
+ }
+} else {
+ JSZip.compressions["DEFLATE"].compress = zip_deflate;
}
})();
View
775 jszip-inflate.js
@@ -0,0 +1,775 @@
+/*
+ * Port of a script by Masanao Izumo.
+ *
+ * Only changes : wrap all the variables in a function and add the
+ * main function to JSZip (DEFLATE compression method).
+ * Everything else was written by M. Izumo.
+ *
+ * Original code can be found here: http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt
+ */
+
+if(!JSZip)
+{
+ throw "JSZip not defined";
+}
+
+/*
+ * Original:
+ * http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt
+ */
+
+(function(){
+
+/* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
+ * Version: 1.0.0.1
+ * LastModified: Dec 25 1999
+ */
+
+/* Interface:
+ * data = zip_inflate(src);
+ */
+
+/* constant parameters */
+var zip_WSIZE = 32768; // Sliding Window size
+var zip_STORED_BLOCK = 0;
+var zip_STATIC_TREES = 1;
+var zip_DYN_TREES = 2;
+
+/* for inflate */
+var zip_lbits = 9; // bits in base literal/length lookup table
+var zip_dbits = 6; // bits in base distance lookup table
+var zip_INBUFSIZ = 32768; // Input buffer size
+var zip_INBUF_EXTRA = 64; // Extra buffer
+
+/* variables (inflate) */
+var zip_slide;
+var zip_wp; // current position in slide
+var zip_fixed_tl = null; // inflate static
+var zip_fixed_td; // inflate static
+var zip_fixed_bl, fixed_bd; // inflate static
+var zip_bit_buf; // bit buffer
+var zip_bit_len; // bits in bit buffer
+var zip_method;
+var zip_eof;
+var zip_copy_leng;
+var zip_copy_dist;
+var zip_tl, zip_td; // literal/length and distance decoder tables
+var zip_bl, zip_bd; // number of bits decoded by tl and td
+
+var zip_inflate_data;
+var zip_inflate_pos;
+
+
+/* constant tables (inflate) */
+var zip_MASK_BITS = new Array(
+ 0x0000,
+ 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
+ 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff);
+// Tables for deflate from PKZIP's appnote.txt.
+var zip_cplens = new Array( // Copy lengths for literal codes 257..285
+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+ 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0);
+/* note: see note #13 above about the 258 in this list. */
+var zip_cplext = new Array( // Extra bits for literal codes 257..285
+ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+ 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99); // 99==invalid
+var zip_cpdist = new Array( // Copy offsets for distance codes 0..29
+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+ 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+ 8193, 12289, 16385, 24577);
+var zip_cpdext = new Array( // Extra bits for distance codes
+ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
+ 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
+ 12, 12, 13, 13);
+var zip_border = new Array( // Order of the bit length code lengths
+ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15);
+/* objects (inflate) */
+
+function zip_HuftList() {
+ this.next = null;
+ this.list = null;
+}
+
+function zip_HuftNode() {
+ this.e = 0; // number of extra bits or operation
+ this.b = 0; // number of bits in this code or subcode
+
+ // union
+ this.n = 0; // literal, length base, or distance base
+ this.t = null; // (zip_HuftNode) pointer to next level of table
+}
+
+function zip_HuftBuild(b, // code lengths in bits (all assumed <= BMAX)
+ n, // number of codes (assumed <= N_MAX)
+ s, // number of simple-valued codes (0..s-1)
+ d, // list of base values for non-simple codes
+ e, // list of extra bits for non-simple codes
+ mm // maximum lookup bits
+ ) {
+ this.BMAX = 16; // maximum bit length of any code
+ this.N_MAX = 288; // maximum number of codes in any set
+ this.status = 0; // 0: success, 1: incomplete table, 2: bad input
+ this.root = null; // (zip_HuftList) starting table
+ this.m = 0; // maximum lookup bits, returns actual
+
+/* Given a list of code lengths and a maximum table size, make a set of
+ tables to decode that set of codes. Return zero on success, one if
+ the given code set is incomplete (the tables are still built in this
+ case), two if the input is invalid (all zero length codes or an
+ oversubscribed set of lengths), and three if not enough memory.
+ The code with value 256 is special, and the tables are constructed
+ so that no bits beyond that code are fetched when that code is
+ decoded. */
+ {
+ var a; // counter for codes of length k
+ var c = new Array(this.BMAX+1); // bit length count table
+ var el; // length of EOB code (value 256)
+ var f; // i repeats in table every f entries
+ var g; // maximum code length
+ var h; // table level
+ var i; // counter, current code
+ var j; // counter
+ var k; // number of bits in current code
+ var lx = new Array(this.BMAX+1); // stack of bits per table
+ var p; // pointer into c[], b[], or v[]
+ var pidx; // index of p
+ var q; // (zip_HuftNode) points to current table
+ var r = new zip_HuftNode(); // table entry for structure assignment
+ var u = new Array(this.BMAX); // zip_HuftNode[BMAX][] table stack
+ var v = new Array(this.N_MAX); // values in order of bit length
+ var w;
+ var x = new Array(this.BMAX+1);// bit offsets, then code stack
+ var xp; // pointer into x or c
+ var y; // number of dummy codes added
+ var z; // number of entries in current table
+ var o;
+ var tail; // (zip_HuftList)
+
+ tail = this.root = null;
+ for(i = 0; i < c.length; i++)
+ c[i] = 0;
+ for(i = 0; i < lx.length; i++)
+ lx[i] = 0;
+ for(i = 0; i < u.length; i++)
+ u[i] = null;
+ for(i = 0; i < v.length; i++)
+ v[i] = 0;
+ for(i = 0; i < x.length; i++)
+ x[i] = 0;
+
+ // Generate counts for each bit length
+ el = n > 256 ? b[256] : this.BMAX; // set length of EOB code, if any
+ p = b; pidx = 0;
+ i = n;
+ do {
+ c[p[pidx]]++; // assume all entries <= BMAX
+ pidx++;
+ } while(--i > 0);
+ if(c[0] == n) { // null input--all zero length codes
+ this.root = null;
+ this.m = 0;
+ this.status = 0;
+ return;
+ }
+
+ // Find minimum and maximum length, bound *m by those
+ for(j = 1; j <= this.BMAX; j++)
+ if(c[j] != 0)
+ break;
+ k = j; // minimum code length
+ if(mm < j)
+ mm = j;
+ for(i = this.BMAX; i != 0; i--)
+ if(c[i] != 0)
+ break;
+ g = i; // maximum code length
+ if(mm > i)
+ mm = i;
+
+ // Adjust last length count to fill out codes, if needed
+ for(y = 1 << j; j < i; j++, y <<= 1)
+ if((y -= c[j]) < 0) {
+ this.status = 2; // bad input: more codes than bits
+ this.m = mm;
+ return;
+ }
+ if((y -= c[i]) < 0) {
+ this.status = 2;
+ this.m = mm;
+ return;
+ }
+ c[i] += y;
+
+ // Generate starting offsets into the value table for each length
+ x[1] = j = 0;
+ p = c;
+ pidx = 1;
+ xp = 2;
+ while(--i > 0) // note that i == g from above
+ x[xp++] = (j += p[pidx++]);
+
+ // Make a table of values in order of bit lengths
+ p = b; pidx = 0;
+ i = 0;
+ do {
+ if((j = p[pidx++]) != 0)
+ v[x[j]++] = i;
+ } while(++i < n);
+ n = x[g]; // set n to length of v
+
+ // Generate the Huffman codes and for each, make the table entries
+ x[0] = i = 0; // first Huffman code is zero
+ p = v; pidx = 0; // grab values in bit order
+ h = -1; // no tables yet--level -1
+ w = lx[0] = 0; // no bits decoded yet
+ q = null; // ditto
+ z = 0; // ditto
+
+ // go through the bit lengths (k already is bits in shortest code)
+ for(; k <= g; k++) {
+ a = c[k];
+ while(a-- > 0) {
+ // here i is the Huffman code of length k bits for value p[pidx]
+ // make tables up to required level
+ while(k > w + lx[1 + h]) {
+ w += lx[1 + h]; // add bits already decoded
+ h++;
+
+ // compute minimum size table less than or equal to *m bits
+ z = (z = g - w) > mm ? mm : z; // upper limit
+ if((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table
+ // too few codes for k-w bit table
+ f -= a + 1; // deduct codes from patterns left
+ xp = k;
+ while(++j < z) { // try smaller tables up to z bits
+ if((f <<= 1) <= c[++xp])
+ break; // enough codes to use up j bits
+ f -= c[xp]; // else deduct codes from patterns
+ }
+ }
+ if(w + j > el && w < el)
+ j = el - w; // make EOB code end at table
+ z = 1 << j; // table entries for j-bit table
+ lx[1 + h] = j; // set table size in stack
+
+ // allocate and link in new table
+ q = new Array(z);
+ for(o = 0; o < z; o++) {
+ q[o] = new zip_HuftNode();
+ }
+
+ if(tail == null)
+ tail = this.root = new zip_HuftList();
+ else
+ tail = tail.next = new zip_HuftList();
+ tail.next = null;
+ tail.list = q;
+ u[h] = q; // table starts after link
+
+ /* connect to last table, if there is one */
+ if(h > 0) {
+ x[h] = i; // save pattern for backing up
+ r.b = lx[h]; // bits to dump before this table
+ r.e = 16 + j; // bits in this table
+ r.t = q; // pointer to this table
+ j = (i & ((1 << w) - 1)) >> (w - lx[h]);
+ u[h-1][j].e = r.e;
+ u[h-1][j].b = r.b;
+ u[h-1][j].n = r.n;
+ u[h-1][j].t = r.t;
+ }
+ }
+
+ // set up table entry in r
+ r.b = k - w;
+ if(pidx >= n)
+ r.e = 99; // out of values--invalid code
+ else if(p[pidx] < s) {
+ r.e = (p[pidx] < 256 ? 16 : 15); // 256 is end-of-block code
+ r.n = p[pidx++]; // simple code is just the value
+ } else {
+ r.e = e[p[pidx] - s]; // non-simple--look up in lists
+ r.n = d[p[pidx++] - s];
+ }
+
+ // fill code-like entries with r //
+ f = 1 << (k - w);
+ for(j = i >> w; j < z; j += f) {
+ q[j].e = r.e;
+ q[j].b = r.b;
+ q[j].n = r.n;
+ q[j].t = r.t;
+ }
+
+ // backwards increment the k-bit code i
+ for(j = 1 << (k - 1); (i & j) != 0; j >>= 1)
+ i ^= j;
+ i ^= j;
+
+ // backup over finished tables
+ while((i & ((1 << w) - 1)) != x[h]) {
+ w -= lx[h]; // don't need to update q
+ h--;
+ }
+ }
+ }
+
+ /* return actual size of base table */
+ this.m = lx[1];
+
+ /* Return true (1) if we were given an incomplete table */
+ this.status = ((y != 0 && g != 1) ? 1 : 0);
+ } /* end of constructor */
+}
+
+
+/* routines (inflate) */
+
+function zip_GET_BYTE() {
+ if(zip_inflate_data.length == zip_inflate_pos)
+ return -1;
+ return zip_inflate_data.charCodeAt(zip_inflate_pos++) & 0xff;
+}
+
+function zip_NEEDBITS(n) {
+ while(zip_bit_len < n) {
+ zip_bit_buf |= zip_GET_BYTE() << zip_bit_len;
+ zip_bit_len += 8;
+ }
+}
+
+function zip_GETBITS(n) {
+ return zip_bit_buf & zip_MASK_BITS[n];
+}
+
+function zip_DUMPBITS(n) {
+ zip_bit_buf >>= n;
+ zip_bit_len -= n;
+}
+
+function zip_inflate_codes(buff, off, size) {
+ /* inflate (decompress) the codes in a deflated (compressed) block.
+ Return an error code or zero if it all goes ok. */
+ var e; // table entry flag/number of extra bits
+ var t; // (zip_HuftNode) pointer to table entry
+ var n;
+
+ if(size == 0)
+ return 0;
+
+ // inflate the coded data
+ n = 0;
+ for(;;) { // do until end of block
+ zip_NEEDBITS(zip_bl);
+ t = zip_tl.list[zip_GETBITS(zip_bl)];
+ e = t.e;
+ while(e > 16) {
+ if(e == 99)
+ return -1;
+ zip_DUMPBITS(t.b);
+ e -= 16;
+ zip_NEEDBITS(e);
+ t = t.t[zip_GETBITS(e)];
+ e = t.e;
+ }
+ zip_DUMPBITS(t.b);
+
+ if(e == 16) { // then it's a literal
+ zip_wp &= zip_WSIZE - 1;
+ buff[off + n++] = zip_slide[zip_wp++] = t.n;
+ if(n == size)
+ return size;
+ continue;
+ }
+
+ // exit if end of block
+ if(e == 15)
+ break;
+
+ // it's an EOB or a length
+
+ // get length of block to copy
+ zip_NEEDBITS(e);
+ zip_copy_leng = t.n + zip_GETBITS(e);
+ zip_DUMPBITS(e);
+
+ // decode distance of block to copy
+ zip_NEEDBITS(zip_bd);
+ t = zip_td.list[zip_GETBITS(zip_bd)];
+ e = t.e;
+
+ while(e > 16) {
+ if(e == 99)
+ return -1;
+ zip_DUMPBITS(t.b);
+ e -= 16;
+ zip_NEEDBITS(e);
+ t = t.t[zip_GETBITS(e)];
+ e = t.e;
+ }
+ zip_DUMPBITS(t.b);
+ zip_NEEDBITS(e);
+ zip_copy_dist = zip_wp - t.n - zip_GETBITS(e);
+ zip_DUMPBITS(e);
+
+ // do the copy
+ while(zip_copy_leng > 0 && n < size) {
+ zip_copy_leng--;
+ zip_copy_dist &= zip_WSIZE - 1;
+ zip_wp &= zip_WSIZE - 1;
+ buff[off + n++] = zip_slide[zip_wp++]
+ = zip_slide[zip_copy_dist++];
+ }
+
+ if(n == size)
+ return size;
+ }
+
+ zip_method = -1; // done
+ return n;
+}
+
+function zip_inflate_stored(buff, off, size) {
+ /* "decompress" an inflated type 0 (stored) block. */
+ var n;
+
+ // go to byte boundary
+ n = zip_bit_len & 7;
+ zip_DUMPBITS(n);
+
+ // get the length and its complement
+ zip_NEEDBITS(16);
+ n = zip_GETBITS(16);
+ zip_DUMPBITS(16);
+ zip_NEEDBITS(16);
+ if(n != ((~zip_bit_buf) & 0xffff))
+ return -1; // error in compressed data
+ zip_DUMPBITS(16);
+
+ // read and output the compressed data
+ zip_copy_leng = n;
+
+ n = 0;
+ while(zip_copy_leng > 0 && n < size) {
+ zip_copy_leng--;
+ zip_wp &= zip_WSIZE - 1;
+ zip_NEEDBITS(8);
+ buff[off + n++] = zip_slide[zip_wp++] =
+ zip_GETBITS(8);
+ zip_DUMPBITS(8);
+ }
+
+ if(zip_copy_leng == 0)
+ zip_method = -1; // done
+ return n;
+}
+
+function zip_inflate_fixed(buff, off, size) {
+ /* decompress an inflated type 1 (fixed Huffman codes) block. We should
+ either replace this with a custom decoder, or at least precompute the
+ Huffman tables. */
+
+ // if first time, set up tables for fixed blocks
+ if(zip_fixed_tl == null) {
+ var i; // temporary variable
+ var l = new Array(288); // length list for huft_build
+ var h; // zip_HuftBuild
+
+ // literal table
+ for(i = 0; i < 144; i++)
+ l[i] = 8;
+ for(; i < 256; i++)
+ l[i] = 9;
+ for(; i < 280; i++)
+ l[i] = 7;
+ for(; i < 288; i++) // make a complete, but wrong code set
+ l[i] = 8;
+ zip_fixed_bl = 7;
+
+ h = new zip_HuftBuild(l, 288, 257, zip_cplens, zip_cplext,
+ zip_fixed_bl);
+ if(h.status != 0) {
+ alert("HufBuild error: "+h.status);
+ return -1;
+ }
+ zip_fixed_tl = h.root;
+ zip_fixed_bl = h.m;
+
+ // distance table
+ for(i = 0; i < 30; i++) // make an incomplete code set
+ l[i] = 5;
+ zip_fixed_bd = 5;
+
+ h = new zip_HuftBuild(l, 30, 0, zip_cpdist, zip_cpdext, zip_fixed_bd);
+ if(h.status > 1) {
+ zip_fixed_tl = null;
+ alert("HufBuild error: "+h.status);
+ return -1;
+ }
+ zip_fixed_td = h.root;
+ zip_fixed_bd = h.m;
+ }
+
+ zip_tl = zip_fixed_tl;
+ zip_td = zip_fixed_td;
+ zip_bl = zip_fixed_bl;
+ zip_bd = zip_fixed_bd;
+ return zip_inflate_codes(buff, off, size);
+}
+
+function zip_inflate_dynamic(buff, off, size) {
+ // decompress an inflated type 2 (dynamic Huffman codes) block.
+ var i; // temporary variables
+ var j;
+ var l; // last length
+ var n; // number of lengths to get
+ var t; // (zip_HuftNode) literal/length code table
+ var nb; // number of bit length codes
+ var nl; // number of literal/length codes
+ var nd; // number of distance codes
+ var ll = new Array(286+30); // literal/length and distance code lengths
+ var h; // (zip_HuftBuild)
+
+ for(i = 0; i < ll.length; i++)
+ ll[i] = 0;
+
+ // read in table lengths
+ zip_NEEDBITS(5);
+ nl = 257 + zip_GETBITS(5); // number of literal/length codes
+ zip_DUMPBITS(5);
+ zip_NEEDBITS(5);
+ nd = 1 + zip_GETBITS(5); // number of distance codes
+ zip_DUMPBITS(5);
+ zip_NEEDBITS(4);
+ nb = 4 + zip_GETBITS(4); // number of bit length codes
+ zip_DUMPBITS(4);
+ if(nl > 286 || nd > 30)
+ return -1; // bad lengths
+
+ // read in bit-length-code lengths
+ for(j = 0; j < nb; j++)
+ {
+ zip_NEEDBITS(3);
+ ll[zip_border[j]] = zip_GETBITS(3);
+ zip_DUMPBITS(3);
+ }
+ for(; j < 19; j++)
+ ll[zip_border[j]] = 0;
+
+ // build decoding table for trees--single level, 7 bit lookup
+ zip_bl = 7;
+ h = new zip_HuftBuild(ll, 19, 19, null, null, zip_bl);
+ if(h.status != 0)
+ return -1; // incomplete code set
+
+ zip_tl = h.root;
+ zip_bl = h.m;
+
+ // read in literal and distance code lengths
+ n = nl + nd;
+ i = l = 0;
+ while(i < n) {
+ zip_NEEDBITS(zip_bl);
+ t = zip_tl.list[zip_GETBITS(zip_bl)];
+ j = t.b;
+ zip_DUMPBITS(j);
+ j = t.n;
+ if(j < 16) // length of code in bits (0..15)
+ ll[i++] = l = j; // save last length in l
+ else if(j == 16) { // repeat last length 3 to 6 times
+ zip_NEEDBITS(2);
+ j = 3 + zip_GETBITS(2);
+ zip_DUMPBITS(2);
+ if(i + j > n)
+ return -1;
+ while(j-- > 0)
+ ll[i++] = l;
+ } else if(j == 17) { // 3 to 10 zero length codes
+ zip_NEEDBITS(3);
+ j = 3 + zip_GETBITS(3);
+ zip_DUMPBITS(3);
+ if(i + j > n)
+ return -1;
+ while(j-- > 0)
+ ll[i++] = 0;
+ l = 0;
+ } else { // j == 18: 11 to 138 zero length codes
+ zip_NEEDBITS(7);
+ j = 11 + zip_GETBITS(7);
+ zip_DUMPBITS(7);
+ if(i + j > n)
+ return -1;
+ while(j-- > 0)
+ ll[i++] = 0;
+ l = 0;
+ }
+ }
+
+ // build the decoding tables for literal/length and distance codes
+ zip_bl = zip_lbits;
+ h = new zip_HuftBuild(ll, nl, 257, zip_cplens, zip_cplext, zip_bl);
+ if(zip_bl == 0) // no literals or lengths
+ h.status = 1;
+ if(h.status != 0) {
+ if(h.status == 1)
+ ;// **incomplete literal tree**
+ return -1; // incomplete code set
+ }
+ zip_tl = h.root;
+ zip_bl = h.m;
+
+ for(i = 0; i < nd; i++)
+ ll[i] = ll[i + nl];
+ zip_bd = zip_dbits;
+ h = new zip_HuftBuild(ll, nd, 0, zip_cpdist, zip_cpdext, zip_bd);
+ zip_td = h.root;
+ zip_bd = h.m;
+
+ if(zip_bd == 0 && nl > 257) { // lengths but no distances
+ // **incomplete distance tree**
+ return -1;
+ }
+
+ if(h.status == 1) {
+ ;// **incomplete distance tree**
+ }
+ if(h.status != 0)
+ return -1;
+
+ // decompress until an end-of-block code
+ return zip_inflate_codes(buff, off, size);
+}
+
+function zip_inflate_start() {
+ var i;
+
+ if(zip_slide == null)
+ zip_slide = new Array(2 * zip_WSIZE);
+ zip_wp = 0;
+ zip_bit_buf = 0;
+ zip_bit_len = 0;
+ zip_method = -1;
+ zip_eof = false;
+ zip_copy_leng = zip_copy_dist = 0;
+ zip_tl = null;
+}
+
+function zip_inflate_internal(buff, off, size) {
+ // decompress an inflated entry
+ var n, i;
+
+ n = 0;
+ while(n < size) {
+ if(zip_eof && zip_method == -1)
+ return n;
+
+ if(zip_copy_leng > 0) {
+ if(zip_method != zip_STORED_BLOCK) {
+ // STATIC_TREES or DYN_TREES
+ while(zip_copy_leng > 0 && n < size) {
+ zip_copy_leng--;
+ zip_copy_dist &= zip_WSIZE - 1;
+ zip_wp &= zip_WSIZE - 1;
+ buff[off + n++] = zip_slide[zip_wp++] =
+ zip_slide[zip_copy_dist++];
+ }
+ } else {
+ while(zip_copy_leng > 0 && n < size) {
+ zip_copy_leng--;
+ zip_wp &= zip_WSIZE - 1;
+ zip_NEEDBITS(8);
+ buff[off + n++] = zip_slide[zip_wp++] = zip_GETBITS(8);
+ zip_DUMPBITS(8);
+ }
+ if(zip_copy_leng == 0)
+ zip_method = -1; // done
+ }
+ if(n == size)
+ return n;
+ }
+
+ if(zip_method == -1) {
+ if(zip_eof)
+ break;
+
+ // read in last block bit
+ zip_NEEDBITS(1);
+ if(zip_GETBITS(1) != 0)
+ zip_eof = true;
+ zip_DUMPBITS(1);
+
+ // read in block type
+ zip_NEEDBITS(2);
+ zip_method = zip_GETBITS(2);
+ zip_DUMPBITS(2);
+ zip_tl = null;
+ zip_copy_leng = 0;
+ }
+
+ switch(zip_method) {
+ case 0: // zip_STORED_BLOCK
+ i = zip_inflate_stored(buff, off + n, size - n);
+ break;
+
+ case 1: // zip_STATIC_TREES
+ if(zip_tl != null)
+ i = zip_inflate_codes(buff, off + n, size - n);
+ else
+ i = zip_inflate_fixed(buff, off + n, size - n);
+ break;
+
+ case 2: // zip_DYN_TREES
+ if(zip_tl != null)
+ i = zip_inflate_codes(buff, off + n, size - n);
+ else
+ i = zip_inflate_dynamic(buff, off + n, size - n);
+ break;
+
+ default: // error
+ i = -1;
+ break;
+ }
+
+ if(i == -1) {
+ if(zip_eof)
+ return 0;
+ return -1;
+ }
+ n += i;
+ }
+ return n;
+}
+
+function zip_inflate(str) {
+ var out, buff;
+ var i, j;
+
+ zip_inflate_start();
+ zip_inflate_data = str;
+ zip_inflate_pos = 0;
+
+ buff = new Array(1024);
+ out = "";
+ while((i = zip_inflate_internal(buff, 0, buff.length)) > 0) {
+ for(j = 0; j < i; j++)
+ out += String.fromCharCode(buff[j]);
+ }
+ zip_inflate_data = null; // G.C.
+ return out;
+}
+
+//
+// end of the script of Masanao Izumo.
+//
+
+// we add the compression method for JSZip
+if(!JSZip.compressions["DEFLATE"]) {
+ JSZip.compressions["DEFLATE"] = {
+ magic : "\x08\x00",
+ uncompress : zip_inflate
+ }
+} else {
+ JSZip.compressions["DEFLATE"].uncompress = zip_inflate;
+}
+
+})();
View
396 jszip-load.js
@@ -0,0 +1,396 @@
+/**
+
+JSZip - A Javascript class for generating Zip files
+<http://jszip.stuartk.co.uk>
+
+(c) 2011 David Duponchel <d.duponchel@gmail.com>
+Licenced under the GPLv3 and the MIT licences
+
+**/
+(function () {
+
+ /**
+ * Prettify a string read as binary.
+ * @param str the string to prettify.
+ * @return a pretty string.
+ */
+ var pretty = function (str) {
+ var res = '', code, i;
+ for (i = 0; i < str.length; i++)
+ {
+ code = str.charCodeAt(i);
+ res += '\\x' + (code < 10 ? "0" : "") + code.toString(16);
+ }
+ return res;
+ };
+
+ /**
+ * Find a compression registered in JSZip.
+ * @param compressionMethod the method magic to find.
+ * @return the JSZip compression object, null if none found.
+ */
+ var findCompression = function (compressionMethod)
+ {
+ for (var method in JSZip.compressions)
+ {
+ if (JSZip.compressions[method].magic === compressionMethod)
+ {
+ return JSZip.compressions[method];
+ }
+ }
+ return null;
+ };
+
+ /**
+ * @Class StreamReader
+ * Read bytes from a stream.
+ * @param stream the stream to read.
+ */
+ function StreamReader(stream) {
+ this.stream = stream;
+ this.index = 0;
+ }
+ /**
+ * Check that the offset will not go too far.
+ * @param offset the additional offset to check.
+ * @throws an Error if the offset is out of bounds.
+ */
+ StreamReader.prototype.checkRange = function (offset)
+ {
+ if (this.index + offset > this.stream.length)
+ {
+ throw new Error("End of stream reached (stream length = " + this.stream.length + ", asked index = " + (this.index + offset) + ")");
+ }
+ };
+ /**
+ * Check if the end of the file has been reached.
+ * @return true if it is the case, false otherwise.
+ */
+ StreamReader.prototype.eof = function ()
+ {
+ return this.index >= this.stream.length;
+ };
+ /**
+ * Get the byte at the specified index.
+ * @param i the index to use.
+ * @return a byte.
+ */
+ StreamReader.prototype.byteAt = function(i)
+ {
+ return this.stream.charCodeAt(i) & 0xff;
+ };
+ /**
+ * Get the next byte of this stream.
+ * @return the next byte.
+ */
+ StreamReader.prototype.byte = function ()
+ {
+ this.checkRange(1);
+ return this.byteAt(this.index++ + 1);
+ };
+ /**
+ * Get the next number with a given byte size.
+ * @param size the number of bytes to read.
+ * @return the corresponding number.
+ */
+ StreamReader.prototype.int = function (size)
+ {
+ var result = 0, i;
+ this.checkRange(size);
+ for(i = size - 1; i >= 0; i--)
+ {
+ result = (result << 8) + this.byteAt(this.index + i);
+ }
+ this.index += size;
+ return result;
+ };
+ /**
+ * Get the next string with a given byte size.
+ * @param size the number of bytes to read.
+ * @return the corresponding string.
+ */
+ StreamReader.prototype.string = function (size)
+ {
+ var result = "", i, code;
+ this.checkRange(size);
+ for(i = 0; i < size; i++)
+ {
+ code = this.byteAt(this.index + i);
+ result += String.fromCharCode(code);
+ }
+ this.index += size;
+ return result;
+ };
+ /**
+ * Get the next date.
+ * @return the date.
+ */
+ StreamReader.prototype.date = function ()
+ {
+ var dostime = this.int(4);
+ return new Date(
+ ((dostime >> 25) & 0x7f) + 1980, // year
+ ((dostime >> 21) & 0x0f) - 1, // month
+ (dostime >> 16) & 0x1f, // day
+ (dostime >> 11) & 0x1f, // hour
+ (dostime >> 5) & 0x3f, // minute
+ (dostime & 0x1f) << 1); // second
+ };
+
+ /**
+ * @Class ZipEntry
+ * An entry in the zip file.
+ */
+ function ZipEntry()
+ {
+ }
+ /**
+ * say if the file is encrypted.
+ * @return true if the file is encrypted, false otherwise.
+ */
+ ZipEntry.prototype.isEncrypted = function ()
+ {
+ return this.bitFlag & 0x0001 === 0x0001;
+ },
+ /**
+ * say if the file has a data decriptor.
+ * @return true if the file has a data descriptor, false otherwise.
+ */
+ ZipEntry.prototype.hasDataDescriptor = function ()
+ {
+ return this.bitFlag & 0x0008 === 0x0008;
+ },
+ /**
+ * Read the local part header of a zip file and add the info in this object.
+ * @param reader the reader to use.
+ */
+ ZipEntry.prototype.readLocalPartHeader = function(reader)
+ {
+ // the signature has already been consumed
+ this.versionNeeded = reader.int(2);
+ this.bitFlag = reader.int(2);
+ this.compressionMethod = reader.string(2);
+ this.date = reader.date();
+ this.crc32 = reader.int(4);
+ this.compressedSize = reader.int(4);
+ this.uncompressedSize = reader.int(4);
+ this.fileNameLength = reader.int(2);
+ this.extraFieldsLength = reader.int(2);
+
+ if (this.isEncrypted())
+ {
+ throw new Error("Encrypted zip are not supported");
+ }
+ if (this.hasDataDescriptor())
+ {
+ throw new Error("Data descriptor not supported");
+ }
+ };
+ /**
+ * Read the local part of a zip file and add the info in this object.
+ * @param reader the reader to use.
+ */
+ ZipEntry.prototype.readLocalPart = function(reader)
+ {
+ var compression;
+
+ this.readLocalPartHeader(reader);
+
+ this.fileName = reader.string(this.fileNameLength);
+ this.readExtraFields(reader, this.extraFieldsLength);
+ this.compressedFileData = reader.string(this.compressedSize);
+ this.uncompressedFileData = null;
+
+ compression = findCompression(this.compressionMethod);
+ if (compression === null) // no compression found
+ {
+ throw new Error("compression " + this.compressionMethod + " unknown");
+ }
+ this.uncompressedFileData = compression.uncompress(this.compressedFileData);
+ };
+ /**
+ * Read the central part of a zip file and add the info in this object.
+ * @param reader the reader to use.
+ */
+ ZipEntry.prototype.readCentralPart = function(reader)
+ {
+ this.versionMadeBy = reader.string(2);
+
+ this.readLocalPartHeader(reader);
+
+ this.fileCommentLength = reader.int(2);
+ this.diskNumberStart = reader.int(2);
+ this.internalFileAttributes = reader.int(2);
+ this.externalFileAttributes = reader.int(4);
+ this.localHeaderOffset = reader.int(4);
+
+ this.fileName = reader.string(this.fileNameLength);
+ this.readExtraFields(reader, this.extraFieldsLength);
+ this.fileComment = reader.string(this.fileCommentLength);
+
+ // warning, this is true only for zip with madeBy == DOS (plateform dependent feature)
+ this.dir = this.externalFileAttributes & 0x00000010 ? true : false;
+ };
+ /**
+ * Read the central part of a zip file and add the info in this object.
+ * @param reader the reader to use.
+ */
+ ZipEntry.prototype.readExtraFields = function(reader, extraFieldsLength)
+ {
+ var start = reader.index,
+ extraFieldId,
+ extraFieldLength,
+ extraFieldValue;
+
+ this.extraFields = this.extraFields || [];
+
+ while (reader.index < start + extraFieldsLength)
+ {
+ extraFieldId = reader.int(2);
+ extraFieldLength = reader.int(2);
+ extraFieldValue = reader.string(extraFieldLength);
+
+ this.extraFields.push({
+ id: extraFieldId,
+ length: extraFieldLength,
+ value: extraFieldValue
+ });
+ }
+ }
+
+
+ /**
+ * @Class ZipEntries
+ * All the entries in the zip file.
+ * @param data the binary stream to load.
+ */
+ function ZipEntries(data)
+ {
+ this.files = {};
+ if (data) this.load(data);
+ }
+ /**
+ * Add a ZipEntry created after a local record.
+ * @param zipEntry the zip entry to add.
+ * @param offset the number of bytes from the start of this archive.
+ */
+ ZipEntries.prototype.addLocal = function (zipEntry, offset)
+ {
+ zipEntry.localHeaderOffset = offset;
+ this.files['disk0-offset' + offset] = zipEntry;
+ };
+ /**
+ * Add a ZipEntry created after a central directory record.
+ * @param zipEntry the zip entry to add.
+ */
+ ZipEntries.prototype.addCentral = function(zipEntry)
+ {
+ var file, i;
+ // if we have a central directory recort, the local file header must be already here.
+ file = this.files['disk0-offset' + zipEntry.localHeaderOffset];
+ // they contain similiar informations, merging
+ for(i in zipEntry)
+ {
+ file[i] = (typeof file[i] === "undefined" || file[i] === null) ? zipEntry[i] : file[i];
+ }
+ };
+ /**
+ * Read the end of the central directory.
+ * @param reader the reader to use.
+ */
+ ZipEntries.prototype.readEndOfCentral = function (reader)
+ {
+ this.diskNumber = reader.int(2);
+ this.diskWithCentralDirStart = reader.int(2);
+ this.centralDirRecordsOnThisDisk = reader.int(2);
+ this.centralDirRecords = reader.int(2);
+ this.centralDirSize = reader.int(4);
+ this.centralDirOffset = reader.int(4);
+ this.zipCommentLength = reader.int(2);
+ this.zipComment = reader.string(this.zipCommentLength);
+ };
+ /**
+ * Read a zip file and create ZipEntries.
+ * @param data the binary string representing a zip file.
+ */
+ ZipEntries.prototype.load = function(data)
+ {
+ var reader = new StreamReader(data),
+ hasMoreFiles = true,
+ offset, signature, file, size;
+ while(hasMoreFiles)
+ {
+ offset = reader.index;
+ signature = reader.string(4);
+ // console.log(pretty(signature));
+ switch(signature)
+ {
+ case JSZip.signature.LOCAL_FILE_HEADER: // local file header signature
+ file = new ZipEntry();
+ file.readLocalPart(reader);
+ this.addLocal(file, offset);
+ break;
+ case JSZip.signature.CENTRAL_FILE_HEADER: // central file header signature
+ file = new ZipEntry();
+ file.readCentralPart(reader);
+ this.addCentral(file);
+ break;
+ case JSZip.signature.CENTRAL_DIRECTORY_END: // end of central dir signature
+ this.readEndOfCentral(reader);
+ break;
+ case "\x50\x4b\x06\x08": // archive extra data signature
+ throw new Error("Central Directory Encryption Feature not supported");
+ case "\x50\x4b\x05\x05": // Digital signature
+ // not supported, but don't block the process : discard information
+ size = reader.int(2);
+ reader.string(size);
+ break;
+ case "\x50\x4b\x06\x06": // zip64 end of central directory record
+ case "\x50\x4b\x06\x07": // zip64 end of central directory locator
+ throw new Error("ZIP64 Feature not supported");
+ case "\x50\x4b\x07\x08": // data descriptor record
+ // the spec says that the signature is recommended but optional.
+ // I hope everyone follow this recommendation :D
+ // This data is only useful when reading on a non-seekable device.
+ reader.string(12);
+ // TODO 4+2*8 bytes for zip64
+ break;
+ default:
+ throw new Error("signature " + pretty(signature) + " unknown");
+ }
+ hasMoreFiles = !reader.eof();
+ }
+ };
+
+ /**
+ * Implementation of the load method of JSZip.
+ * It uses the above classes to decode a zip file, and load every files.
+ * @param data the data to load.
+ * @param options Options for loading the stream.
+ * options.base64 : is the stream in base64 ? default : false
+ */
+ JSZip.prototype.load = function(data, options)
+ {
+ var files, zipEntries, i, input;
+ options = options || {};
+ if(options.base64)
+ {
+ data = JSZipBase64.decode(data);
+ }
+
+ zipEntries = new ZipEntries(data);
+ files = zipEntries.files;
+ for (i in files)
+ {
+ input = files[i];
+ this.add(input.fileName, input.uncompressedFileData, {
+ binary:true,
+ date:input.date,
+ dir:input.dir
+ });
+ }
+
+ return this;
+ }
+
+})();
View
27 jszip.js
@@ -39,6 +39,24 @@ function JSZip(compression)
}
}
+JSZip.signature = {
+ LOCAL_FILE_HEADER : "\x50\x4b\x03\x04",
+ CENTRAL_FILE_HEADER : "\x50\x4b\x01\x02",
+ CENTRAL_DIRECTORY_END : "\x50\x4b\x05\x06"
+};
+
+/**
+ * Load a zip stream into the current JSZip object.
+ * @param stream The stream to load
+ * @param options Options for loading the stream.
+ * options.base64 : is the stream in base64 ? default : false
+ * @return this JSZip object
+ */
+JSZip.prototype.load = function (stream, options)
+{
+ throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
+};
+
/**
* Add a file to the zip file
* @param name The name of the file
@@ -227,9 +245,9 @@ JSZip.prototype.generate = function(asBytes)
if( !this.files.hasOwnProperty(name) ) { continue; }
var fileRecord = "", dirRecord = "";
- fileRecord = "\x50\x4b\x03\x04" + this.files[name].header + name + this.files[name].data;
+ fileRecord = JSZip.signature.LOCAL_FILE_HEADER + this.files[name].header + name + this.files[name].data;
- dirRecord = "\x50\x4b\x01\x02" +
+ dirRecord = JSZip.signature.CENTRAL_FILE_HEADER +
// version made by (00: DOS)
"\x14\x00" +
// file header (common to file and central directory)
@@ -259,7 +277,7 @@ JSZip.prototype.generate = function(asBytes)
var dirEnd = "";
// end of central dir signature
- dirEnd = "\x50\x4b\x05\x06" +
+ dirEnd = JSZip.signature.CENTRAL_DIRECTORY_END +
// number of this disk
"\x00\x00" +
// number of the disk with the start of the central directory
@@ -296,6 +314,9 @@ JSZip.compressions = {
magic : "\x00\x00",
compress : function (content) {
return content; // no compression
+ },
+ uncompress : function (content) {
+ return content; // no compression
}
}
};
View
20 test/index.html
@@ -4,7 +4,9 @@
<title>JavaScript Zip Testing</title>
<link media="screen" href="qunit.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="../jszip.js"></script>
+<script type="text/javascript" src="../jszip-load.js"></script>
<script type="text/javascript" src="../jszip-deflate.js"></script>
+<script type="text/javascript" src="../jszip-inflate.js"></script>
<script type="text/javascript" src="qunit.js"></script>
<script type="text/javascript">
@@ -23,6 +25,13 @@
return true;
}
+function reload(bytesStream)
+{
+ var content = new JSZip().load(bytesStream, true).generate();
+ var actual = JSZipBase64.decode(content);
+ return actual;
+}
+
var refZips = [];
refZips["text"]=JSZipBase64.decode("UEsDBAoDAAAAAJx08Trj5ZWwDAAAAAwAAAAJAAAASGVsbG8udHh0SGVsbG8gV29ybGQKUEsBAhQDCgMAAAAAnHTxOuPllbAMAAAADAAAAAkAAAAAAAAAAAAggKSBAAAAAEhlbGxvLnR4dFBLBQYAAAAAAQABADcAAAAzAAAAAAA=");
refZips["utf8"]=JSZipBase64.decode("UEsDBAoAAAAAAJp95Tx8M2u8CgAAAAoAAAAKAAAAYW1vdW50LnR4dMOi4oCawqwxNQpQSwECFAAKAAAAAACafeU8fDNrvAoAAAAKAAAACgAAAAAAAAAAAAAAAAAAAAAAYW1vdW50LnR4dFBLBQYAAAAAAQABADgAAAAyAAAAAAA=");
@@ -64,7 +73,7 @@
18 Total
*/
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
-
+ equals(reload(actual), actual, "Generated ZIP can be parsed");
});
test("Zip text file with UTF-8 characters", function()
@@ -78,7 +87,7 @@
var actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
-
+ equals(reload(actual), actual, "Generated ZIP can be parsed");
});
test("Zip text file with date", function()
@@ -100,7 +109,7 @@
10 Total
*/
ok(similar(actual, expected, 10) , "Generated ZIP matches reference ZIP");
-
+ equals(reload(actual), actual, "Generated ZIP can be parsed");
});
@@ -115,7 +124,7 @@
actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
-
+ equals(reload(actual), actual, "Generated ZIP can be parsed");
});
test("Zip empty folder", function()
@@ -129,7 +138,7 @@
actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
-
+ equals(reload(actual), actual, "Generated ZIP can be parsed");
});
test("Zip text, folder and image", function()
@@ -157,6 +166,7 @@
//console.log("data:application/zip;base64,"+content);
ok(similar(actual, expected, 54) , "Generated ZIP matches reference ZIP");
+ equals(reload(actual), actual, "Generated ZIP can be parsed");
});
test("Finding a file", function()

0 comments on commit f02df57

Please sign in to comment.
Something went wrong with that request. Please try again.