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