You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.2 KiB

  1. const bigInt = require("big-integer");
  2. module.exports.leBuff2int = leBuff2int;
  3. module.exports.leInt2Buff = leInt2Buff;
  4. module.exports.beBuff2int = beBuff2int;
  5. module.exports.beInt2Buff = beInt2Buff;
  6. module.exports.stringifyBigInts = stringifyBigInts;
  7. module.exports.unstringifyBigInts = unstringifyBigInts;
  8. function leBuff2int (buff) {
  9. let res = bigInt.zero;
  10. for (let i=0; i<buff.length; i++) {
  11. const n = bigInt(buff[i]);
  12. res = res.add(n.shiftLeft(i*8));
  13. }
  14. return res;
  15. }
  16. function leInt2Buff(n, len) {
  17. let r = n;
  18. let o =0;
  19. const buff = Buffer.alloc(len);
  20. while ((r.gt(bigInt.zero))&&(o<buff.length)) {
  21. let c = Number(r.and(bigInt(255)));
  22. buff[o] = c;
  23. o++;
  24. r = r.shiftRight(8);
  25. }
  26. if (r.gt(bigInt.zero)) throw new Error("Number does not feed in buffer");
  27. return buff;
  28. }
  29. function beBuff2int (buff) {
  30. let res = bigInt.zero;
  31. for (let i=0; i<buff.length; i++) {
  32. const n = bigInt(buff[buff.length - i - 1]);
  33. res = res.add(n.shiftLeft(i*8));
  34. }
  35. return res;
  36. }
  37. function beInt2Buff(n, len) {
  38. let r = n;
  39. let o =len-1;
  40. const buff = Buffer.alloc(len);
  41. while ((r.greater(bigInt.zero))&&(o>=0)) {
  42. let c = Number(r.and(bigInt(255)));
  43. buff[o] = c;
  44. o--;
  45. r = r.shiftRight(8);
  46. }
  47. if (r.gt(bigInt.zero)) throw new Error("Number does not feed in buffer");
  48. return buff;
  49. }
  50. function stringifyBigInts(o) {
  51. if ((typeof(o) == "bigint") || o.isZero !== undefined) {
  52. return o.toString(10);
  53. } else if (Array.isArray(o)) {
  54. return o.map(stringifyBigInts);
  55. } else if (typeof o == "object") {
  56. const res = {};
  57. for (let k in o) {
  58. res[k] = stringifyBigInts(o[k]);
  59. }
  60. return res;
  61. } else {
  62. return o;
  63. }
  64. }
  65. function unstringifyBigInts(o) {
  66. if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) {
  67. return bigInt(o);
  68. } else if (Array.isArray(o)) {
  69. return o.map(unstringifyBigInts);
  70. } else if (typeof o == "object") {
  71. const res = {};
  72. for (let k in o) {
  73. res[k] = unstringifyBigInts(o[k]);
  74. }
  75. return res;
  76. } else {
  77. return o;
  78. }
  79. }