From 2f61cc7454b83d87ef2e5f92e63cf03eb70506cf Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 15 Mar 2016 18:30:11 -0700 Subject: [PATCH] make it possible to serialize tuples --- protos/types.proto | 5 +++++ src/orchpylib.cc | 16 ++++++++++++++++ test/runtest.py | 1 + 3 files changed, 22 insertions(+) diff --git a/protos/types.proto b/protos/types.proto index a72674458..3c6e071c4 100644 --- a/protos/types.proto +++ b/protos/types.proto @@ -21,6 +21,7 @@ message Obj { String string_data = 1; Int int_data = 2; Double double_data = 3; + Tuple tuple_data = 7; List list_data = 4; Array array_data = 5; PyObj pyobj_data = 6; @@ -30,6 +31,10 @@ message List { repeated Obj elem = 1; } +message Tuple { + repeated Obj elem = 1; +} + message Value { uint64 ref = 1; // for pass by reference Obj obj = 2; // for pass by value diff --git a/src/orchpylib.cc b/src/orchpylib.cc index e2f59879b..bf11bfd2b 100644 --- a/src/orchpylib.cc +++ b/src/orchpylib.cc @@ -163,6 +163,14 @@ int serialize(PyObject* val, Obj* obj) { Double* data = obj->mutable_double_data(); double d = PyFloat_AsDouble(val); data->set_data(d); + } else if (PyTuple_Check(val)) { + Tuple* data = obj->mutable_tuple_data(); + for (size_t i = 0, size = PyTuple_Size(val); i < size; ++i) { + Obj* elem = data->add_elem(); + if (serialize(PyTuple_GetItem(val, i), elem) != 0) { + return -1; + } + } } else if (PyList_Check(val)) { List* data = obj->mutable_list_data(); for (size_t i = 0, size = PyList_Size(val); i < size; ++i) { @@ -247,6 +255,14 @@ PyObject* deserialize(const Obj& obj) { return PyInt_FromLong(obj.int_data().data()); } else if (obj.has_double_data()) { return PyFloat_FromDouble(obj.double_data().data()); + } else if (obj.has_tuple_data()) { + const Tuple& data = obj.tuple_data(); + size_t size = data.elem_size(); + PyObject* tuple = PyTuple_New(size); + for (size_t i = 0; i < size; ++i) { + PyTuple_SetItem(tuple, i, deserialize(data.elem(i))); + } + return tuple; } else if (obj.has_list_data()) { const List& data = obj.list_data(); size_t size = data.elem_size(); diff --git a/test/runtest.py b/test/runtest.py index 5bf951ce1..195a56aa9 100644 --- a/test/runtest.py +++ b/test/runtest.py @@ -65,6 +65,7 @@ class SerializationTest(unittest.TestCase): self.roundTripTest(42) self.roundTripTest("hello world") self.roundTripTest(42.0) + self.roundTripTest((1.0, "hi")) a = np.zeros((100, 100)) res = orchpy.lib.serialize_object(a)