splay.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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.splay"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojox.encoding.compression.splay"] = true;
  8. dojo.provide("dojox.encoding.compression.splay");
  9. dojo.require("dojox.encoding.bits");
  10. dojo.getObject("encoding.compression.splay", true, dojox);
  11. dojox.encoding.compression.Splay = function(n){
  12. this.up = new Array(2 * n + 1);
  13. this.left = new Array(n);
  14. this.right = new Array(n);
  15. this.reset();
  16. };
  17. dojo.extend(dojox.encoding.compression.Splay, {
  18. reset: function(){
  19. for(var i = 1; i < this.up.length; this.up[i] = Math.floor((i - 1) / 2), ++i);
  20. for(var i = 0; i < this.left.length; this.left[i] = 2 * i + 1, this.right[i] = 2 * i + 2, ++i);
  21. },
  22. splay: function(i){
  23. var a = i + this.left.length;
  24. do{
  25. var c = this.up[a];
  26. if(c){ // root
  27. // rotated pair
  28. var d = this.up[c];
  29. // swap descendants
  30. var b = this.left[d];
  31. if(c == b){
  32. b = this.right[d];
  33. this.right[d] = a;
  34. } else {
  35. this.left[d] = a;
  36. }
  37. this[a == this.left[c] ? "left" : "right"][c] = b;
  38. this.up[a] = d;
  39. this.up[b] = c;
  40. a = d;
  41. }else{
  42. a = c;
  43. }
  44. }while(a); // root
  45. },
  46. encode: function(value, stream){
  47. var s = [], a = value + this.left.length;
  48. do{
  49. s.push(this.right[this.up[a]] == a);
  50. a = this.up[a];
  51. }while(a); // root
  52. this.splay(value);
  53. var l = s.length;
  54. while(s.length){ stream.putBits(s.pop() ? 1 : 0, 1); }
  55. return l;
  56. },
  57. decode: function(stream){
  58. var a = 0; // root;
  59. do{
  60. a = this[stream.getBits(1) ? "right" : "left"][a];
  61. }while(a < this.left.length);
  62. a -= this.left.length;
  63. this.splay(a);
  64. return a;
  65. }
  66. });
  67. }