1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // http://code.google.com/p/protobuf/
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // Author: petar@google.com (Petar Petrov)
38 #include <google/protobuf/stubs/common.h>
39 #include <google/protobuf/pyext/python_descriptor.h>
40 #include <google/protobuf/io/coded_stream.h>
41 #include <google/protobuf/descriptor.h>
42 #include <google/protobuf/dynamic_message.h>
43 #include <google/protobuf/message.h>
44 #include <google/protobuf/unknown_field_set.h>
45 #include <google/protobuf/pyext/python_protobuf.h>
48 #define IS_64BIT (SIZEOF_LONG == 8)
50 #define FIELD_BELONGS_TO_MESSAGE(field_descriptor, message) \
51 ((message)->GetDescriptor() == (field_descriptor)->containing_type())
53 #define FIELD_IS_REPEATED(field_descriptor) \
54 ((field_descriptor)->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED)
56 #define GOOGLE_CHECK_GET_INT32(arg, value) \
58 if (!CheckAndGetInteger(arg, &value, kint32min_py, kint32max_py)) { \
62 #define GOOGLE_CHECK_GET_INT64(arg, value) \
64 if (!CheckAndGetInteger(arg, &value, kint64min_py, kint64max_py)) { \
68 #define GOOGLE_CHECK_GET_UINT32(arg, value) \
70 if (!CheckAndGetInteger(arg, &value, kPythonZero, kuint32max_py)) { \
74 #define GOOGLE_CHECK_GET_UINT64(arg, value) \
76 if (!CheckAndGetInteger(arg, &value, kPythonZero, kuint64max_py)) { \
80 #define GOOGLE_CHECK_GET_FLOAT(arg, value) \
82 if (!CheckAndGetFloat(arg, &value)) { \
86 #define GOOGLE_CHECK_GET_DOUBLE(arg, value) \
88 if (!CheckAndGetDouble(arg, &value)) { \
92 #define GOOGLE_CHECK_GET_BOOL(arg, value) \
94 if (!CheckAndGetBool(arg, &value)) { \
98 #define C(str) const_cast<char*>(str)
102 // Constants used for integer type range checking.
103 static PyObject* kPythonZero;
104 static PyObject* kint32min_py;
105 static PyObject* kint32max_py;
106 static PyObject* kuint32max_py;
107 static PyObject* kint64min_py;
108 static PyObject* kint64max_py;
109 static PyObject* kuint64max_py;
115 // --- Support Routines:
117 static void AddConstants(PyObject* module) {
123 {"LABEL_OPTIONAL", google::protobuf::FieldDescriptor::LABEL_OPTIONAL},
124 {"LABEL_REQUIRED", google::protobuf::FieldDescriptor::LABEL_REQUIRED},
125 {"LABEL_REPEATED", google::protobuf::FieldDescriptor::LABEL_REPEATED},
127 {"CPPTYPE_MESSAGE", google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE},
129 {"TYPE_MESSAGE", google::protobuf::FieldDescriptor::TYPE_MESSAGE},
134 for (NameValue* constant = constants;
135 constant->name != NULL; constant++) {
136 PyModule_AddIntConstant(module, constant->name, constant->value);
140 // --- CMessage Custom Type:
142 // ------ Type Forward Declaration:
145 struct CMessage_Type;
147 static void CMessageDealloc(CMessage* self);
148 static int CMessageInit(CMessage* self, PyObject *args, PyObject *kwds);
149 static PyObject* CMessageStr(CMessage* self);
151 static PyObject* CMessage_AddMessage(CMessage* self, PyObject* args);
152 static PyObject* CMessage_AddRepeatedScalar(CMessage* self, PyObject* args);
153 static PyObject* CMessage_AssignRepeatedScalar(CMessage* self, PyObject* args);
154 static PyObject* CMessage_ByteSize(CMessage* self, PyObject* args);
155 static PyObject* CMessage_Clear(CMessage* self, PyObject* args);
156 static PyObject* CMessage_ClearField(CMessage* self, PyObject* args);
157 static PyObject* CMessage_ClearFieldByDescriptor(
158 CMessage* self, PyObject* args);
159 static PyObject* CMessage_CopyFrom(CMessage* self, PyObject* args);
160 static PyObject* CMessage_DebugString(CMessage* self, PyObject* args);
161 static PyObject* CMessage_DeleteRepeatedField(CMessage* self, PyObject* args);
162 static PyObject* CMessage_Equals(CMessage* self, PyObject* args);
163 static PyObject* CMessage_FieldLength(CMessage* self, PyObject* args);
164 static PyObject* CMessage_FindInitializationErrors(CMessage* self);
165 static PyObject* CMessage_GetRepeatedMessage(CMessage* self, PyObject* args);
166 static PyObject* CMessage_GetRepeatedScalar(CMessage* self, PyObject* args);
167 static PyObject* CMessage_GetScalar(CMessage* self, PyObject* args);
168 static PyObject* CMessage_HasField(CMessage* self, PyObject* args);
169 static PyObject* CMessage_HasFieldByDescriptor(CMessage* self, PyObject* args);
170 static PyObject* CMessage_IsInitialized(CMessage* self, PyObject* args);
171 static PyObject* CMessage_ListFields(CMessage* self, PyObject* args);
172 static PyObject* CMessage_MergeFrom(CMessage* self, PyObject* args);
173 static PyObject* CMessage_MergeFromString(CMessage* self, PyObject* args);
174 static PyObject* CMessage_MutableMessage(CMessage* self, PyObject* args);
175 static PyObject* CMessage_NewSubMessage(CMessage* self, PyObject* args);
176 static PyObject* CMessage_SetScalar(CMessage* self, PyObject* args);
177 static PyObject* CMessage_SerializePartialToString(
178 CMessage* self, PyObject* args);
179 static PyObject* CMessage_SerializeToString(CMessage* self, PyObject* args);
180 static PyObject* CMessage_SetInParent(CMessage* self, PyObject* args);
181 static PyObject* CMessage_SwapRepeatedFieldElements(
182 CMessage* self, PyObject* args);
184 // ------ Object Definition:
186 typedef struct CMessage {
189 struct CMessage* parent; // NULL if wasn't created from another message.
190 CFieldDescriptor* parent_field;
191 const char* full_name;
192 google::protobuf::Message* message;
197 // ------ Method Table:
199 #define CMETHOD(name, args, doc) \
200 { C(#name), (PyCFunction)CMessage_##name, args, C(doc) }
201 static PyMethodDef CMessageMethods[] = {
202 CMETHOD(AddMessage, METH_O,
203 "Adds a new message to a repeated composite field."),
204 CMETHOD(AddRepeatedScalar, METH_VARARGS,
205 "Adds a scalar to a repeated scalar field."),
206 CMETHOD(AssignRepeatedScalar, METH_VARARGS,
207 "Clears and sets the values of a repeated scalar field."),
208 CMETHOD(ByteSize, METH_NOARGS,
209 "Returns the size of the message in bytes."),
210 CMETHOD(Clear, METH_O,
211 "Clears a protocol message."),
212 CMETHOD(ClearField, METH_VARARGS,
213 "Clears a protocol message field by name."),
214 CMETHOD(ClearFieldByDescriptor, METH_O,
215 "Clears a protocol message field by descriptor."),
216 CMETHOD(CopyFrom, METH_O,
217 "Copies a protocol message into the current message."),
218 CMETHOD(DebugString, METH_NOARGS,
219 "Returns the debug string of a protocol message."),
220 CMETHOD(DeleteRepeatedField, METH_VARARGS,
221 "Deletes a slice of values from a repeated field."),
222 CMETHOD(Equals, METH_O,
223 "Checks if two protocol messages are equal (by identity)."),
224 CMETHOD(FieldLength, METH_O,
225 "Returns the number of elements in a repeated field."),
226 CMETHOD(FindInitializationErrors, METH_NOARGS,
227 "Returns the initialization errors of a message."),
228 CMETHOD(GetRepeatedMessage, METH_VARARGS,
229 "Returns a message from a repeated composite field."),
230 CMETHOD(GetRepeatedScalar, METH_VARARGS,
231 "Returns a scalar value from a repeated scalar field."),
232 CMETHOD(GetScalar, METH_O,
233 "Returns the scalar value of a field."),
234 CMETHOD(HasField, METH_O,
235 "Checks if a message field is set."),
236 CMETHOD(HasFieldByDescriptor, METH_O,
237 "Checks if a message field is set by given its descriptor"),
238 CMETHOD(IsInitialized, METH_NOARGS,
239 "Checks if all required fields of a protocol message are set."),
240 CMETHOD(ListFields, METH_NOARGS,
241 "Lists all set fields of a message."),
242 CMETHOD(MergeFrom, METH_O,
243 "Merges a protocol message into the current message."),
244 CMETHOD(MergeFromString, METH_O,
245 "Merges a serialized message into the current message."),
246 CMETHOD(MutableMessage, METH_O,
247 "Returns a new instance of a nested protocol message."),
248 CMETHOD(NewSubMessage, METH_O,
249 "Creates and returns a python message given the descriptor of a "
250 "composite field of the current message."),
251 CMETHOD(SetScalar, METH_VARARGS,
252 "Sets the value of a singular scalar field."),
253 CMETHOD(SerializePartialToString, METH_VARARGS,
254 "Serializes the message to a string, even if it isn't initialized."),
255 CMETHOD(SerializeToString, METH_NOARGS,
256 "Serializes the message to a string, only for initialized messages."),
257 CMETHOD(SetInParent, METH_NOARGS,
258 "Sets the has bit of the given field in its parent message."),
259 CMETHOD(SwapRepeatedFieldElements, METH_VARARGS,
260 "Swaps the elements in two positions in a repeated field."),
265 static PyMemberDef CMessageMembers[] = {
266 { C("full_name"), T_STRING, offsetof(CMessage, full_name), 0, "Full name" },
270 // ------ Type Definition:
272 // The definition for the type object that captures the type of CMessage
274 PyTypeObject CMessage_Type = {
275 PyObject_HEAD_INIT(&PyType_Type)
277 C("google.protobuf.internal."
278 "_net_proto2___python."
279 "CMessage"), // tp_name
280 sizeof(CMessage), // tp_basicsize
282 (destructor)CMessageDealloc, // tp_dealloc
293 (reprfunc)CMessageStr, // tp_str
297 Py_TPFLAGS_DEFAULT, // tp_flags
298 C("A ProtocolMessage"), // tp_doc
302 0, // tp_weaklistoffset
305 CMessageMethods, // tp_methods
306 CMessageMembers, // tp_members
313 (initproc)CMessageInit, // tp_init
314 PyType_GenericAlloc, // tp_alloc
315 PyType_GenericNew, // tp_new
316 PyObject_Del, // tp_free
319 // ------ Helper Functions:
321 static void FormatTypeError(PyObject* arg, char* expected_types) {
322 PyObject* repr = PyObject_Repr(arg);
323 PyErr_Format(PyExc_TypeError,
324 "%.100s has type %.100s, but expected one of: %s",
325 PyString_AS_STRING(repr),
326 arg->ob_type->tp_name,
332 static bool CheckAndGetInteger(
333 PyObject* arg, T* value, PyObject* min, PyObject* max) {
334 bool is_long = PyLong_Check(arg);
335 if (!PyInt_Check(arg) && !is_long) {
336 FormatTypeError(arg, "int, long");
340 if (PyObject_Compare(min, arg) > 0 || PyObject_Compare(max, arg) < 0) {
341 PyObject* s = PyObject_Str(arg);
342 PyErr_Format(PyExc_ValueError,
343 "Value out of range: %s",
344 PyString_AS_STRING(s));
349 if (min == kPythonZero) {
350 *value = static_cast<T>(PyLong_AsUnsignedLongLong(arg));
352 *value = static_cast<T>(PyLong_AsLongLong(arg));
355 *value = static_cast<T>(PyInt_AsLong(arg));
360 static bool CheckAndGetDouble(PyObject* arg, double* value) {
361 if (!PyInt_Check(arg) && !PyLong_Check(arg) &&
362 !PyFloat_Check(arg)) {
363 FormatTypeError(arg, "int, long, float");
366 *value = PyFloat_AsDouble(arg);
370 static bool CheckAndGetFloat(PyObject* arg, float* value) {
372 if (!CheckAndGetDouble(arg, &double_value)) {
375 *value = static_cast<float>(double_value);
379 static bool CheckAndGetBool(PyObject* arg, bool* value) {
380 if (!PyInt_Check(arg) && !PyBool_Check(arg) && !PyLong_Check(arg)) {
381 FormatTypeError(arg, "int, long, bool");
384 *value = static_cast<bool>(PyInt_AsLong(arg));
388 google::protobuf::DynamicMessageFactory* global_message_factory = NULL;
389 static const google::protobuf::Message* CreateMessage(const char* message_type) {
390 string message_name(message_type);
391 const google::protobuf::Descriptor* descriptor =
392 GetDescriptorPool()->FindMessageTypeByName(message_name);
393 if (descriptor == NULL) {
396 return global_message_factory->GetPrototype(descriptor);
399 static void ReleaseSubMessage(google::protobuf::Message* message,
400 const google::protobuf::FieldDescriptor* field_descriptor,
401 CMessage* child_cmessage) {
402 Message* released_message = message->GetReflection()->ReleaseMessage(
403 message, field_descriptor, global_message_factory);
404 GOOGLE_DCHECK(child_cmessage->message != NULL);
405 // ReleaseMessage will return NULL which differs from
406 // child_cmessage->message, if the field does not exist. In this case,
407 // the latter points to the default instance via a const_cast<>, so we
408 // have to reset it to a new mutable object since we are taking ownership.
409 if (released_message == NULL) {
410 const Message* prototype = global_message_factory->GetPrototype(
411 child_cmessage->message->GetDescriptor());
412 GOOGLE_DCHECK(prototype != NULL);
413 child_cmessage->message = prototype->New();
415 child_cmessage->parent = NULL;
416 child_cmessage->parent_field = NULL;
417 child_cmessage->free_message = true;
418 child_cmessage->read_only = false;
421 static bool CheckAndSetString(
422 PyObject* arg, google::protobuf::Message* message,
423 const google::protobuf::FieldDescriptor* descriptor,
424 const google::protobuf::Reflection* reflection,
427 GOOGLE_DCHECK(descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING ||
428 descriptor->type() == google::protobuf::FieldDescriptor::TYPE_BYTES);
429 if (descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING) {
430 if (!PyString_Check(arg) && !PyUnicode_Check(arg)) {
431 FormatTypeError(arg, "str, unicode");
435 if (PyString_Check(arg)) {
436 PyObject* unicode = PyUnicode_FromEncodedObject(arg, "ascii", NULL);
437 if (unicode == NULL) {
438 PyObject* repr = PyObject_Repr(arg);
439 PyErr_Format(PyExc_ValueError,
440 "%s has type str, but isn't in 7-bit ASCII "
441 "encoding. Non-ASCII strings must be converted to "
442 "unicode objects before being added.",
443 PyString_AS_STRING(repr));
450 } else if (!PyString_Check(arg)) {
451 FormatTypeError(arg, "str");
455 PyObject* encoded_string = NULL;
456 if (descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING) {
457 if (PyString_Check(arg)) {
458 encoded_string = PyString_AsEncodedObject(arg, "utf-8", NULL);
460 encoded_string = PyUnicode_AsEncodedObject(arg, "utf-8", NULL);
463 // In this case field type is "bytes".
464 encoded_string = arg;
465 Py_INCREF(encoded_string);
468 if (encoded_string == NULL) {
473 Py_ssize_t value_len;
474 if (PyString_AsStringAndSize(encoded_string, &value, &value_len) < 0) {
475 Py_DECREF(encoded_string);
479 string value_string(value, value_len);
481 reflection->AddString(message, descriptor, value_string);
482 } else if (index < 0) {
483 reflection->SetString(message, descriptor, value_string);
485 reflection->SetRepeatedString(message, descriptor, index, value_string);
487 Py_DECREF(encoded_string);
491 static PyObject* ToStringObject(
492 const google::protobuf::FieldDescriptor* descriptor, string value) {
493 if (descriptor->type() != google::protobuf::FieldDescriptor::TYPE_STRING) {
494 return PyString_FromStringAndSize(value.c_str(), value.length());
497 PyObject* result = PyUnicode_DecodeUTF8(value.c_str(), value.length(), NULL);
498 // If the string can't be decoded in UTF-8, just return a string object that
499 // contains the raw bytes. This can't happen if the value was assigned using
500 // the members of the Python message object, but can happen if the values were
501 // parsed from the wire (binary).
502 if (result == NULL) {
504 result = PyString_FromStringAndSize(value.c_str(), value.length());
509 static void AssureWritable(CMessage* self) {
511 self->parent == NULL ||
512 self->parent_field == NULL) {
516 if (!self->read_only) {
520 AssureWritable(self->parent);
522 google::protobuf::Message* message = self->parent->message;
523 const google::protobuf::Reflection* reflection = message->GetReflection();
524 self->message = reflection->MutableMessage(
525 message, self->parent_field->descriptor, global_message_factory);
526 self->read_only = false;
529 static PyObject* InternalGetScalar(
530 google::protobuf::Message* message,
531 const google::protobuf::FieldDescriptor* field_descriptor) {
532 const google::protobuf::Reflection* reflection = message->GetReflection();
534 if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
536 PyExc_KeyError, "Field does not belong to message!");
540 PyObject* result = NULL;
541 switch (field_descriptor->cpp_type()) {
542 case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
543 int32 value = reflection->GetInt32(*message, field_descriptor);
544 result = PyInt_FromLong(value);
547 case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
548 int64 value = reflection->GetInt64(*message, field_descriptor);
550 result = PyInt_FromLong(value);
552 result = PyLong_FromLongLong(value);
556 case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
557 uint32 value = reflection->GetUInt32(*message, field_descriptor);
559 result = PyInt_FromLong(value);
561 result = PyLong_FromLongLong(value);
565 case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
566 uint64 value = reflection->GetUInt64(*message, field_descriptor);
568 if (value <= static_cast<uint64>(kint64max)) {
569 result = PyInt_FromLong(static_cast<uint64>(value));
572 if (value <= static_cast<uint32>(kint32max)) {
573 result = PyInt_FromLong(static_cast<uint32>(value));
577 result = PyLong_FromUnsignedLongLong(value);
581 case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
582 float value = reflection->GetFloat(*message, field_descriptor);
583 result = PyFloat_FromDouble(value);
586 case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
587 double value = reflection->GetDouble(*message, field_descriptor);
588 result = PyFloat_FromDouble(value);
591 case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
592 bool value = reflection->GetBool(*message, field_descriptor);
593 result = PyBool_FromLong(value);
596 case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
597 string value = reflection->GetString(*message, field_descriptor);
598 result = ToStringObject(field_descriptor, value);
601 case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
602 if (!message->GetReflection()->HasField(*message, field_descriptor)) {
603 // Look for the value in the unknown fields.
604 google::protobuf::UnknownFieldSet* unknown_field_set =
605 message->GetReflection()->MutableUnknownFields(message);
606 for (int i = 0; i < unknown_field_set->field_count(); ++i) {
607 if (unknown_field_set->field(i).number() ==
608 field_descriptor->number()) {
609 result = PyInt_FromLong(unknown_field_set->field(i).varint());
615 if (result == NULL) {
616 const google::protobuf::EnumValueDescriptor* enum_value =
617 message->GetReflection()->GetEnum(*message, field_descriptor);
618 result = PyInt_FromLong(enum_value->number());
624 PyExc_SystemError, "Getting a value from a field of unknown type %d",
625 field_descriptor->cpp_type());
631 static PyObject* InternalSetScalar(
632 google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field_descriptor,
634 const google::protobuf::Reflection* reflection = message->GetReflection();
636 if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
638 PyExc_KeyError, "Field does not belong to message!");
642 switch (field_descriptor->cpp_type()) {
643 case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
644 GOOGLE_CHECK_GET_INT32(arg, value);
645 reflection->SetInt32(message, field_descriptor, value);
648 case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
649 GOOGLE_CHECK_GET_INT64(arg, value);
650 reflection->SetInt64(message, field_descriptor, value);
653 case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
654 GOOGLE_CHECK_GET_UINT32(arg, value);
655 reflection->SetUInt32(message, field_descriptor, value);
658 case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
659 GOOGLE_CHECK_GET_UINT64(arg, value);
660 reflection->SetUInt64(message, field_descriptor, value);
663 case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
664 GOOGLE_CHECK_GET_FLOAT(arg, value);
665 reflection->SetFloat(message, field_descriptor, value);
668 case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
669 GOOGLE_CHECK_GET_DOUBLE(arg, value);
670 reflection->SetDouble(message, field_descriptor, value);
673 case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
674 GOOGLE_CHECK_GET_BOOL(arg, value);
675 reflection->SetBool(message, field_descriptor, value);
678 case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
679 if (!CheckAndSetString(
680 arg, message, field_descriptor, reflection, false, -1)) {
685 case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
686 GOOGLE_CHECK_GET_INT32(arg, value);
687 const google::protobuf::EnumDescriptor* enum_descriptor =
688 field_descriptor->enum_type();
689 const google::protobuf::EnumValueDescriptor* enum_value =
690 enum_descriptor->FindValueByNumber(value);
691 if (enum_value != NULL) {
692 reflection->SetEnum(message, field_descriptor, enum_value);
695 // Add the value to the unknown fields.
696 google::protobuf::UnknownFieldSet* unknown_field_set =
697 message->GetReflection()->MutableUnknownFields(message);
698 for (int i = 0; i < unknown_field_set->field_count(); ++i) {
699 if (unknown_field_set->field(i).number() ==
700 field_descriptor->number()) {
701 unknown_field_set->mutable_field(i)->set_varint(value);
708 unknown_field_set->AddVarint(field_descriptor->number(), value);
710 reflection->ClearField(message, field_descriptor);
716 PyExc_SystemError, "Setting value to a field of unknown type %d",
717 field_descriptor->cpp_type());
723 static PyObject* InternalAddRepeatedScalar(
724 google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field_descriptor,
727 if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
729 PyExc_KeyError, "Field does not belong to message!");
733 const google::protobuf::Reflection* reflection = message->GetReflection();
734 switch (field_descriptor->cpp_type()) {
735 case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
736 GOOGLE_CHECK_GET_INT32(arg, value);
737 reflection->AddInt32(message, field_descriptor, value);
740 case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
741 GOOGLE_CHECK_GET_INT64(arg, value);
742 reflection->AddInt64(message, field_descriptor, value);
745 case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
746 GOOGLE_CHECK_GET_UINT32(arg, value);
747 reflection->AddUInt32(message, field_descriptor, value);
750 case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
751 GOOGLE_CHECK_GET_UINT64(arg, value);
752 reflection->AddUInt64(message, field_descriptor, value);
755 case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
756 GOOGLE_CHECK_GET_FLOAT(arg, value);
757 reflection->AddFloat(message, field_descriptor, value);
760 case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
761 GOOGLE_CHECK_GET_DOUBLE(arg, value);
762 reflection->AddDouble(message, field_descriptor, value);
765 case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
766 GOOGLE_CHECK_GET_BOOL(arg, value);
767 reflection->AddBool(message, field_descriptor, value);
770 case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
771 if (!CheckAndSetString(
772 arg, message, field_descriptor, reflection, true, -1)) {
777 case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
778 GOOGLE_CHECK_GET_INT32(arg, value);
779 const google::protobuf::EnumDescriptor* enum_descriptor =
780 field_descriptor->enum_type();
781 const google::protobuf::EnumValueDescriptor* enum_value =
782 enum_descriptor->FindValueByNumber(value);
783 if (enum_value != NULL) {
784 reflection->AddEnum(message, field_descriptor, enum_value);
786 PyObject* s = PyObject_Str(arg);
787 PyErr_Format(PyExc_ValueError, "Unknown enum value: %s",
788 PyString_AS_STRING(s));
796 PyExc_SystemError, "Adding value to a field of unknown type %d",
797 field_descriptor->cpp_type());
803 static PyObject* InternalGetRepeatedScalar(
804 CMessage* cmessage, const google::protobuf::FieldDescriptor* field_descriptor,
806 google::protobuf::Message* message = cmessage->message;
807 const google::protobuf::Reflection* reflection = message->GetReflection();
809 int field_size = reflection->FieldSize(*message, field_descriptor);
811 index = field_size + index;
813 if (index < 0 || index >= field_size) {
814 PyErr_Format(PyExc_IndexError,
815 "list assignment index (%d) out of range", index);
819 PyObject* result = NULL;
820 switch (field_descriptor->cpp_type()) {
821 case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
822 int32 value = reflection->GetRepeatedInt32(
823 *message, field_descriptor, index);
824 result = PyInt_FromLong(value);
827 case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
828 int64 value = reflection->GetRepeatedInt64(
829 *message, field_descriptor, index);
830 result = PyLong_FromLongLong(value);
833 case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
834 uint32 value = reflection->GetRepeatedUInt32(
835 *message, field_descriptor, index);
836 result = PyLong_FromLongLong(value);
839 case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
840 uint64 value = reflection->GetRepeatedUInt64(
841 *message, field_descriptor, index);
842 result = PyLong_FromUnsignedLongLong(value);
845 case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
846 float value = reflection->GetRepeatedFloat(
847 *message, field_descriptor, index);
848 result = PyFloat_FromDouble(value);
851 case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
852 double value = reflection->GetRepeatedDouble(
853 *message, field_descriptor, index);
854 result = PyFloat_FromDouble(value);
857 case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
858 bool value = reflection->GetRepeatedBool(
859 *message, field_descriptor, index);
860 result = PyBool_FromLong(value ? 1 : 0);
863 case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
864 const google::protobuf::EnumValueDescriptor* enum_value =
865 message->GetReflection()->GetRepeatedEnum(
866 *message, field_descriptor, index);
867 result = PyInt_FromLong(enum_value->number());
870 case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
871 string value = reflection->GetRepeatedString(
872 *message, field_descriptor, index);
873 result = ToStringObject(field_descriptor, value);
876 case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
877 CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type);
878 if (py_cmsg == NULL) {
881 const google::protobuf::Message& msg = reflection->GetRepeatedMessage(
882 *message, field_descriptor, index);
883 py_cmsg->parent = cmessage;
884 py_cmsg->full_name = field_descriptor->full_name().c_str();
885 py_cmsg->message = const_cast<google::protobuf::Message*>(&msg);
886 py_cmsg->free_message = false;
887 py_cmsg->read_only = false;
888 result = reinterpret_cast<PyObject*>(py_cmsg);
894 "Getting value from a repeated field of unknown type %d",
895 field_descriptor->cpp_type());
901 static PyObject* InternalGetRepeatedScalarSlice(
902 CMessage* cmessage, const google::protobuf::FieldDescriptor* field_descriptor,
908 bool return_list = false;
909 google::protobuf::Message* message = cmessage->message;
911 if (PyInt_Check(slice)) {
912 from = to = PyInt_AsLong(slice);
913 } else if (PyLong_Check(slice)) {
914 from = to = PyLong_AsLong(slice);
915 } else if (PySlice_Check(slice)) {
916 const google::protobuf::Reflection* reflection = message->GetReflection();
917 length = reflection->FieldSize(*message, field_descriptor);
919 reinterpret_cast<PySliceObject*>(slice), length, &from, &to, &step);
922 PyErr_SetString(PyExc_TypeError, "list indices must be integers");
927 return InternalGetRepeatedScalar(cmessage, field_descriptor, from);
930 PyObject* list = PyList_New(0);
936 if (step < 0) return list;
937 for (Py_ssize_t index = from; index < to; index += step) {
938 if (index < 0 || index >= length) break;
939 PyObject* s = InternalGetRepeatedScalar(
940 cmessage, field_descriptor, index);
941 PyList_Append(list, s);
945 if (step > 0) return list;
946 for (Py_ssize_t index = from; index > to; index += step) {
947 if (index < 0 || index >= length) break;
948 PyObject* s = InternalGetRepeatedScalar(
949 cmessage, field_descriptor, index);
950 PyList_Append(list, s);
957 // ------ C Constructor/Destructor:
959 static int CMessageInit(CMessage* self, PyObject *args, PyObject *kwds) {
960 self->message = NULL;
964 static void CMessageDealloc(CMessage* self) {
965 if (self->free_message) {
966 if (self->read_only) {
967 PyErr_WriteUnraisable(reinterpret_cast<PyObject*>(self));
969 delete self->message;
971 self->ob_type->tp_free(reinterpret_cast<PyObject*>(self));
976 static PyObject* CMessage_Clear(CMessage* self, PyObject* arg) {
977 AssureWritable(self);
978 google::protobuf::Message* message = self->message;
980 // This block of code is equivalent to the following:
981 // for cfield_descriptor, child_cmessage in arg:
982 // ReleaseSubMessage(cfield_descriptor, child_cmessage)
983 if (!PyList_Check(arg)) {
984 PyErr_SetString(PyExc_TypeError, "Must be a list");
987 PyObject* messages_to_clear = arg;
988 Py_ssize_t num_messages_to_clear = PyList_GET_SIZE(messages_to_clear);
989 for(int i = 0; i < num_messages_to_clear; ++i) {
990 PyObject* message_tuple = PyList_GET_ITEM(messages_to_clear, i);
991 if (!PyTuple_Check(message_tuple) || PyTuple_GET_SIZE(message_tuple) != 2) {
992 PyErr_SetString(PyExc_TypeError, "Must be a tuple of size 2");
996 PyObject* py_cfield_descriptor = PyTuple_GET_ITEM(message_tuple, 0);
997 PyObject* py_child_cmessage = PyTuple_GET_ITEM(message_tuple, 1);
998 if (!PyObject_TypeCheck(py_cfield_descriptor, &CFieldDescriptor_Type) ||
999 !PyObject_TypeCheck(py_child_cmessage, &CMessage_Type)) {
1000 PyErr_SetString(PyExc_ValueError, "Invalid Tuple");
1004 CFieldDescriptor* cfield_descriptor = reinterpret_cast<CFieldDescriptor *>(
1005 py_cfield_descriptor);
1006 CMessage* child_cmessage = reinterpret_cast<CMessage *>(py_child_cmessage);
1007 ReleaseSubMessage(message, cfield_descriptor->descriptor, child_cmessage);
1014 static PyObject* CMessage_IsInitialized(CMessage* self, PyObject* args) {
1015 return PyBool_FromLong(self->message->IsInitialized() ? 1 : 0);
1018 static PyObject* CMessage_HasField(CMessage* self, PyObject* arg) {
1020 if (PyString_AsStringAndSize(arg, &field_name, NULL) < 0) {
1024 google::protobuf::Message* message = self->message;
1025 const google::protobuf::Descriptor* descriptor = message->GetDescriptor();
1026 const google::protobuf::FieldDescriptor* field_descriptor =
1027 descriptor->FindFieldByName(field_name);
1028 if (field_descriptor == NULL) {
1029 PyErr_Format(PyExc_ValueError, "Unknown field %s.", field_name);
1034 message->GetReflection()->HasField(*message, field_descriptor);
1035 return PyBool_FromLong(has_field ? 1 : 0);
1038 static PyObject* CMessage_HasFieldByDescriptor(CMessage* self, PyObject* arg) {
1039 CFieldDescriptor* cfield_descriptor = NULL;
1040 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg),
1041 &CFieldDescriptor_Type)) {
1042 PyErr_SetString(PyExc_TypeError, "Must be a field descriptor");
1045 cfield_descriptor = reinterpret_cast<CFieldDescriptor*>(arg);
1047 google::protobuf::Message* message = self->message;
1048 const google::protobuf::FieldDescriptor* field_descriptor =
1049 cfield_descriptor->descriptor;
1051 if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
1052 PyErr_SetString(PyExc_KeyError,
1053 "Field does not belong to message!");
1057 if (FIELD_IS_REPEATED(field_descriptor)) {
1058 PyErr_SetString(PyExc_KeyError,
1059 "Field is repeated. A singular method is required.");
1064 message->GetReflection()->HasField(*message, field_descriptor);
1065 return PyBool_FromLong(has_field ? 1 : 0);
1068 static PyObject* CMessage_ClearFieldByDescriptor(
1069 CMessage* self, PyObject* arg) {
1070 CFieldDescriptor* cfield_descriptor = NULL;
1071 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg),
1072 &CFieldDescriptor_Type)) {
1073 PyErr_SetString(PyExc_TypeError, "Must be a field descriptor");
1076 cfield_descriptor = reinterpret_cast<CFieldDescriptor*>(arg);
1078 google::protobuf::Message* message = self->message;
1079 const google::protobuf::FieldDescriptor* field_descriptor =
1080 cfield_descriptor->descriptor;
1082 if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
1083 PyErr_SetString(PyExc_KeyError,
1084 "Field does not belong to message!");
1088 message->GetReflection()->ClearField(message, field_descriptor);
1092 static PyObject* CMessage_ClearField(CMessage* self, PyObject* args) {
1094 CMessage* child_cmessage = NULL;
1095 if (!PyArg_ParseTuple(args, C("s|O!:ClearField"), &field_name,
1096 &CMessage_Type, &child_cmessage)) {
1100 google::protobuf::Message* message = self->message;
1101 const google::protobuf::Descriptor* descriptor = message->GetDescriptor();
1102 const google::protobuf::FieldDescriptor* field_descriptor =
1103 descriptor->FindFieldByName(field_name);
1104 if (field_descriptor == NULL) {
1105 PyErr_Format(PyExc_ValueError, "Unknown field %s.", field_name);
1109 if (child_cmessage != NULL && !FIELD_IS_REPEATED(field_descriptor)) {
1110 ReleaseSubMessage(message, field_descriptor, child_cmessage);
1112 message->GetReflection()->ClearField(message, field_descriptor);
1117 static PyObject* CMessage_GetScalar(CMessage* self, PyObject* arg) {
1118 CFieldDescriptor* cdescriptor = NULL;
1119 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg),
1120 &CFieldDescriptor_Type)) {
1121 PyErr_SetString(PyExc_TypeError, "Must be a field descriptor");
1124 cdescriptor = reinterpret_cast<CFieldDescriptor*>(arg);
1126 google::protobuf::Message* message = self->message;
1127 return InternalGetScalar(message, cdescriptor->descriptor);
1130 static PyObject* CMessage_GetRepeatedScalar(CMessage* self, PyObject* args) {
1131 CFieldDescriptor* cfield_descriptor;
1133 if (!PyArg_ParseTuple(args, C("O!O:GetRepeatedScalar"),
1134 &CFieldDescriptor_Type, &cfield_descriptor, &slice)) {
1138 return InternalGetRepeatedScalarSlice(
1139 self, cfield_descriptor->descriptor, slice);
1142 static PyObject* CMessage_AssignRepeatedScalar(CMessage* self, PyObject* args) {
1143 CFieldDescriptor* cfield_descriptor;
1145 if (!PyArg_ParseTuple(args, C("O!O:AssignRepeatedScalar"),
1146 &CFieldDescriptor_Type, &cfield_descriptor, &slice)) {
1150 AssureWritable(self);
1151 google::protobuf::Message* message = self->message;
1152 message->GetReflection()->ClearField(message, cfield_descriptor->descriptor);
1154 PyObject* iter = PyObject_GetIter(slice);
1156 while ((next = PyIter_Next(iter)) != NULL) {
1157 if (InternalAddRepeatedScalar(
1158 message, cfield_descriptor->descriptor, next) == NULL) {
1169 static PyObject* CMessage_DeleteRepeatedField(CMessage* self, PyObject* args) {
1170 CFieldDescriptor* cfield_descriptor;
1172 if (!PyArg_ParseTuple(args, C("O!O:DeleteRepeatedField"),
1173 &CFieldDescriptor_Type, &cfield_descriptor, &slice)) {
1176 AssureWritable(self);
1178 Py_ssize_t length, from, to, step, slice_length;
1179 google::protobuf::Message* message = self->message;
1180 const google::protobuf::FieldDescriptor* field_descriptor =
1181 cfield_descriptor->descriptor;
1182 const google::protobuf::Reflection* reflection = message->GetReflection();
1184 length = reflection->FieldSize(*message, field_descriptor);
1186 if (PyInt_Check(slice) || PyLong_Check(slice)) {
1187 from = to = PyLong_AsLong(slice);
1189 from = to = length + from;
1195 if (from < 0 || from >= length) {
1196 PyErr_Format(PyExc_IndexError, "list assignment index out of range");
1199 } else if (PySlice_Check(slice)) {
1200 from = to = step = slice_length = 0;
1201 PySlice_GetIndicesEx(
1202 reinterpret_cast<PySliceObject*>(slice),
1203 length, &from, &to, &step, &slice_length);
1212 PyErr_SetString(PyExc_TypeError, "list indices must be integers");
1216 Py_ssize_t i = from;
1217 std::vector<bool> to_delete(length, false);
1218 while (i >= min && i <= max) {
1219 to_delete[i] = true;
1224 for (i = 0; i < length; ++i) {
1225 if (!to_delete[i]) {
1227 reflection->SwapElements(message, field_descriptor, i, to);
1234 reflection->RemoveLast(message, field_descriptor);
1242 static PyObject* CMessage_SetScalar(CMessage* self, PyObject* args) {
1243 CFieldDescriptor* cfield_descriptor;
1245 if (!PyArg_ParseTuple(args, C("O!O:SetScalar"),
1246 &CFieldDescriptor_Type, &cfield_descriptor, &arg)) {
1249 AssureWritable(self);
1251 return InternalSetScalar(self->message, cfield_descriptor->descriptor, arg);
1254 static PyObject* CMessage_AddRepeatedScalar(CMessage* self, PyObject* args) {
1255 CFieldDescriptor* cfield_descriptor;
1257 if (!PyArg_ParseTuple(args, C("O!O:AddRepeatedScalar"),
1258 &CFieldDescriptor_Type, &cfield_descriptor, &value)) {
1261 AssureWritable(self);
1263 return InternalAddRepeatedScalar(
1264 self->message, cfield_descriptor->descriptor, value);
1267 static PyObject* CMessage_FieldLength(CMessage* self, PyObject* arg) {
1268 CFieldDescriptor* cfield_descriptor;
1269 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg),
1270 &CFieldDescriptor_Type)) {
1271 PyErr_SetString(PyExc_TypeError, "Must be a field descriptor");
1274 cfield_descriptor = reinterpret_cast<CFieldDescriptor*>(arg);
1276 google::protobuf::Message* message = self->message;
1277 int length = message->GetReflection()->FieldSize(
1278 *message, cfield_descriptor->descriptor);
1279 return PyInt_FromLong(length);
1282 static PyObject* CMessage_DebugString(CMessage* self, PyObject* args) {
1283 return PyString_FromString(self->message->DebugString().c_str());
1286 static PyObject* CMessage_SerializeToString(CMessage* self, PyObject* args) {
1287 int size = self->message->ByteSize();
1289 return PyString_FromString("");
1291 PyObject* result = PyString_FromStringAndSize(NULL, size);
1292 if (result == NULL) {
1295 char* buffer = PyString_AS_STRING(result);
1296 self->message->SerializeWithCachedSizesToArray(
1297 reinterpret_cast<uint8*>(buffer));
1301 static PyObject* CMessage_SerializePartialToString(
1302 CMessage* self, PyObject* args) {
1304 self->message->SerializePartialToString(&contents);
1305 return PyString_FromStringAndSize(contents.c_str(), contents.size());
1308 static PyObject* CMessageStr(CMessage* self) {
1310 str[sizeof(str) - 1] = 0;
1311 snprintf(str, sizeof(str) - 1, "CMessage: <%p>", self->message);
1312 return PyString_FromString(str);
1315 static PyObject* CMessage_MergeFrom(CMessage* self, PyObject* arg) {
1316 CMessage* other_message;
1317 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg), &CMessage_Type)) {
1318 PyErr_SetString(PyExc_TypeError, "Must be a message");
1322 other_message = reinterpret_cast<CMessage*>(arg);
1323 if (other_message->message->GetDescriptor() !=
1324 self->message->GetDescriptor()) {
1325 PyErr_Format(PyExc_TypeError,
1326 "Tried to merge from a message with a different type. "
1328 self->message->GetDescriptor()->full_name().c_str(),
1329 other_message->message->GetDescriptor()->full_name().c_str());
1332 AssureWritable(self);
1334 self->message->MergeFrom(*other_message->message);
1338 static PyObject* CMessage_CopyFrom(CMessage* self, PyObject* arg) {
1339 CMessage* other_message;
1340 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg), &CMessage_Type)) {
1341 PyErr_SetString(PyExc_TypeError, "Must be a message");
1345 other_message = reinterpret_cast<CMessage*>(arg);
1346 if (other_message->message->GetDescriptor() !=
1347 self->message->GetDescriptor()) {
1348 PyErr_Format(PyExc_TypeError,
1349 "Tried to copy from a message with a different type. "
1351 self->message->GetDescriptor()->full_name().c_str(),
1352 other_message->message->GetDescriptor()->full_name().c_str());
1356 AssureWritable(self);
1358 self->message->CopyFrom(*other_message->message);
1362 static PyObject* CMessage_MergeFromString(CMessage* self, PyObject* arg) {
1364 Py_ssize_t data_length;
1365 if (PyObject_AsReadBuffer(arg, &data, &data_length) < 0) {
1369 AssureWritable(self);
1370 google::protobuf::io::CodedInputStream input(
1371 reinterpret_cast<const uint8*>(data), data_length);
1372 input.SetExtensionRegistry(GetDescriptorPool(), global_message_factory);
1373 bool success = self->message->MergePartialFromCodedStream(&input);
1375 return PyInt_FromLong(self->message->ByteSize());
1377 return PyInt_FromLong(-1);
1381 static PyObject* CMessage_ByteSize(CMessage* self, PyObject* args) {
1382 return PyLong_FromLong(self->message->ByteSize());
1385 static PyObject* CMessage_SetInParent(CMessage* self, PyObject* args) {
1386 AssureWritable(self);
1390 static PyObject* CMessage_SwapRepeatedFieldElements(
1391 CMessage* self, PyObject* args) {
1392 CFieldDescriptor* cfield_descriptor;
1394 if (!PyArg_ParseTuple(args, C("O!ii:SwapRepeatedFieldElements"),
1395 &CFieldDescriptor_Type, &cfield_descriptor,
1396 &index1, &index2)) {
1400 google::protobuf::Message* message = self->message;
1401 const google::protobuf::Reflection* reflection = message->GetReflection();
1403 reflection->SwapElements(
1404 message, cfield_descriptor->descriptor, index1, index2);
1408 static PyObject* CMessage_AddMessage(CMessage* self, PyObject* arg) {
1409 CFieldDescriptor* cfield_descriptor;
1410 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg),
1411 &CFieldDescriptor_Type)) {
1412 PyErr_SetString(PyExc_TypeError, "Must be a field descriptor");
1415 cfield_descriptor = reinterpret_cast<CFieldDescriptor*>(arg);
1416 AssureWritable(self);
1418 CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type);
1419 if (py_cmsg == NULL) {
1423 google::protobuf::Message* message = self->message;
1424 const google::protobuf::Reflection* reflection = message->GetReflection();
1425 google::protobuf::Message* sub_message =
1426 reflection->AddMessage(message, cfield_descriptor->descriptor);
1428 py_cmsg->parent = NULL;
1429 py_cmsg->full_name = sub_message->GetDescriptor()->full_name().c_str();
1430 py_cmsg->message = sub_message;
1431 py_cmsg->free_message = false;
1432 py_cmsg->read_only = false;
1433 return reinterpret_cast<PyObject*>(py_cmsg);
1436 static PyObject* CMessage_GetRepeatedMessage(CMessage* self, PyObject* args) {
1437 CFieldDescriptor* cfield_descriptor;
1439 if (!PyArg_ParseTuple(args, C("O!O:GetRepeatedMessage"),
1440 &CFieldDescriptor_Type, &cfield_descriptor, &slice)) {
1444 return InternalGetRepeatedScalarSlice(
1445 self, cfield_descriptor->descriptor, slice);
1448 static PyObject* CMessage_NewSubMessage(CMessage* self, PyObject* arg) {
1449 CFieldDescriptor* cfield_descriptor;
1450 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg),
1451 &CFieldDescriptor_Type)) {
1452 PyErr_SetString(PyExc_TypeError, "Must be a field descriptor");
1455 cfield_descriptor = reinterpret_cast<CFieldDescriptor*>(arg);
1457 CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type);
1458 if (py_cmsg == NULL) {
1462 google::protobuf::Message* message = self->message;
1463 const google::protobuf::Reflection* reflection = message->GetReflection();
1464 const google::protobuf::Message& sub_message =
1465 reflection->GetMessage(*message, cfield_descriptor->descriptor,
1466 global_message_factory);
1468 py_cmsg->full_name = sub_message.GetDescriptor()->full_name().c_str();
1469 py_cmsg->parent = self;
1470 py_cmsg->parent_field = cfield_descriptor;
1471 py_cmsg->message = const_cast<google::protobuf::Message*>(&sub_message);
1472 py_cmsg->free_message = false;
1473 py_cmsg->read_only = true;
1474 return reinterpret_cast<PyObject*>(py_cmsg);
1477 static PyObject* CMessage_MutableMessage(CMessage* self, PyObject* arg) {
1478 CFieldDescriptor* cfield_descriptor;
1479 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg),
1480 &CFieldDescriptor_Type)) {
1481 PyErr_SetString(PyExc_TypeError, "Must be a field descriptor");
1484 cfield_descriptor = reinterpret_cast<CFieldDescriptor*>(arg);
1485 AssureWritable(self);
1487 CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type);
1488 if (py_cmsg == NULL) {
1492 google::protobuf::Message* message = self->message;
1493 const google::protobuf::Reflection* reflection = message->GetReflection();
1494 google::protobuf::Message* mutable_message =
1495 reflection->MutableMessage(message, cfield_descriptor->descriptor,
1496 global_message_factory);
1498 py_cmsg->full_name = mutable_message->GetDescriptor()->full_name().c_str();
1499 py_cmsg->message = mutable_message;
1500 py_cmsg->free_message = false;
1501 py_cmsg->read_only = false;
1502 return reinterpret_cast<PyObject*>(py_cmsg);
1505 static PyObject* CMessage_Equals(CMessage* self, PyObject* arg) {
1506 CMessage* other_message;
1507 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg), &CMessage_Type)) {
1508 PyErr_SetString(PyExc_TypeError, "Must be a message");
1511 other_message = reinterpret_cast<CMessage*>(arg);
1513 if (other_message->message == self->message) {
1514 return PyBool_FromLong(1);
1517 if (other_message->message->GetDescriptor() !=
1518 self->message->GetDescriptor()) {
1519 return PyBool_FromLong(0);
1522 return PyBool_FromLong(1);
1525 static PyObject* CMessage_ListFields(CMessage* self, PyObject* args) {
1526 google::protobuf::Message* message = self->message;
1527 const google::protobuf::Reflection* reflection = message->GetReflection();
1528 vector<const google::protobuf::FieldDescriptor*> fields;
1529 reflection->ListFields(*message, &fields);
1531 PyObject* list = PyList_New(fields.size());
1536 for (unsigned int i = 0; i < fields.size(); ++i) {
1537 bool is_extension = fields[i]->is_extension();
1538 PyObject* t = PyTuple_New(2);
1544 PyObject* is_extension_object = PyBool_FromLong(is_extension ? 1 : 0);
1546 PyObject* field_name;
1549 s = &fields[i]->full_name();
1551 s = &fields[i]->name();
1553 field_name = PyString_FromStringAndSize(s->c_str(), s->length());
1554 if (field_name == NULL) {
1560 PyTuple_SET_ITEM(t, 0, is_extension_object);
1561 PyTuple_SET_ITEM(t, 1, field_name);
1562 PyList_SET_ITEM(list, i, t);
1568 static PyObject* CMessage_FindInitializationErrors(CMessage* self) {
1569 google::protobuf::Message* message = self->message;
1570 vector<string> errors;
1571 message->FindInitializationErrors(&errors);
1573 PyObject* error_list = PyList_New(errors.size());
1574 if (error_list == NULL) {
1577 for (unsigned int i = 0; i < errors.size(); ++i) {
1578 const string& error = errors[i];
1579 PyObject* error_string = PyString_FromStringAndSize(
1580 error.c_str(), error.length());
1581 if (error_string == NULL) {
1582 Py_DECREF(error_list);
1585 PyList_SET_ITEM(error_list, i, error_string);
1590 // ------ Python Constructor:
1592 PyObject* Python_NewCMessage(PyObject* ignored, PyObject* arg) {
1593 const char* message_type = PyString_AsString(arg);
1594 if (message_type == NULL) {
1598 const google::protobuf::Message* message = CreateMessage(message_type);
1599 if (message == NULL) {
1600 PyErr_Format(PyExc_TypeError, "Couldn't create message of type %s!",
1605 CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type);
1606 if (py_cmsg == NULL) {
1609 py_cmsg->message = message->New();
1610 py_cmsg->free_message = true;
1611 py_cmsg->full_name = message->GetDescriptor()->full_name().c_str();
1612 py_cmsg->read_only = false;
1613 py_cmsg->parent = NULL;
1614 py_cmsg->parent_field = NULL;
1615 return reinterpret_cast<PyObject*>(py_cmsg);
1618 // --- Module Functions (exposed to Python):
1620 PyMethodDef methods[] = {
1621 { C("NewCMessage"), (PyCFunction)Python_NewCMessage,
1623 C("Creates a new C++ protocol message, given its full name.") },
1624 { C("NewCDescriptorPool"), (PyCFunction)Python_NewCDescriptorPool,
1626 C("Creates a new C++ descriptor pool.") },
1627 { C("BuildFile"), (PyCFunction)Python_BuildFile,
1629 C("Registers a new protocol buffer file in the global C++ descriptor "
1634 // --- Exposing the C proto living inside Python proto to C code:
1636 extern const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg);
1637 extern Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg);
1639 static const google::protobuf::Message* GetCProtoInsidePyProtoImpl(PyObject* msg) {
1640 PyObject* c_msg_obj = PyObject_GetAttrString(msg, "_cmsg");
1641 if (c_msg_obj == NULL) {
1645 Py_DECREF(c_msg_obj);
1646 if (!PyObject_TypeCheck(c_msg_obj, &CMessage_Type)) {
1649 CMessage* c_msg = reinterpret_cast<CMessage*>(c_msg_obj);
1650 return c_msg->message;
1653 static google::protobuf::Message* MutableCProtoInsidePyProtoImpl(PyObject* msg) {
1654 PyObject* c_msg_obj = PyObject_GetAttrString(msg, "_cmsg");
1655 if (c_msg_obj == NULL) {
1659 Py_DECREF(c_msg_obj);
1660 if (!PyObject_TypeCheck(c_msg_obj, &CMessage_Type)) {
1663 CMessage* c_msg = reinterpret_cast<CMessage*>(c_msg_obj);
1664 AssureWritable(c_msg);
1665 return c_msg->message;
1668 // --- Module Init Function:
1670 static const char module_docstring[] =
1671 "python-proto2 is a module that can be used to enhance proto2 Python API\n"
1674 "It provides access to the protocol buffers C++ reflection API that\n"
1675 "implements the basic protocol buffer functions.";
1678 void init_net_proto2___python() {
1679 // Initialize constants.
1680 kPythonZero = PyInt_FromLong(0);
1681 kint32min_py = PyInt_FromLong(kint32min);
1682 kint32max_py = PyInt_FromLong(kint32max);
1683 kuint32max_py = PyLong_FromLongLong(kuint32max);
1684 kint64min_py = PyLong_FromLongLong(kint64min);
1685 kint64max_py = PyLong_FromLongLong(kint64max);
1686 kuint64max_py = PyLong_FromUnsignedLongLong(kuint64max);
1688 global_message_factory = new DynamicMessageFactory(GetDescriptorPool());
1689 global_message_factory->SetDelegateToGeneratedFactory(true);
1691 // Export our functions to Python.
1693 m = Py_InitModule3(C("_net_proto2___python"), methods, C(module_docstring));
1700 CMessage_Type.tp_new = PyType_GenericNew;
1701 if (PyType_Ready(&CMessage_Type) < 0) {
1705 if (!InitDescriptor()) {
1709 // Override {Get,Mutable}CProtoInsidePyProto.
1710 GetCProtoInsidePyProtoPtr = GetCProtoInsidePyProtoImpl;
1711 MutableCProtoInsidePyProtoPtr = MutableCProtoInsidePyProtoImpl;
1715 } // namespace python
1716 } // namespace protobuf
1717 } // namespace google