1 | define([ |
---|
2 | "dojo/_base/lang", // dojo.extend |
---|
3 | "../bits" |
---|
4 | ], function(lang, bits) { |
---|
5 | |
---|
6 | var lzw = lang.getObject("dojox.encoding.compression.lzw", true); |
---|
7 | /*===== |
---|
8 | lzw = dojox.encoding.compression.lzw; |
---|
9 | =====*/ |
---|
10 | |
---|
11 | var _bits = function(x){ |
---|
12 | var w = 1; |
---|
13 | for(var v = 2; x >= v; v <<= 1, ++w); |
---|
14 | return w; |
---|
15 | }; |
---|
16 | |
---|
17 | lzw.Encoder = function(n){ |
---|
18 | this.size = n; |
---|
19 | this.init(); |
---|
20 | }; |
---|
21 | |
---|
22 | lang.extend(lzw.Encoder, { |
---|
23 | init: function(){ |
---|
24 | this.dict = {}; |
---|
25 | for(var i = 0; i < this.size; ++i){ |
---|
26 | this.dict[String.fromCharCode(i)] = i; |
---|
27 | } |
---|
28 | this.width = _bits(this.code = this.size); |
---|
29 | this.p = ""; |
---|
30 | }, |
---|
31 | encode: function(value, stream){ |
---|
32 | var c = String.fromCharCode(value), p = this.p + c, r = 0; |
---|
33 | // if already in the dictionary |
---|
34 | if(p in this.dict){ |
---|
35 | this.p = p; |
---|
36 | return r; |
---|
37 | } |
---|
38 | stream.putBits(this.dict[this.p], this.width); |
---|
39 | // if we need to increase the code length |
---|
40 | if((this.code & (this.code + 1)) == 0){ |
---|
41 | stream.putBits(this.code++, r = this.width++); |
---|
42 | } |
---|
43 | // add new string |
---|
44 | this.dict[p] = this.code++; |
---|
45 | this.p = c; |
---|
46 | return r + this.width; |
---|
47 | }, |
---|
48 | flush: function(stream){ |
---|
49 | if(this.p.length == 0){ |
---|
50 | return 0; |
---|
51 | } |
---|
52 | stream.putBits(this.dict[this.p], this.width); |
---|
53 | this.p = ""; |
---|
54 | return this.width; |
---|
55 | } |
---|
56 | }); |
---|
57 | |
---|
58 | lzw.Decoder = function(n){ |
---|
59 | this.size = n; |
---|
60 | this.init(); |
---|
61 | }; |
---|
62 | |
---|
63 | lang.extend(lzw.Decoder, { |
---|
64 | init: function(){ |
---|
65 | this.codes = new Array(this.size); |
---|
66 | for(var i = 0; i < this.size; ++i){ |
---|
67 | this.codes[i] = String.fromCharCode(i); |
---|
68 | } |
---|
69 | this.width = _bits(this.size); |
---|
70 | this.p = -1; |
---|
71 | }, |
---|
72 | decode: function(stream){ |
---|
73 | var c = stream.getBits(this.width), v; |
---|
74 | if(c < this.codes.length){ |
---|
75 | v = this.codes[c]; |
---|
76 | if(this.p >= 0){ |
---|
77 | this.codes.push(this.codes[this.p] + v.substr(0, 1)); |
---|
78 | } |
---|
79 | }else{ |
---|
80 | if((c & (c + 1)) == 0){ |
---|
81 | this.codes.push(""); |
---|
82 | ++this.width; |
---|
83 | return ""; |
---|
84 | } |
---|
85 | var x = this.codes[this.p]; |
---|
86 | v = x + x.substr(0, 1); |
---|
87 | this.codes.push(v); |
---|
88 | } |
---|
89 | this.p = c; |
---|
90 | return v; |
---|
91 | } |
---|
92 | }); |
---|
93 | |
---|
94 | return lzw; |
---|
95 | }); |
---|