Skip to content

Commit

Permalink
Add copy method (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
tfpf authored Dec 10, 2024
1 parent 32e7347 commit 67ac6b6
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/pysorteddict/pysorteddict.cc
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ struct SortedDictType
int setitem(PyObject*, PyObject*);
PyObject* str(void);
PyObject* clear(void);
PyObject* copy(void);
PyObject* items(void);
PyObject* keys(void);
PyObject* values(void);
Expand Down Expand Up @@ -239,6 +240,25 @@ PyObject* SortedDictType::clear(void)
Py_RETURN_NONE;
}

PyObject* SortedDictType::copy(void)
{
PyTypeObject* type = Py_TYPE(this);
PyObject* sd_copy = type->tp_alloc(type, 0); // New reference.
if (sd_copy == nullptr)
{
return nullptr;
}
SortedDictType* this_copy = reinterpret_cast<SortedDictType*>(sd_copy);
this_copy->map = new std::map<PyObject*, PyObject*, PyObject_CustomCompare>(*this->map);
for (auto& item : *this_copy->map)
{
Py_INCREF(item.first);
Py_INCREF(item.second);
}
this_copy->key_type = Py_NewRef(this->key_type);
return sd_copy;
}

PyObject* SortedDictType::items(void)
{
PyObject* pyitems = PyList_New(this->map->size()); // New reference.
Expand Down Expand Up @@ -405,6 +425,18 @@ static PyObject* sorted_dict_type_clear(PyObject* self, PyObject* args)
return sd->clear();
}

PyDoc_STRVAR(
sorted_dict_type_copy_doc,
"d.copy() -> SortedDict\n"
"Return a shallow copy of the sorted dictionary ``d``."
);

static PyObject* sorted_dict_type_copy(PyObject* self, PyObject* args)
{
SortedDictType* sd = reinterpret_cast<SortedDictType*>(self);
return sd->copy();
}

PyDoc_STRVAR(
sorted_dict_type_items_doc,
"d.items() -> list[tuple[object, object]]\n"
Expand Down Expand Up @@ -451,6 +483,12 @@ static PyMethodDef sorted_dict_type_methods[] = {
METH_NOARGS, // ml_flags
sorted_dict_type_clear_doc, // ml_doc
},
{
"copy", // ml_name
sorted_dict_type_copy, // ml_meth
METH_NOARGS, // ml_flags
sorted_dict_type_copy_doc, // ml_doc
},
{
"items", // ml_name
sorted_dict_type_items, // ml_meth
Expand Down

0 comments on commit 67ac6b6

Please sign in to comment.