Skip to content

Commit

Permalink
support deepcopy & copy
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangyuncong committed Nov 21, 2017
1 parent 1cfa795 commit 47b93a3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/fastpb/template/module.jinjacc
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,23 @@ namespace {
return PyString_FromStringAndSize(result.data(), result.length());
}

PyObject *
{{ message.name }}_Copy({{ message.name }}* self)
{
{{ message.name }}* cloned = NULL;
Py_BEGIN_ALLOW_THREADS
cloned = ({{ message.name }}*){{ message.name }}_new(&{{ message.name }}Type, NULL, NULL);
cloned->protobuf->CopyFrom(*self->protobuf);
Py_END_ALLOW_THREADS
return (PyObject*)cloned;
}

PyObject *
{{ message.name }}_DeepCopy({{ message.name }}* self, PyObject* /*memo*/)
{
return {{ message.name }}_Copy(self);
}


PyObject *
{{ message.name }}_ParseFromString({{ message.name }}* self, PyObject *value)
Expand Down Expand Up @@ -658,6 +675,12 @@ namespace {
{"ParseMany", (PyCFunction){{ message.name }}_ParseMany, METH_VARARGS | METH_CLASS,
"Parses many protocol buffers of this type from a string."
},
{"__copy__", (PyCFunction){{ message.name }}_DeepCopy, METH_NOARGS,
"copy a pb message."
},
{"__deepcopy__", (PyCFunction){{ message.name }}_DeepCopy, METH_O,
"deep copy a pb message."
},
{NULL} // Sentinel
};

Expand Down
7 changes: 7 additions & 0 deletions src/fastpb/template/test.jinjapy
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ class Test_{{ file.package.replace('.', '_') }}(unittest.TestCase):
{% for field in message.field %}
self.assertEquals(pb.{{ field.name }}, pb2.{{ field.name }})
{% endfor %}

pb3 = copy.deepcopy(pb)

{% for field in message.field %}
self.assertEquals(pb.{{ field.name }}, pb3.{{ field.name }})
{% endfor %}

{% endfor %}
{% endfor %}

Expand Down

0 comments on commit 47b93a3

Please sign in to comment.