lzw.js 2.4 KB

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