from Itzik S; see issue #28

with minor corrections
This commit is contained in:
Christopher Dunn 2015-01-20 16:24:11 -06:00
parent 9de2c2d84d
commit e87e41cdb0
2 changed files with 26 additions and 7 deletions

View File

@ -400,8 +400,7 @@ Json::Value obj_value(Json::objectValue); // {}
O(n) expensive operations.
Update 'removed' iff removed.
(This is a better pattern than removeMember().)
JSON_FAIL if !isValidIndex(i) or if not arrayObject
\return true iff removed
\return true iff removed (no exceptions)
*/
bool removeIndex(ArrayIndex i, Value* removed);

View File

@ -1018,12 +1018,32 @@ Value Value::removeMember(const std::string& key) {
return removeMember(key.c_str());
}
bool Value::removeIndex(ArrayIndex i, Value* removed) {
JSON_ASSERT_MESSAGE(this->type_ == arrayValue,
"in Json::Value::removeIndex(): requires arrayValue");
JSON_ASSERT_MESSAGE(this->isValidIndex(i),
"invalid index i=" << i << " for array of size " << this->size());
bool Value::removeIndex(ArrayIndex index, Value* removed) {
if (this->type_ != arrayValue) {
return false;
}
#ifdef JSON_VALUE_USE_INTERNAL_MAP
JSON_FAIL_MESSAGE("removeIndex is not implemented for ValueInternalArray.");
return false;
#else
CZString key(index);
ObjectValues::iterator it = this->value_.map_->find(key);
if (it == this->value_.map_->end()) {
return false;
}
*removed = it->second;
ArrayIndex oldSize = this->size();
// shift left all items left, into the place of the "removed"
for (ArrayIndex i=index; i<oldSize-1; i++){
CZString key(i);
(*this->value_.map_)[key] = (*this)[i+1];
}
// erase the last one ("leftover")
CZString keyLast(oldSize-1);
ObjectValues::iterator itLast = this->value_.map_->find(keyLast);
this->value_.map_->erase(itLast);
return true;
#endif
}
#ifdef JSON_USE_CPPTL