@@ -8662,33 +8662,48 @@ frozendict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
86628662 return d ;
86638663}
86648664
8665- static void
8665+ static int
86668666transfer_keys_and_values_lock_held (PyObject * res , PyObject * dict )
86678667{
86688668 PyDictObject * new = (PyDictObject * )res ;
86698669 PyDictObject * old = (PyDictObject * )dict ;
86708670 assert (can_modify_dict (old ));
86718671
8672- // Fast path: do nothing on an empty dict:
86738672 if (old -> ma_keys == Py_EMPTY_KEYS ) {
8674- return ;
8673+ return 0 ;
86758674 }
86768675
86778676 Py_ssize_t used = old -> ma_used ;
86788677 PyDictKeysObject * keys = old -> ma_keys ;
86798678 PyDictValues * values = old -> ma_values ;
86808679
8681- // Clear the old dict keys and values, but do not decref them:
8682- clear_common (old );
8683- set_keys (old , Py_EMPTY_KEYS );
8684- set_values (old , NULL );
8685- ASSERT_CONSISTENT (old );
8680+ if (values && values -> embedded ) {
8681+ // values are inline in the object, copy them and clear the object's copy
8682+ PyDictValues * v = values ;
8683+ values = copy_values (v );
8684+ if (!values ) {
8685+ PyErr_NoMemory ();
8686+ return -1 ;
8687+ }
8688+ dictkeys_incref (keys );
8689+ clear_common (old );
8690+ for (Py_ssize_t i = 0 ; i < keys -> dk_nentries ; i ++ ) {
8691+ FT_ATOMIC_STORE_PTR_RELEASE (v -> values [i ], NULL );
8692+ }
8693+ FT_ATOMIC_STORE_UINT8_RELEASE (v -> size , 0 );
8694+ }
8695+ else {
8696+ clear_common (old );
8697+ set_keys (old , Py_EMPTY_KEYS );
8698+ set_values (old , NULL );
8699+ ASSERT_CONSISTENT (old );
8700+ }
86868701
8687- // Transfer keys and values from dict to frozendict:
86888702 new -> ma_used = used ;
86898703 new -> ma_keys = keys ;
86908704 new -> ma_values = values ;
86918705 ASSERT_CONSISTENT (new );
8706+ return 0 ;
86928707}
86938708
86948709PyObject *
@@ -8704,9 +8719,14 @@ PyDict_AsFrozenDictAndClear(PyObject *dict)
87048719 return NULL ;
87058720 }
87068721
8722+ int err ;
87078723 Py_BEGIN_CRITICAL_SECTION (dict );
8708- transfer_keys_and_values_lock_held (res , dict );
8724+ err = transfer_keys_and_values_lock_held (res , dict );
87098725 Py_END_CRITICAL_SECTION ();
8726+ if (err < 0 ) {
8727+ Py_DECREF (res );
8728+ return NULL ;
8729+ }
87108730
87118731 _PyObject_GC_TRACK (res );
87128732 assert (_PyFrozenDictObject_CAST (res )-> ma_hash == -1 );
0 commit comments