From 47b93a3db1fabfde6754e9e91b2922e03a64e68a Mon Sep 17 00:00:00 2001 From: zhangyuncong Date: Tue, 21 Nov 2017 16:04:57 +0800 Subject: [PATCH] support deepcopy & copy --- src/fastpb/template/module.jinjacc | 23 +++++++++++++++++++++++ src/fastpb/template/test.jinjapy | 7 +++++++ 2 files changed, 30 insertions(+) diff --git a/src/fastpb/template/module.jinjacc b/src/fastpb/template/module.jinjacc index eb51fbe..25c2593 100644 --- a/src/fastpb/template/module.jinjacc +++ b/src/fastpb/template/module.jinjacc @@ -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) @@ -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 }; diff --git a/src/fastpb/template/test.jinjapy b/src/fastpb/template/test.jinjapy index f6d4439..dbd0daf 100644 --- a/src/fastpb/template/test.jinjapy +++ b/src/fastpb/template/test.jinjapy @@ -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 %}