bits.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. define("dojox/encoding/bits", [
  2. "dojo/_base/lang" // dojo.extend
  3. ], function(lang) {
  4. var bits = lang.getObject("dojox.encoding.bits", true);
  5. /*=====
  6. bits = dojox.encoding.bits;
  7. =====*/
  8. bits.OutputStream = function(){
  9. this.reset();
  10. };
  11. lang.extend(bits.OutputStream, {
  12. reset: function(){
  13. this.buffer = [];
  14. this.accumulator = 0;
  15. this.available = 8;
  16. },
  17. putBits: function(value, width){
  18. while(width){
  19. var w = Math.min(width, this.available);
  20. var v = (w <= width ? value >>> (width - w) : value) << (this.available - w);
  21. this.accumulator |= v & (255 >>> (8 - this.available));
  22. this.available -= w;
  23. if(!this.available){
  24. this.buffer.push(this.accumulator);
  25. this.accumulator = 0;
  26. this.available = 8;
  27. }
  28. width -= w;
  29. }
  30. },
  31. getWidth: function(){
  32. return this.buffer.length * 8 + (8 - this.available);
  33. },
  34. getBuffer: function(){
  35. var b = this.buffer;
  36. if(this.available < 8){ b.push(this.accumulator & (255 << this.available)); }
  37. this.reset();
  38. return b;
  39. }
  40. });
  41. bits.InputStream = function(buffer, width){
  42. this.buffer = buffer;
  43. this.width = width;
  44. this.bbyte = this.bit = 0;
  45. };
  46. lang.extend(bits.InputStream, {
  47. getBits: function(width){
  48. var r = 0;
  49. while(width){
  50. var w = Math.min(width, 8 - this.bit);
  51. var v = this.buffer[this.bbyte] >>> (8 - this.bit - w);
  52. r <<= w;
  53. r |= v & ~(~0 << w);
  54. this.bit += w;
  55. if(this.bit == 8){
  56. ++this.bbyte;
  57. this.bit = 0;
  58. }
  59. width -= w;
  60. }
  61. return r;
  62. },
  63. getWidth: function(){
  64. return this.width - this.bbyte * 8 - this.bit;
  65. }
  66. });
  67. return bits;
  68. });