Permalink
Browse files

Add SerializeMany() class method to protobufs. It is the mirror-image…

… of the existing ParseMany() method.
  • Loading branch information...
1 parent 04c238e commit 4e7e07eee66c928e445348704cce7a972e3d1f05 @PeterScott PeterScott committed Jan 6, 2012
Showing with 30 additions and 0 deletions.
  1. +30 −0 src/fastpb/template/module.jinjacc
@@ -1,3 +1,4 @@
+// -*- C++ -*-
#include <Python.h>
#include <string>
#include "structmember.h"
@@ -160,6 +161,32 @@ namespace {
PyObject *
+ {{ message.name }}_SerializeMany(void *nothing, PyObject *values)
+ {
+ std::string result;
+ google::protobuf::io::ZeroCopyOutputStream* output =
+ new google::protobuf::io::StringOutputStream(&result);
+ google::protobuf::io::CodedOutputStream* outputStream =
+ new google::protobuf::io::CodedOutputStream(output);
+
+ PyObject *sequence = PySequence_Fast(values, "The values to serialize must be a sequence.");
+ for (Py_ssize_t i = 0, len = PySequence_Length(sequence); i < len; ++i) {
+ {{ message.name }} *value = ({{ message.name }} *)PySequence_Fast_GET_ITEM(sequence, i);
+
+ Py_BEGIN_ALLOW_THREADS
+ outputStream->WriteVarint32(value->protobuf->ByteSize());
+ value->protobuf->SerializeToCodedStream(outputStream);
+ Py_END_ALLOW_THREADS
+ }
+
+ Py_XDECREF(sequence);
+ delete outputStream;
+ delete output;
+ return PyString_FromStringAndSize(result.data(), result.length());
+ }
+
+
+ PyObject *
{{ message.name }}_ParseFromString({{ message.name }}* self, PyObject *value)
{
std::string serialized(PyString_AsString(value), PyString_Size(value));
@@ -518,6 +545,9 @@ namespace {
{"SerializeToString", (PyCFunction){{ message.name }}_SerializeToString, METH_NOARGS,
"Serializes the protocol buffer to a string."
},
+ {"SerializeMany", (PyCFunction){{ message.name }}_SerializeMany, METH_O | METH_CLASS,
+ "Serializes a sequence of protocol buffers to a string."
+ },
{"ParseFromString", (PyCFunction){{ message.name }}_ParseFromString, METH_O,
"Parses the protocol buffer from a string."
},

0 comments on commit 4e7e07e

Please sign in to comment.