Merge #10114: [tests] sync_with_ping should assert that ping hasn't timed out
[bitcoinplatinum.git] / src / univalue / lib / univalue_write.cpp
blobcfbdad3284ed53215258eba8b6166840c9813937
1 // Copyright 2014 BitPay Inc.
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include <iomanip>
6 #include <sstream>
7 #include <stdio.h>
8 #include "univalue.h"
9 #include "univalue_escapes.h"
11 using namespace std;
13 static string json_escape(const string& inS)
15 string outS;
16 outS.reserve(inS.size() * 2);
18 for (unsigned int i = 0; i < inS.size(); i++) {
19 unsigned char ch = inS[i];
20 const char *escStr = escapes[ch];
22 if (escStr)
23 outS += escStr;
24 else
25 outS += ch;
28 return outS;
31 string UniValue::write(unsigned int prettyIndent,
32 unsigned int indentLevel) const
34 string s;
35 s.reserve(1024);
37 unsigned int modIndent = indentLevel;
38 if (modIndent == 0)
39 modIndent = 1;
41 switch (typ) {
42 case VNULL:
43 s += "null";
44 break;
45 case VOBJ:
46 writeObject(prettyIndent, modIndent, s);
47 break;
48 case VARR:
49 writeArray(prettyIndent, modIndent, s);
50 break;
51 case VSTR:
52 s += "\"" + json_escape(val) + "\"";
53 break;
54 case VNUM:
55 s += val;
56 break;
57 case VBOOL:
58 s += (val == "1" ? "true" : "false");
59 break;
62 return s;
65 static void indentStr(unsigned int prettyIndent, unsigned int indentLevel, string& s)
67 s.append(prettyIndent * indentLevel, ' ');
70 void UniValue::writeArray(unsigned int prettyIndent, unsigned int indentLevel, string& s) const
72 s += "[";
73 if (prettyIndent)
74 s += "\n";
76 for (unsigned int i = 0; i < values.size(); i++) {
77 if (prettyIndent)
78 indentStr(prettyIndent, indentLevel, s);
79 s += values[i].write(prettyIndent, indentLevel + 1);
80 if (i != (values.size() - 1)) {
81 s += ",";
82 if (prettyIndent)
83 s += " ";
85 if (prettyIndent)
86 s += "\n";
89 if (prettyIndent)
90 indentStr(prettyIndent, indentLevel - 1, s);
91 s += "]";
94 void UniValue::writeObject(unsigned int prettyIndent, unsigned int indentLevel, string& s) const
96 s += "{";
97 if (prettyIndent)
98 s += "\n";
100 for (unsigned int i = 0; i < keys.size(); i++) {
101 if (prettyIndent)
102 indentStr(prettyIndent, indentLevel, s);
103 s += "\"" + json_escape(keys[i]) + "\":";
104 if (prettyIndent)
105 s += " ";
106 s += values.at(i).write(prettyIndent, indentLevel + 1);
107 if (i != (values.size() - 1))
108 s += ",";
109 if (prettyIndent)
110 s += "\n";
113 if (prettyIndent)
114 indentStr(prettyIndent, indentLevel - 1, s);
115 s += "}";