Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RepeatedField: unset by index #11425

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions php/ext/google/protobuf/array.c
Original file line number Diff line number Diff line change
Expand Up @@ -406,13 +406,13 @@ PHP_METHOD(RepeatedField, offsetUnset) {
return;
}

if (size == 0 || index != size - 1) {
if (size == 0 || index < 0 || index >= size) {
php_error_docref(NULL, E_USER_ERROR, "Cannot remove element at %ld.\n",
index);
return;
}

upb_Array_Resize(intern->array, size - 1, Arena_Get(&intern->arena));
upb_Array_Delete(intern->array, index, 1);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions php/src/Google/Protobuf/Internal/RepeatedField.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,13 +219,13 @@ public function offsetSet($offset, $value)
public function offsetUnset($offset)
{
$count = count($this->container);
if (!is_numeric($offset) || $count === 0 || $offset !== $count - 1) {
if (!is_numeric($offset) || $count === 0 || $offset < 0 || $offset >= $count) {
trigger_error(
"Cannot remove element at the given index",
E_USER_ERROR);
return;
}
array_pop($this->container);
array_splice($this->container, $offset, 1);
}

/**
Expand Down
27 changes: 27 additions & 0 deletions php/tests/ArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -655,4 +655,31 @@ public function testClone()
$arr2 = clone $arr;
$this->assertSame($arr[0], $arr2[0]);
}

#########################################################
# Test offsetUnset
#########################################################

public function testOffsetUnset()
{
$arr = new RepeatedField(GPBType::INT32);
$arr[] = 0;
$arr[] = 1;
$arr[] = 2;

$this->assertSame(3, count($arr));
$this->assertSame(0, $arr[0]);
$this->assertSame(1, $arr[1]);
$this->assertSame(2, $arr[2]);

$arr->offsetUnset(1);
$this->assertSame(0, $arr[0]);
$this->assertSame(2, $arr[1]);

$arr->offsetUnset(0);
$this->assertSame(2, $arr[0]);

$arr->offsetUnset(0);
$this->assertCount(0, $arr);
}
}