bpo-34574: Prevent OrderedDict iterators from exhaustion during pickling. (GH-9051)

(cherry picked from commit a5259fb05d03f4871837c14fed704541a20896c0)

Co-authored-by: Sergey Fedoseev <fedoseev.sergey@gmail.com>
diff --git a/Objects/odictobject.c b/Objects/odictobject.c
index 5aa51be..7c6e0b7 100644
--- a/Objects/odictobject.c
+++ b/Objects/odictobject.c
@@ -1837,38 +1837,19 @@
 static PyObject *
 odictiter_reduce(odictiterobject *di)
 {
-    PyObject *list, *iter;
-
-    list = PyList_New(0);
-    if (!list)
-        return NULL;
+    /* copy the iterator state */
+    odictiterobject tmp = *di;
+    Py_XINCREF(tmp.di_odict);
+    Py_XINCREF(tmp.di_current);
 
     /* iterate the temporary into a list */
-    for(;;) {
-        PyObject *element = odictiter_iternext(di);
-        if (element) {
-            if (PyList_Append(list, element)) {
-                Py_DECREF(element);
-                Py_DECREF(list);
-                return NULL;
-            }
-            Py_DECREF(element);
-        }
-        else {
-            /* done iterating? */
-            break;
-        }
-    }
-    if (PyErr_Occurred()) {
-        Py_DECREF(list);
+    PyObject *list = PySequence_List((PyObject*)&tmp);
+    Py_XDECREF(tmp.di_odict);
+    Py_XDECREF(tmp.di_current);
+    if (list == NULL) {
         return NULL;
     }
-    iter = _PyObject_GetBuiltin("iter");
-    if (iter == NULL) {
-        Py_DECREF(list);
-        return NULL;
-    }
-    return Py_BuildValue("N(N)", iter, list);
+    return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
 }
 
 static PyMethodDef odictiter_methods[] = {