repeated_scalar_container.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // http://code.google.com/p/protobuf/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  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
  14. // distribution.
  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.
  18. //
  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.
  30. // Author: anuraag@google.com (Anuraag Agrawal)
  31. // Author: tibell@google.com (Johan Tibell)
  32. #include <google/protobuf/pyext/repeated_scalar_container.h>
  33. #include <memory>
  34. #ifndef _SHARED_PTR_H
  35. #include <google/protobuf/stubs/shared_ptr.h>
  36. #endif
  37. #include <google/protobuf/stubs/common.h>
  38. #include <google/protobuf/descriptor.h>
  39. #include <google/protobuf/dynamic_message.h>
  40. #include <google/protobuf/message.h>
  41. #include <google/protobuf/pyext/descriptor.h>
  42. #include <google/protobuf/pyext/message.h>
  43. #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
  44. #if PY_MAJOR_VERSION >= 3
  45. #define PyInt_FromLong PyLong_FromLong
  46. #if PY_VERSION_HEX < 0x03030000
  47. #error "Python 3.0 - 3.2 are not supported."
  48. #else
  49. #define PyString_AsString(ob) \
  50. (PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AS_STRING(ob))
  51. #endif
  52. #endif
  53. namespace google {
  54. namespace protobuf {
  55. namespace python {
  56. extern google::protobuf::DynamicMessageFactory* global_message_factory;
  57. namespace repeated_scalar_container {
  58. static int InternalAssignRepeatedField(
  59. RepeatedScalarContainer* self, PyObject* list) {
  60. self->message->GetReflection()->ClearField(self->message,
  61. self->parent_field->descriptor);
  62. for (Py_ssize_t i = 0; i < PyList_GET_SIZE(list); ++i) {
  63. PyObject* value = PyList_GET_ITEM(list, i);
  64. if (Append(self, value) == NULL) {
  65. return -1;
  66. }
  67. }
  68. return 0;
  69. }
  70. static Py_ssize_t Len(RepeatedScalarContainer* self) {
  71. google::protobuf::Message* message = self->message;
  72. return message->GetReflection()->FieldSize(*message,
  73. self->parent_field->descriptor);
  74. }
  75. static int AssignItem(RepeatedScalarContainer* self,
  76. Py_ssize_t index,
  77. PyObject* arg) {
  78. cmessage::AssureWritable(self->parent);
  79. google::protobuf::Message* message = self->message;
  80. const google::protobuf::FieldDescriptor* field_descriptor =
  81. self->parent_field->descriptor;
  82. if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
  83. PyErr_SetString(
  84. PyExc_KeyError, "Field does not belong to message!");
  85. return -1;
  86. }
  87. const google::protobuf::Reflection* reflection = message->GetReflection();
  88. int field_size = reflection->FieldSize(*message, field_descriptor);
  89. if (index < 0) {
  90. index = field_size + index;
  91. }
  92. if (index < 0 || index >= field_size) {
  93. PyErr_Format(PyExc_IndexError,
  94. "list assignment index (%d) out of range",
  95. static_cast<int>(index));
  96. return -1;
  97. }
  98. if (arg == NULL) {
  99. ScopedPyObjectPtr py_index(PyLong_FromLong(index));
  100. return cmessage::InternalDeleteRepeatedField(message, field_descriptor,
  101. py_index, NULL);
  102. }
  103. if (PySequence_Check(arg) && !(PyBytes_Check(arg) || PyUnicode_Check(arg))) {
  104. PyErr_SetString(PyExc_TypeError, "Value must be scalar");
  105. return -1;
  106. }
  107. switch (field_descriptor->cpp_type()) {
  108. case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
  109. GOOGLE_CHECK_GET_INT32(arg, value, -1);
  110. reflection->SetRepeatedInt32(message, field_descriptor, index, value);
  111. break;
  112. }
  113. case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
  114. GOOGLE_CHECK_GET_INT64(arg, value, -1);
  115. reflection->SetRepeatedInt64(message, field_descriptor, index, value);
  116. break;
  117. }
  118. case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
  119. GOOGLE_CHECK_GET_UINT32(arg, value, -1);
  120. reflection->SetRepeatedUInt32(message, field_descriptor, index, value);
  121. break;
  122. }
  123. case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
  124. GOOGLE_CHECK_GET_UINT64(arg, value, -1);
  125. reflection->SetRepeatedUInt64(message, field_descriptor, index, value);
  126. break;
  127. }
  128. case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
  129. GOOGLE_CHECK_GET_FLOAT(arg, value, -1);
  130. reflection->SetRepeatedFloat(message, field_descriptor, index, value);
  131. break;
  132. }
  133. case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
  134. GOOGLE_CHECK_GET_DOUBLE(arg, value, -1);
  135. reflection->SetRepeatedDouble(message, field_descriptor, index, value);
  136. break;
  137. }
  138. case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
  139. GOOGLE_CHECK_GET_BOOL(arg, value, -1);
  140. reflection->SetRepeatedBool(message, field_descriptor, index, value);
  141. break;
  142. }
  143. case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
  144. if (!CheckAndSetString(
  145. arg, message, field_descriptor, reflection, false, index)) {
  146. return -1;
  147. }
  148. break;
  149. }
  150. case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
  151. GOOGLE_CHECK_GET_INT32(arg, value, -1);
  152. const google::protobuf::EnumDescriptor* enum_descriptor =
  153. field_descriptor->enum_type();
  154. const google::protobuf::EnumValueDescriptor* enum_value =
  155. enum_descriptor->FindValueByNumber(value);
  156. if (enum_value != NULL) {
  157. reflection->SetRepeatedEnum(message, field_descriptor, index,
  158. enum_value);
  159. } else {
  160. ScopedPyObjectPtr s(PyObject_Str(arg));
  161. if (s != NULL) {
  162. PyErr_Format(PyExc_ValueError, "Unknown enum value: %s",
  163. PyString_AsString(s.get()));
  164. }
  165. return -1;
  166. }
  167. break;
  168. }
  169. default:
  170. PyErr_Format(
  171. PyExc_SystemError, "Adding value to a field of unknown type %d",
  172. field_descriptor->cpp_type());
  173. return -1;
  174. }
  175. return 0;
  176. }
  177. static PyObject* Item(RepeatedScalarContainer* self, Py_ssize_t index) {
  178. google::protobuf::Message* message = self->message;
  179. const google::protobuf::FieldDescriptor* field_descriptor =
  180. self->parent_field->descriptor;
  181. const google::protobuf::Reflection* reflection = message->GetReflection();
  182. int field_size = reflection->FieldSize(*message, field_descriptor);
  183. if (index < 0) {
  184. index = field_size + index;
  185. }
  186. if (index < 0 || index >= field_size) {
  187. PyErr_Format(PyExc_IndexError,
  188. "list assignment index (%d) out of range",
  189. static_cast<int>(index));
  190. return NULL;
  191. }
  192. PyObject* result = NULL;
  193. switch (field_descriptor->cpp_type()) {
  194. case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
  195. int32 value = reflection->GetRepeatedInt32(
  196. *message, field_descriptor, index);
  197. result = PyInt_FromLong(value);
  198. break;
  199. }
  200. case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
  201. int64 value = reflection->GetRepeatedInt64(
  202. *message, field_descriptor, index);
  203. result = PyLong_FromLongLong(value);
  204. break;
  205. }
  206. case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
  207. uint32 value = reflection->GetRepeatedUInt32(
  208. *message, field_descriptor, index);
  209. result = PyLong_FromLongLong(value);
  210. break;
  211. }
  212. case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
  213. uint64 value = reflection->GetRepeatedUInt64(
  214. *message, field_descriptor, index);
  215. result = PyLong_FromUnsignedLongLong(value);
  216. break;
  217. }
  218. case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
  219. float value = reflection->GetRepeatedFloat(
  220. *message, field_descriptor, index);
  221. result = PyFloat_FromDouble(value);
  222. break;
  223. }
  224. case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
  225. double value = reflection->GetRepeatedDouble(
  226. *message, field_descriptor, index);
  227. result = PyFloat_FromDouble(value);
  228. break;
  229. }
  230. case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
  231. bool value = reflection->GetRepeatedBool(
  232. *message, field_descriptor, index);
  233. result = PyBool_FromLong(value ? 1 : 0);
  234. break;
  235. }
  236. case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
  237. const google::protobuf::EnumValueDescriptor* enum_value =
  238. message->GetReflection()->GetRepeatedEnum(
  239. *message, field_descriptor, index);
  240. result = PyInt_FromLong(enum_value->number());
  241. break;
  242. }
  243. case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
  244. string value = reflection->GetRepeatedString(
  245. *message, field_descriptor, index);
  246. result = ToStringObject(field_descriptor, value);
  247. break;
  248. }
  249. case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
  250. PyObject* py_cmsg = PyObject_CallObject(reinterpret_cast<PyObject*>(
  251. &CMessage_Type), NULL);
  252. if (py_cmsg == NULL) {
  253. return NULL;
  254. }
  255. CMessage* cmsg = reinterpret_cast<CMessage*>(py_cmsg);
  256. const google::protobuf::Message& msg = reflection->GetRepeatedMessage(
  257. *message, field_descriptor, index);
  258. cmsg->owner = self->owner;
  259. cmsg->parent = self->parent;
  260. cmsg->message = const_cast<google::protobuf::Message*>(&msg);
  261. cmsg->read_only = false;
  262. result = reinterpret_cast<PyObject*>(py_cmsg);
  263. break;
  264. }
  265. default:
  266. PyErr_Format(
  267. PyExc_SystemError,
  268. "Getting value from a repeated field of unknown type %d",
  269. field_descriptor->cpp_type());
  270. }
  271. return result;
  272. }
  273. static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) {
  274. Py_ssize_t from;
  275. Py_ssize_t to;
  276. Py_ssize_t step;
  277. Py_ssize_t length;
  278. Py_ssize_t slicelength;
  279. bool return_list = false;
  280. #if PY_MAJOR_VERSION < 3
  281. if (PyInt_Check(slice)) {
  282. from = to = PyInt_AsLong(slice);
  283. } else // NOLINT
  284. #endif
  285. if (PyLong_Check(slice)) {
  286. from = to = PyLong_AsLong(slice);
  287. } else if (PySlice_Check(slice)) {
  288. length = Len(self);
  289. #if PY_MAJOR_VERSION >= 3
  290. if (PySlice_GetIndicesEx(slice,
  291. #else
  292. if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
  293. #endif
  294. length, &from, &to, &step, &slicelength) == -1) {
  295. return NULL;
  296. }
  297. return_list = true;
  298. } else {
  299. PyErr_SetString(PyExc_TypeError, "list indices must be integers");
  300. return NULL;
  301. }
  302. if (!return_list) {
  303. return Item(self, from);
  304. }
  305. PyObject* list = PyList_New(0);
  306. if (list == NULL) {
  307. return NULL;
  308. }
  309. if (from <= to) {
  310. if (step < 0) {
  311. return list;
  312. }
  313. for (Py_ssize_t index = from; index < to; index += step) {
  314. if (index < 0 || index >= length) {
  315. break;
  316. }
  317. ScopedPyObjectPtr s(Item(self, index));
  318. PyList_Append(list, s);
  319. }
  320. } else {
  321. if (step > 0) {
  322. return list;
  323. }
  324. for (Py_ssize_t index = from; index > to; index += step) {
  325. if (index < 0 || index >= length) {
  326. break;
  327. }
  328. ScopedPyObjectPtr s(Item(self, index));
  329. PyList_Append(list, s);
  330. }
  331. }
  332. return list;
  333. }
  334. PyObject* Append(RepeatedScalarContainer* self, PyObject* item) {
  335. cmessage::AssureWritable(self->parent);
  336. google::protobuf::Message* message = self->message;
  337. const google::protobuf::FieldDescriptor* field_descriptor =
  338. self->parent_field->descriptor;
  339. if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
  340. PyErr_SetString(
  341. PyExc_KeyError, "Field does not belong to message!");
  342. return NULL;
  343. }
  344. const google::protobuf::Reflection* reflection = message->GetReflection();
  345. switch (field_descriptor->cpp_type()) {
  346. case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
  347. GOOGLE_CHECK_GET_INT32(item, value, NULL);
  348. reflection->AddInt32(message, field_descriptor, value);
  349. break;
  350. }
  351. case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
  352. GOOGLE_CHECK_GET_INT64(item, value, NULL);
  353. reflection->AddInt64(message, field_descriptor, value);
  354. break;
  355. }
  356. case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
  357. GOOGLE_CHECK_GET_UINT32(item, value, NULL);
  358. reflection->AddUInt32(message, field_descriptor, value);
  359. break;
  360. }
  361. case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
  362. GOOGLE_CHECK_GET_UINT64(item, value, NULL);
  363. reflection->AddUInt64(message, field_descriptor, value);
  364. break;
  365. }
  366. case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
  367. GOOGLE_CHECK_GET_FLOAT(item, value, NULL);
  368. reflection->AddFloat(message, field_descriptor, value);
  369. break;
  370. }
  371. case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
  372. GOOGLE_CHECK_GET_DOUBLE(item, value, NULL);
  373. reflection->AddDouble(message, field_descriptor, value);
  374. break;
  375. }
  376. case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
  377. GOOGLE_CHECK_GET_BOOL(item, value, NULL);
  378. reflection->AddBool(message, field_descriptor, value);
  379. break;
  380. }
  381. case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
  382. if (!CheckAndSetString(
  383. item, message, field_descriptor, reflection, true, -1)) {
  384. return NULL;
  385. }
  386. break;
  387. }
  388. case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
  389. GOOGLE_CHECK_GET_INT32(item, value, NULL);
  390. const google::protobuf::EnumDescriptor* enum_descriptor =
  391. field_descriptor->enum_type();
  392. const google::protobuf::EnumValueDescriptor* enum_value =
  393. enum_descriptor->FindValueByNumber(value);
  394. if (enum_value != NULL) {
  395. reflection->AddEnum(message, field_descriptor, enum_value);
  396. } else {
  397. ScopedPyObjectPtr s(PyObject_Str(item));
  398. if (s != NULL) {
  399. PyErr_Format(PyExc_ValueError, "Unknown enum value: %s",
  400. PyString_AsString(s.get()));
  401. }
  402. return NULL;
  403. }
  404. break;
  405. }
  406. default:
  407. PyErr_Format(
  408. PyExc_SystemError, "Adding value to a field of unknown type %d",
  409. field_descriptor->cpp_type());
  410. return NULL;
  411. }
  412. Py_RETURN_NONE;
  413. }
  414. static int AssSubscript(RepeatedScalarContainer* self,
  415. PyObject* slice,
  416. PyObject* value) {
  417. Py_ssize_t from;
  418. Py_ssize_t to;
  419. Py_ssize_t step;
  420. Py_ssize_t length;
  421. Py_ssize_t slicelength;
  422. bool create_list = false;
  423. cmessage::AssureWritable(self->parent);
  424. google::protobuf::Message* message = self->message;
  425. const google::protobuf::FieldDescriptor* field_descriptor =
  426. self->parent_field->descriptor;
  427. #if PY_MAJOR_VERSION < 3
  428. if (PyInt_Check(slice)) {
  429. from = to = PyInt_AsLong(slice);
  430. } else
  431. #endif
  432. if (PyLong_Check(slice)) {
  433. from = to = PyLong_AsLong(slice);
  434. } else if (PySlice_Check(slice)) {
  435. const google::protobuf::Reflection* reflection = message->GetReflection();
  436. length = reflection->FieldSize(*message, field_descriptor);
  437. #if PY_MAJOR_VERSION >= 3
  438. if (PySlice_GetIndicesEx(slice,
  439. #else
  440. if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
  441. #endif
  442. length, &from, &to, &step, &slicelength) == -1) {
  443. return -1;
  444. }
  445. create_list = true;
  446. } else {
  447. PyErr_SetString(PyExc_TypeError, "list indices must be integers");
  448. return -1;
  449. }
  450. if (value == NULL) {
  451. return cmessage::InternalDeleteRepeatedField(
  452. message, field_descriptor, slice, NULL);
  453. }
  454. if (!create_list) {
  455. return AssignItem(self, from, value);
  456. }
  457. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  458. if (full_slice == NULL) {
  459. return -1;
  460. }
  461. ScopedPyObjectPtr new_list(Subscript(self, full_slice));
  462. if (new_list == NULL) {
  463. return -1;
  464. }
  465. if (PySequence_SetSlice(new_list, from, to, value) < 0) {
  466. return -1;
  467. }
  468. return InternalAssignRepeatedField(self, new_list);
  469. }
  470. PyObject* Extend(RepeatedScalarContainer* self, PyObject* value) {
  471. cmessage::AssureWritable(self->parent);
  472. if (PyObject_Not(value)) {
  473. Py_RETURN_NONE;
  474. }
  475. ScopedPyObjectPtr iter(PyObject_GetIter(value));
  476. if (iter == NULL) {
  477. PyErr_SetString(PyExc_TypeError, "Value must be iterable");
  478. return NULL;
  479. }
  480. ScopedPyObjectPtr next;
  481. while ((next.reset(PyIter_Next(iter))) != NULL) {
  482. if (Append(self, next) == NULL) {
  483. return NULL;
  484. }
  485. }
  486. if (PyErr_Occurred()) {
  487. return NULL;
  488. }
  489. Py_RETURN_NONE;
  490. }
  491. static PyObject* Insert(RepeatedScalarContainer* self, PyObject* args) {
  492. Py_ssize_t index;
  493. PyObject* value;
  494. if (!PyArg_ParseTuple(args, "lO", &index, &value)) {
  495. return NULL;
  496. }
  497. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  498. ScopedPyObjectPtr new_list(Subscript(self, full_slice));
  499. if (PyList_Insert(new_list, index, value) < 0) {
  500. return NULL;
  501. }
  502. int ret = InternalAssignRepeatedField(self, new_list);
  503. if (ret < 0) {
  504. return NULL;
  505. }
  506. Py_RETURN_NONE;
  507. }
  508. static PyObject* Remove(RepeatedScalarContainer* self, PyObject* value) {
  509. Py_ssize_t match_index = -1;
  510. for (Py_ssize_t i = 0; i < Len(self); ++i) {
  511. ScopedPyObjectPtr elem(Item(self, i));
  512. if (PyObject_RichCompareBool(elem, value, Py_EQ)) {
  513. match_index = i;
  514. break;
  515. }
  516. }
  517. if (match_index == -1) {
  518. PyErr_SetString(PyExc_ValueError, "remove(x): x not in container");
  519. return NULL;
  520. }
  521. if (AssignItem(self, match_index, NULL) < 0) {
  522. return NULL;
  523. }
  524. Py_RETURN_NONE;
  525. }
  526. static PyObject* RichCompare(RepeatedScalarContainer* self,
  527. PyObject* other,
  528. int opid) {
  529. if (opid != Py_EQ && opid != Py_NE) {
  530. Py_INCREF(Py_NotImplemented);
  531. return Py_NotImplemented;
  532. }
  533. // Copy the contents of this repeated scalar container, and other if it is
  534. // also a repeated scalar container, into Python lists so we can delegate
  535. // to the list's compare method.
  536. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  537. if (full_slice == NULL) {
  538. return NULL;
  539. }
  540. ScopedPyObjectPtr other_list_deleter;
  541. if (PyObject_TypeCheck(other, &RepeatedScalarContainer_Type)) {
  542. other_list_deleter.reset(Subscript(
  543. reinterpret_cast<RepeatedScalarContainer*>(other), full_slice));
  544. other = other_list_deleter.get();
  545. }
  546. ScopedPyObjectPtr list(Subscript(self, full_slice));
  547. if (list == NULL) {
  548. return NULL;
  549. }
  550. return PyObject_RichCompare(list, other, opid);
  551. }
  552. PyObject* Reduce(RepeatedScalarContainer* unused_self) {
  553. PyErr_Format(
  554. PickleError_class,
  555. "can't pickle repeated message fields, convert to list first");
  556. return NULL;
  557. }
  558. static PyObject* Sort(RepeatedScalarContainer* self,
  559. PyObject* args,
  560. PyObject* kwds) {
  561. // Support the old sort_function argument for backwards
  562. // compatibility.
  563. if (kwds != NULL) {
  564. PyObject* sort_func = PyDict_GetItemString(kwds, "sort_function");
  565. if (sort_func != NULL) {
  566. // Must set before deleting as sort_func is a borrowed reference
  567. // and kwds might be the only thing keeping it alive.
  568. if (PyDict_SetItemString(kwds, "cmp", sort_func) == -1)
  569. return NULL;
  570. if (PyDict_DelItemString(kwds, "sort_function") == -1)
  571. return NULL;
  572. }
  573. }
  574. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  575. if (full_slice == NULL) {
  576. return NULL;
  577. }
  578. ScopedPyObjectPtr list(Subscript(self, full_slice));
  579. if (list == NULL) {
  580. return NULL;
  581. }
  582. ScopedPyObjectPtr m(PyObject_GetAttrString(list, "sort"));
  583. if (m == NULL) {
  584. return NULL;
  585. }
  586. ScopedPyObjectPtr res(PyObject_Call(m, args, kwds));
  587. if (res == NULL) {
  588. return NULL;
  589. }
  590. int ret = InternalAssignRepeatedField(self, list);
  591. if (ret < 0) {
  592. return NULL;
  593. }
  594. Py_RETURN_NONE;
  595. }
  596. static int Init(RepeatedScalarContainer* self,
  597. PyObject* args,
  598. PyObject* kwargs) {
  599. PyObject* py_parent;
  600. PyObject* py_parent_field;
  601. if (!PyArg_UnpackTuple(args, "__init__()", 2, 2, &py_parent,
  602. &py_parent_field)) {
  603. return -1;
  604. }
  605. if (!PyObject_TypeCheck(py_parent, &CMessage_Type)) {
  606. PyErr_Format(PyExc_TypeError,
  607. "expect %s, but got %s",
  608. CMessage_Type.tp_name,
  609. Py_TYPE(py_parent)->tp_name);
  610. return -1;
  611. }
  612. if (!PyObject_TypeCheck(py_parent_field, &CFieldDescriptor_Type)) {
  613. PyErr_Format(PyExc_TypeError,
  614. "expect %s, but got %s",
  615. CFieldDescriptor_Type.tp_name,
  616. Py_TYPE(py_parent_field)->tp_name);
  617. return -1;
  618. }
  619. CMessage* cmessage = reinterpret_cast<CMessage*>(py_parent);
  620. CFieldDescriptor* cdescriptor = reinterpret_cast<CFieldDescriptor*>(
  621. py_parent_field);
  622. if (!FIELD_BELONGS_TO_MESSAGE(cdescriptor->descriptor, cmessage->message)) {
  623. PyErr_SetString(
  624. PyExc_KeyError, "Field does not belong to message!");
  625. return -1;
  626. }
  627. self->message = cmessage->message;
  628. self->parent = cmessage;
  629. self->parent_field = cdescriptor;
  630. self->owner = cmessage->owner;
  631. return 0;
  632. }
  633. // Initializes the underlying Message object of "to" so it becomes a new parent
  634. // repeated scalar, and copies all the values from "from" to it. A child scalar
  635. // container can be released by passing it as both from and to (e.g. making it
  636. // the recipient of the new parent message and copying the values from itself).
  637. static int InitializeAndCopyToParentContainer(
  638. RepeatedScalarContainer* from,
  639. RepeatedScalarContainer* to) {
  640. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  641. if (full_slice == NULL) {
  642. return -1;
  643. }
  644. ScopedPyObjectPtr values(Subscript(from, full_slice));
  645. if (values == NULL) {
  646. return -1;
  647. }
  648. google::protobuf::Message* new_message = global_message_factory->GetPrototype(
  649. from->message->GetDescriptor())->New();
  650. to->parent = NULL;
  651. // TODO(anuraag): Document why it's OK to hang on to parent_field,
  652. // even though it's a weak reference. It ought to be enough to
  653. // hold on to the FieldDescriptor only.
  654. to->parent_field = from->parent_field;
  655. to->message = new_message;
  656. to->owner.reset(new_message);
  657. if (InternalAssignRepeatedField(to, values) < 0) {
  658. return -1;
  659. }
  660. return 0;
  661. }
  662. int Release(RepeatedScalarContainer* self) {
  663. return InitializeAndCopyToParentContainer(self, self);
  664. }
  665. PyObject* DeepCopy(RepeatedScalarContainer* self, PyObject* arg) {
  666. ScopedPyObjectPtr init_args(
  667. PyTuple_Pack(2, self->parent, self->parent_field));
  668. PyObject* clone = PyObject_CallObject(
  669. reinterpret_cast<PyObject*>(&RepeatedScalarContainer_Type), init_args);
  670. if (clone == NULL) {
  671. return NULL;
  672. }
  673. if (!PyObject_TypeCheck(clone, &RepeatedScalarContainer_Type)) {
  674. Py_DECREF(clone);
  675. return NULL;
  676. }
  677. if (InitializeAndCopyToParentContainer(
  678. self, reinterpret_cast<RepeatedScalarContainer*>(clone)) < 0) {
  679. Py_DECREF(clone);
  680. return NULL;
  681. }
  682. return clone;
  683. }
  684. static void Dealloc(RepeatedScalarContainer* self) {
  685. self->owner.reset();
  686. Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
  687. }
  688. void SetOwner(RepeatedScalarContainer* self,
  689. const shared_ptr<Message>& new_owner) {
  690. self->owner = new_owner;
  691. }
  692. static PySequenceMethods SqMethods = {
  693. (lenfunc)Len, /* sq_length */
  694. 0, /* sq_concat */
  695. 0, /* sq_repeat */
  696. (ssizeargfunc)Item, /* sq_item */
  697. 0, /* sq_slice */
  698. (ssizeobjargproc)AssignItem /* sq_ass_item */
  699. };
  700. static PyMappingMethods MpMethods = {
  701. (lenfunc)Len, /* mp_length */
  702. (binaryfunc)Subscript, /* mp_subscript */
  703. (objobjargproc)AssSubscript, /* mp_ass_subscript */
  704. };
  705. static PyMethodDef Methods[] = {
  706. { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
  707. "Makes a deep copy of the class." },
  708. { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
  709. "Outputs picklable representation of the repeated field." },
  710. { "append", (PyCFunction)Append, METH_O,
  711. "Appends an object to the repeated container." },
  712. { "extend", (PyCFunction)Extend, METH_O,
  713. "Appends objects to the repeated container." },
  714. { "insert", (PyCFunction)Insert, METH_VARARGS,
  715. "Appends objects to the repeated container." },
  716. { "remove", (PyCFunction)Remove, METH_O,
  717. "Removes an object from the repeated container." },
  718. { "sort", (PyCFunction)Sort, METH_VARARGS | METH_KEYWORDS,
  719. "Sorts the repeated container."},
  720. { NULL, NULL }
  721. };
  722. } // namespace repeated_scalar_container
  723. PyTypeObject RepeatedScalarContainer_Type = {
  724. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  725. "google.protobuf.internal."
  726. "cpp._message.RepeatedScalarContainer", // tp_name
  727. sizeof(RepeatedScalarContainer), // tp_basicsize
  728. 0, // tp_itemsize
  729. (destructor)repeated_scalar_container::Dealloc, // tp_dealloc
  730. 0, // tp_print
  731. 0, // tp_getattr
  732. 0, // tp_setattr
  733. 0, // tp_compare
  734. 0, // tp_repr
  735. 0, // tp_as_number
  736. &repeated_scalar_container::SqMethods, // tp_as_sequence
  737. &repeated_scalar_container::MpMethods, // tp_as_mapping
  738. 0, // tp_hash
  739. 0, // tp_call
  740. 0, // tp_str
  741. 0, // tp_getattro
  742. 0, // tp_setattro
  743. 0, // tp_as_buffer
  744. Py_TPFLAGS_DEFAULT, // tp_flags
  745. "A Repeated scalar container", // tp_doc
  746. 0, // tp_traverse
  747. 0, // tp_clear
  748. (richcmpfunc)repeated_scalar_container::RichCompare, // tp_richcompare
  749. 0, // tp_weaklistoffset
  750. 0, // tp_iter
  751. 0, // tp_iternext
  752. repeated_scalar_container::Methods, // tp_methods
  753. 0, // tp_members
  754. 0, // tp_getset
  755. 0, // tp_base
  756. 0, // tp_dict
  757. 0, // tp_descr_get
  758. 0, // tp_descr_set
  759. 0, // tp_dictoffset
  760. (initproc)repeated_scalar_container::Init, // tp_init
  761. };
  762. } // namespace python
  763. } // namespace protobuf
  764. } // namespace google