diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py index b66d96010b..68f1999b16 100755 --- a/python/google/protobuf/internal/message_test.py +++ b/python/google/protobuf/internal/message_test.py @@ -549,6 +549,15 @@ class MessageTest(unittest.TestCase): self.assertEqual([4, 3, 2, 1], [m.bb for m in msg.repeated_nested_message[::-1]]) + def testSortEmptyRepeated(self, message_module): + message = message_module.NestedTestAllTypes() + self.assertFalse(message.HasField('child')) + self.assertFalse(message.HasField('payload')) + message.child.repeated_child.sort() + message.payload.repeated_int32.sort() + self.assertFalse(message.HasField('child')) + self.assertFalse(message.HasField('payload')) + def testSortingRepeatedScalarFieldsDefaultComparator(self, message_module): """Check some different types with the default comparator.""" message = message_module.TestAllTypes() diff --git a/python/repeated.c b/python/repeated.c index 57e347939b..7940b4d36f 100644 --- a/python/repeated.c +++ b/python/repeated.c @@ -473,11 +473,14 @@ static PyObject* PyUpb_RepeatedContainer_Sort(PyObject* pself, PyObject* args, } } + if (PyUpb_RepeatedContainer_Length(pself) == 0) Py_RETURN_NONE; + PyObject* ret = NULL; PyObject* full_slice = NULL; PyObject* list = NULL; PyObject* m = NULL; PyObject* res = NULL; + if ((full_slice = PySlice_New(NULL, NULL, NULL)) && (list = PyUpb_RepeatedContainer_Subscript(pself, full_slice)) && (m = PyObject_GetAttrString(list, "sort")) &&