lzw.js 2.3 KB

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