node_core_bitop.js 968 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. class Bitop {
  2. constructor(buffer) {
  3. this.buffer = buffer;
  4. this.buflen = buffer.length;
  5. this.bufpos = 0;
  6. this.bufoff = 0;
  7. this.iserro = false;
  8. }
  9. read(n) {
  10. let v = 0;
  11. let d = 0;
  12. while (n) {
  13. if (n < 0 || this.bufpos >= this.buflen) {
  14. this.iserro = true;
  15. return 0;
  16. }
  17. this.iserro = false;
  18. d = this.bufoff + n > 8 ? 8 - this.bufoff : n;
  19. v <<= d;
  20. v += (this.buffer[this.bufpos] >> (8 - this.bufoff - d)) & (0xff >> (8 - d))
  21. this.bufoff += d;
  22. n -= d;
  23. if (this.bufoff == 8) {
  24. this.bufpos++;
  25. this.bufoff = 0;
  26. }
  27. }
  28. return v;
  29. }
  30. look(n) {
  31. let p = this.bufpos;
  32. let o = this.bufoff;
  33. let v = this.read(n);
  34. this.bufpos = p;
  35. this.bufoff = o;
  36. return v;
  37. }
  38. read_golomb() {
  39. let n;
  40. for (n = 0; this.read(1) == 0 && !this.iserro; n++);
  41. return (1 << n) + this.read(n) - 1;
  42. }
  43. }
  44. module.exports = Bitop;