snarkjs/src/stringifybigint.js
src/stringifybigint.jsRaw
1/*
2 Copyright 2018 0kims association.
3
4 This file is part of snarkjs.
5
6 snarkjs is a free software: you can redistribute it and/or
7 modify it under the terms of the GNU General Public License as published by the
8 Free Software Foundation, either version 3 of the License, or (at your option)
9 any later version.
10
11 snarkjs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 more details.
15
16 You should have received a copy of the GNU General Public License along with
17 snarkjs. If not, see <https://www.gnu.org/licenses/>.
18*/
19
20const bigInt = require("./bigint.js");
21
22module.exports.stringifyBigInts = stringifyBigInts;
23module.exports.unstringifyBigInts = unstringifyBigInts;
24
25function stringifyBigInts(o) {
26 if ((typeof(o) == "bigint") || (o instanceof bigInt)) {
27 return o.toString(10);
28 } else if (Array.isArray(o)) {
29 return o.map(stringifyBigInts);
30 } else if (typeof o == "object") {
31 const res = {};
32 for (let k in o) {
33 res[k] = stringifyBigInts(o[k]);
34 }
35 return res;
36 } else {
37 return o;
38 }
39}
40
41function unstringifyBigInts(o) {
42 if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) {
43 return bigInt(o);
44 } else if (Array.isArray(o)) {
45 return o.map(unstringifyBigInts);
46 } else if (typeof o == "object") {
47 const res = {};
48 for (let k in o) {
49 res[k] = unstringifyBigInts(o[k]);
50 }
51 return res;
52 } else {
53 return o;
54 }
55}