bit_iterator.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
  2. // returns a function that reads bits.
  3. // takes a buffer iterator as input
  4. module.exports = function bitIterator(nextBuffer) {
  5. var bit = 0, byte = 0;
  6. var bytes = nextBuffer();
  7. var f = function(n) {
  8. if (n === null && bit != 0) { // align to byte boundary
  9. bit = 0
  10. byte++;
  11. return;
  12. }
  13. var result = 0;
  14. while(n > 0) {
  15. if (byte >= bytes.length) {
  16. byte = 0;
  17. bytes = nextBuffer();
  18. }
  19. var left = 8 - bit;
  20. if (bit === 0 && n > 0)
  21. f.bytesRead++;
  22. if (n >= left) {
  23. result <<= left;
  24. result |= (BITMASK[left] & bytes[byte++]);
  25. bit = 0;
  26. n -= left;
  27. } else {
  28. result <<= n;
  29. result |= ((bytes[byte] & (BITMASK[n] << (8 - n - bit))) >> (8 - n - bit));
  30. bit += n;
  31. n = 0;
  32. }
  33. }
  34. return result;
  35. };
  36. f.bytesRead = 0;
  37. return f;
  38. };