🐛 avoid stackoverflow in json stringify

This commit is contained in:
ValKmjolnir 2023-12-12 00:05:38 +08:00
parent c59743b2ed
commit 6e819391aa
2 changed files with 28 additions and 0 deletions

View File

@ -115,6 +115,12 @@ std::string json::var_generate(var& value) {
}
std::string json::vector_generate(nas_vec& vect) {
// avoid stackoverflow
if (vect.printed) {
error_info() += "json::stringify: get vector containing itself\n";
return "undefined";
}
vect.printed = true;
std::string out = "[";
for(auto& i : vect.elems) {
out += var_generate(i) + ",";
@ -123,10 +129,17 @@ std::string json::vector_generate(nas_vec& vect) {
out.pop_back();
}
out += "]";
vect.printed = false;
return out;
}
std::string json::hash_generate(nas_hash& hash) {
// avoid stackoverflow
if (hash.printed) {
error_info() += "json::stringify: get hash containing itself\n";
return "undefined";
}
hash.printed = true;
std::string out = "{";
for(auto& i : hash.elems) {
out += "\"" + i.first + "\":";
@ -136,6 +149,7 @@ std::string json::hash_generate(nas_hash& hash) {
out.pop_back();
}
out += "}";
hash.printed = false;
return out;
}

View File

@ -66,6 +66,20 @@ test_func(json.stringify({
test_func("");
println();
func {
var a = {};
a.a = a;
var b = [];
append(b, b);
println(json.stringify(a));
println(json.get_error());
println(json.stringify(b));
println(json.get_error());
println();
}();
var test_json = func(json) {
var bar = process_bar.high_resolution_bar(30);
var tmp = [