unsigned.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const Bn = require('bn.js')
  2. const Pipe = require('buffer-pipe')
  3. module.exports = {
  4. encode,
  5. decode,
  6. read,
  7. readBn,
  8. write
  9. }
  10. function read (stream) {
  11. return readBn(stream).toString()
  12. }
  13. function readBn (stream) {
  14. const num = new Bn(0)
  15. let shift = 0
  16. let byt
  17. while (true) {
  18. byt = stream.read(1)[0]
  19. num.ior(new Bn(byt & 0x7f).shln(shift))
  20. if (byt >> 7 === 0) {
  21. break
  22. } else {
  23. shift += 7
  24. }
  25. }
  26. return num
  27. }
  28. function write (number, stream) {
  29. const num = new Bn(number)
  30. while (true) {
  31. const i = num.maskn(7).toNumber()
  32. num.ishrn(7)
  33. if (num.isZero()) {
  34. stream.write([i])
  35. break
  36. } else {
  37. stream.write([i | 0x80])
  38. }
  39. }
  40. }
  41. /**
  42. * LEB128 encodeds an interger
  43. * @param {String|Number} num
  44. * @return {Buffer}
  45. */
  46. function encode (num) {
  47. const stream = new Pipe()
  48. write(num, stream)
  49. return stream.buffer
  50. }
  51. /**
  52. * decodes a LEB128 encoded interger
  53. * @param {Buffer} buffer
  54. * @return {String}
  55. */
  56. function decode (buffer) {
  57. const stream = new Pipe(buffer)
  58. return read(stream)
  59. }