Skip to content

Commit

Permalink
[picojson] Let objects be ordered when serializing (#17027)
Browse files Browse the repository at this point in the history
This PR changes the serialization logic of objects to follow the insertion
order of elements to keep the output consistent across different platforms.
  • Loading branch information
Ubospica authored May 26, 2024
1 parent f498cef commit 4f1e2df
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions 3rdparty/picojson/picojson.h
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,24 @@ void value::_serialize(Iter oi, int indent) const {
if (indent != -1) {
++indent;
}

#if PICOJSON_USE_ORDERED_OBJECT
for (auto i = u_.object_->ordered_keys().begin(); i != u_.object_->ordered_keys().end();
++i) {
if (i != u_.object_->ordered_keys().begin()) {
*oi++ = ',';
}
if (indent != -1) {
_indent(oi, indent);
}
serialize_str(*i, oi);
*oi++ = ':';
if (indent != -1) {
*oi++ = ' ';
}
u_.object_->at(*i)._serialize(oi, indent);
}
#else
for (object::const_iterator i = u_.object_->begin(); i != u_.object_->end(); ++i) {
if (i != u_.object_->begin()) {
*oi++ = ',';
Expand All @@ -741,6 +759,7 @@ void value::_serialize(Iter oi, int indent) const {
}
i->second._serialize(oi, indent);
}
#endif
if (indent != -1) {
--indent;
if (!u_.object_->empty()) {
Expand Down
13 changes: 13 additions & 0 deletions 3rdparty/picojson/test_picojson.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,21 @@ void test_modifier() {
assert((obj.ordered_keys() == std::vector<std::string>{}));
}

void test_serializer() {
picojson::object obj;

obj["bar"] = picojson::value(static_cast<int64_t>(10));
obj["baz"] = picojson::value(10.5);
obj["foo"] = picojson::value(true);

picojson::value v(obj);

assert((v.serialize(false) == "{\"bar\":10,\"baz\":10.5,\"foo\":true}"));
}

int main() {
test_constructor();
test_modifier();
test_serializer();
return 0;
}

0 comments on commit 4f1e2df

Please sign in to comment.