bits.js 1.8 KB

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