repeated_scalar_container.cc 26 KB

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