Fix Value::resize to fill all array elements (#1265)

* Fix Value::resize to fill all array elements

Fixes #1264
This commit is contained in:
Billy Donahue 2021-02-09 23:50:37 -05:00 committed by GitHub
parent da9e17d257
commit fda274ddd2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 1 deletions

View File

@ -912,7 +912,8 @@ void Value::resize(ArrayIndex newSize) {
if (newSize == 0) if (newSize == 0)
clear(); clear();
else if (newSize > oldSize) else if (newSize > oldSize)
this->operator[](newSize - 1); for (ArrayIndex i = oldSize; i < newSize; ++i)
(*this)[i];
else { else {
for (ArrayIndex index = newSize; index < oldSize; ++index) { for (ArrayIndex index = newSize; index < oldSize; ++index) {
value_.map_->erase(index); value_.map_->erase(index);

View File

@ -12,6 +12,7 @@
#include "fuzz.h" #include "fuzz.h"
#include "jsontest.h" #include "jsontest.h"
#include <algorithm>
#include <cmath> #include <cmath>
#include <cstring> #include <cstring>
#include <functional> #include <functional>
@ -24,6 +25,7 @@
#include <memory> #include <memory>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <vector>
using CharReaderPtr = std::unique_ptr<Json::CharReader>; using CharReaderPtr = std::unique_ptr<Json::CharReader>;
@ -347,6 +349,17 @@ JSONTEST_FIXTURE_LOCAL(ValueTest, resizeArray) {
JSONTEST_ASSERT_EQUAL(array.size(), 0); JSONTEST_ASSERT_EQUAL(array.size(), 0);
} }
} }
JSONTEST_FIXTURE_LOCAL(ValueTest, resizePopulatesAllMissingElements) {
int n = 10;
Json::Value v;
v.resize(n);
JSONTEST_ASSERT_EQUAL(n, v.size());
JSONTEST_ASSERT_EQUAL(n, std::distance(v.begin(), v.end()));
for (const Json::Value& e : v)
JSONTEST_ASSERT_EQUAL(e, Json::Value{});
}
JSONTEST_FIXTURE_LOCAL(ValueTest, getArrayValue) { JSONTEST_FIXTURE_LOCAL(ValueTest, getArrayValue) {
Json::Value array; Json::Value array;
for (Json::ArrayIndex i = 0; i < 5; i++) for (Json::ArrayIndex i = 0; i < 5; i++)