Skip to content

Commit 49f3efe

Browse files
authored
replaced recursive calls with loops (#54)
1 parent 6297695 commit 49f3efe

15 files changed

+595
-319
lines changed

src/hjson_decode.cpp

Lines changed: 222 additions & 160 deletions
Large diffs are not rendered by default.

src/hjson_encode.cpp

Lines changed: 244 additions & 157 deletions
Large diffs are not rendered by default.

src/hjson_value.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ class Value::ValueImpl {
4949
ValueImpl(const std::string&);
5050
ValueImpl(Type);
5151
~ValueImpl();
52+
static void DeepClear(Value &val);
5253
};
5354

5455

@@ -112,16 +113,47 @@ Value::ValueImpl::ValueImpl(Type _type)
112113
}
113114

114115

116+
// Bottom-up destruction in order to avoid stack overflow due to recursive destructor calls.
117+
void Value::ValueImpl::DeepClear(Value &val) {
118+
// The map/vector will only be destroyed if use_count == 1
119+
if (val.size() && val.prv.use_count() == 1) {
120+
std::vector<std::pair<Value, int> > v;
121+
122+
v.emplace_back(val, 0);
123+
124+
while (!v.empty()) {
125+
if (v.back().second >= v.back().first.size()) {
126+
v.back().first.clear();
127+
v.pop_back();
128+
} else {
129+
Value &n = v.back().first[v.back().second];
130+
v.back().second++;
131+
// The map/vector will only be destroyed if use_count == 1
132+
if (n.size() && n.prv.use_count() == 1) {
133+
v.emplace_back(v.back().first[v.back().second - 1], 0);
134+
}
135+
}
136+
}
137+
}
138+
}
139+
140+
115141
Value::ValueImpl::~ValueImpl() {
116142
switch (type)
117143
{
118144
case Type::String:
119145
delete s;
120146
break;
121147
case Type::Vector:
148+
for (auto e = v->begin(); e != v->end(); ++e) {
149+
DeepClear(*e);
150+
}
122151
delete v;
123152
break;
124153
case Type::Map:
154+
for (auto e = m->m.begin(); e != m->m.end(); ++e) {
155+
DeepClear(e->second);
156+
}
125157
delete m;
126158
break;
127159
default:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
""
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
""
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
""

test/assets/failObj4_test.hjson

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
a: 1
2+
b: 2
3+
# trailing bracket in bracketless root
4+
}

test/assets/failStr9a_test.hjson

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[
2+
[
3+
=
4+
[[''''''
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
""
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
""

0 commit comments

Comments
 (0)