circom/src/utils.js
src/utils.jsRaw
1const fnv = require("fnv-plus");
2const bigInt = require("big-integer");
3
4module.exports.ident =ident;
5
6module.exports.extractSizes =extractSizes;
7module.exports.flatArray = flatArray;
8module.exports.csArr = csArr;
9module.exports.subArray = subArray;
10module.exports.accSizes = accSizes;
11module.exports.fnvHash = fnvHash;
12module.exports.stringifyBigInts = stringifyBigInts;
13module.exports.unstringifyBigInts = unstringifyBigInts;
14
15function ident(text) {
16 let lines = text.split("\n");
17 for (let i=0; i<lines.length; i++) {
18 if (lines[i]) lines[i] = " "+lines[i];
19 }
20 return lines.join("\n");
21}
22
23function extractSizes (o) {
24 if (! Array.isArray(o)) return [];
25 return [o.length, ...extractSizes(o[0])];
26}
27
28function flatArray(a) {
29 var res = [];
30 fillArray(res, a);
31 return res;
32
33 function fillArray(res, a) {
34 if (Array.isArray(a)) {
35 for (let i=0; i<a.length; i++) {
36 fillArray(res, a[i]);
37 }
38 } else {
39 res.push(a);
40 }
41 }
42}
43
44// Input [1,2,3]
45// Returns " ,1 ,2, 3"
46function csArr(_arr) {
47 let S = "";
48 const arr = _arr || [];
49 for (let i=0; i<arr.length; i++) {
50 S = " ,"+arr[i];
51 }
52 return S;
53}
54
55function subArray(value, sels) {
56 if ((!sels) || (sels.length == 0)) return value;
57
58 return subArray(value[sels[0]], sels.slice(1));
59}
60
61function accSizes(_sizes) {
62 const sizes = _sizes || [];
63 const accSizes = [1, 0];
64 for (let i=sizes.length-1; i>=0; i--) {
65 accSizes.unshift(accSizes[0]*sizes[i]);
66 }
67 return accSizes;
68}
69
70function fnvHash(str) {
71 return fnv.hash(str, 64).hex();
72}
73
74
75
76function stringifyBigInts(o) {
77 if ((typeof(o) == "bigint") || o.isZero !== undefined) {
78 return o.toString(10);
79 } else if (Array.isArray(o)) {
80 return o.map(stringifyBigInts);
81 } else if (typeof o == "object") {
82 const res = {};
83 for (let k in o) {
84 res[k] = stringifyBigInts(o[k]);
85 }
86 return res;
87 } else {
88 return o;
89 }
90}
91
92function unstringifyBigInts(o) {
93 if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) {
94 return bigInt(o);
95 } else if (Array.isArray(o)) {
96 return o.map(unstringifyBigInts);
97 } else if (typeof o == "object") {
98 const res = {};
99 for (let k in o) {
100 res[k] = unstringifyBigInts(o[k]);
101 }
102 return res;
103 } else {
104 return o;
105 }
106}
107
108
109