repeated_scalar_container.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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. default:
  248. PyErr_Format(
  249. PyExc_SystemError,
  250. "Getting value from a repeated field of unknown type %d",
  251. field_descriptor->cpp_type());
  252. }
  253. return result;
  254. }
  255. static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) {
  256. Py_ssize_t from;
  257. Py_ssize_t to;
  258. Py_ssize_t step;
  259. Py_ssize_t length;
  260. Py_ssize_t slicelength;
  261. bool return_list = false;
  262. #if PY_MAJOR_VERSION < 3
  263. if (PyInt_Check(slice)) {
  264. from = to = PyInt_AsLong(slice);
  265. } else // NOLINT
  266. #endif
  267. if (PyLong_Check(slice)) {
  268. from = to = PyLong_AsLong(slice);
  269. } else if (PySlice_Check(slice)) {
  270. length = Len(self);
  271. #if PY_MAJOR_VERSION >= 3
  272. if (PySlice_GetIndicesEx(slice,
  273. length, &from, &to, &step, &slicelength) == -1) {
  274. #else
  275. if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
  276. length, &from, &to, &step, &slicelength) == -1) {
  277. #endif
  278. return NULL;
  279. }
  280. return_list = true;
  281. } else {
  282. PyErr_SetString(PyExc_TypeError, "list indices must be integers");
  283. return NULL;
  284. }
  285. if (!return_list) {
  286. return Item(self, from);
  287. }
  288. PyObject* list = PyList_New(0);
  289. if (list == NULL) {
  290. return NULL;
  291. }
  292. if (from <= to) {
  293. if (step < 0) {
  294. return list;
  295. }
  296. for (Py_ssize_t index = from; index < to; index += step) {
  297. if (index < 0 || index >= length) {
  298. break;
  299. }
  300. ScopedPyObjectPtr s(Item(self, index));
  301. PyList_Append(list, s.get());
  302. }
  303. } else {
  304. if (step > 0) {
  305. return list;
  306. }
  307. for (Py_ssize_t index = from; index > to; index += step) {
  308. if (index < 0 || index >= length) {
  309. break;
  310. }
  311. ScopedPyObjectPtr s(Item(self, index));
  312. PyList_Append(list, s.get());
  313. }
  314. }
  315. return list;
  316. }
  317. PyObject* Append(RepeatedScalarContainer* self, PyObject* item) {
  318. cmessage::AssureWritable(self->parent);
  319. Message* message = self->message;
  320. const FieldDescriptor* field_descriptor = self->parent_field_descriptor;
  321. const Reflection* reflection = message->GetReflection();
  322. switch (field_descriptor->cpp_type()) {
  323. case FieldDescriptor::CPPTYPE_INT32: {
  324. GOOGLE_CHECK_GET_INT32(item, value, NULL);
  325. reflection->AddInt32(message, field_descriptor, value);
  326. break;
  327. }
  328. case FieldDescriptor::CPPTYPE_INT64: {
  329. GOOGLE_CHECK_GET_INT64(item, value, NULL);
  330. reflection->AddInt64(message, field_descriptor, value);
  331. break;
  332. }
  333. case FieldDescriptor::CPPTYPE_UINT32: {
  334. GOOGLE_CHECK_GET_UINT32(item, value, NULL);
  335. reflection->AddUInt32(message, field_descriptor, value);
  336. break;
  337. }
  338. case FieldDescriptor::CPPTYPE_UINT64: {
  339. GOOGLE_CHECK_GET_UINT64(item, value, NULL);
  340. reflection->AddUInt64(message, field_descriptor, value);
  341. break;
  342. }
  343. case FieldDescriptor::CPPTYPE_FLOAT: {
  344. GOOGLE_CHECK_GET_FLOAT(item, value, NULL);
  345. reflection->AddFloat(message, field_descriptor, value);
  346. break;
  347. }
  348. case FieldDescriptor::CPPTYPE_DOUBLE: {
  349. GOOGLE_CHECK_GET_DOUBLE(item, value, NULL);
  350. reflection->AddDouble(message, field_descriptor, value);
  351. break;
  352. }
  353. case FieldDescriptor::CPPTYPE_BOOL: {
  354. GOOGLE_CHECK_GET_BOOL(item, value, NULL);
  355. reflection->AddBool(message, field_descriptor, value);
  356. break;
  357. }
  358. case FieldDescriptor::CPPTYPE_STRING: {
  359. if (!CheckAndSetString(
  360. item, message, field_descriptor, reflection, true, -1)) {
  361. return NULL;
  362. }
  363. break;
  364. }
  365. case FieldDescriptor::CPPTYPE_ENUM: {
  366. GOOGLE_CHECK_GET_INT32(item, value, NULL);
  367. if (reflection->SupportsUnknownEnumValues()) {
  368. reflection->AddEnumValue(message, field_descriptor, value);
  369. } else {
  370. const EnumDescriptor* enum_descriptor = field_descriptor->enum_type();
  371. const EnumValueDescriptor* enum_value =
  372. enum_descriptor->FindValueByNumber(value);
  373. if (enum_value != NULL) {
  374. reflection->AddEnum(message, field_descriptor, enum_value);
  375. } else {
  376. ScopedPyObjectPtr s(PyObject_Str(item));
  377. if (s != NULL) {
  378. PyErr_Format(PyExc_ValueError, "Unknown enum value: %s",
  379. PyString_AsString(s.get()));
  380. }
  381. return NULL;
  382. }
  383. }
  384. break;
  385. }
  386. default:
  387. PyErr_Format(
  388. PyExc_SystemError, "Adding value to a field of unknown type %d",
  389. field_descriptor->cpp_type());
  390. return NULL;
  391. }
  392. Py_RETURN_NONE;
  393. }
  394. static int AssSubscript(RepeatedScalarContainer* self,
  395. PyObject* slice,
  396. PyObject* value) {
  397. Py_ssize_t from;
  398. Py_ssize_t to;
  399. Py_ssize_t step;
  400. Py_ssize_t length;
  401. Py_ssize_t slicelength;
  402. bool create_list = false;
  403. cmessage::AssureWritable(self->parent);
  404. Message* message = self->message;
  405. const FieldDescriptor* field_descriptor =
  406. self->parent_field_descriptor;
  407. #if PY_MAJOR_VERSION < 3
  408. if (PyInt_Check(slice)) {
  409. from = to = PyInt_AsLong(slice);
  410. } else
  411. #endif
  412. if (PyLong_Check(slice)) {
  413. from = to = PyLong_AsLong(slice);
  414. } else if (PySlice_Check(slice)) {
  415. const Reflection* reflection = message->GetReflection();
  416. length = reflection->FieldSize(*message, field_descriptor);
  417. #if PY_MAJOR_VERSION >= 3
  418. if (PySlice_GetIndicesEx(slice,
  419. length, &from, &to, &step, &slicelength) == -1) {
  420. #else
  421. if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
  422. length, &from, &to, &step, &slicelength) == -1) {
  423. #endif
  424. return -1;
  425. }
  426. create_list = true;
  427. } else {
  428. PyErr_SetString(PyExc_TypeError, "list indices must be integers");
  429. return -1;
  430. }
  431. if (value == NULL) {
  432. return cmessage::InternalDeleteRepeatedField(
  433. self->parent, field_descriptor, slice, NULL);
  434. }
  435. if (!create_list) {
  436. return AssignItem(self, from, value);
  437. }
  438. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  439. if (full_slice == NULL) {
  440. return -1;
  441. }
  442. ScopedPyObjectPtr new_list(Subscript(self, full_slice.get()));
  443. if (new_list == NULL) {
  444. return -1;
  445. }
  446. if (PySequence_SetSlice(new_list.get(), from, to, value) < 0) {
  447. return -1;
  448. }
  449. return InternalAssignRepeatedField(self, new_list.get());
  450. }
  451. PyObject* Extend(RepeatedScalarContainer* self, PyObject* value) {
  452. cmessage::AssureWritable(self->parent);
  453. // TODO(ptucker): Deprecate this behavior. b/18413862
  454. if (value == Py_None) {
  455. Py_RETURN_NONE;
  456. }
  457. if ((Py_TYPE(value)->tp_as_sequence == NULL) && PyObject_Not(value)) {
  458. Py_RETURN_NONE;
  459. }
  460. ScopedPyObjectPtr iter(PyObject_GetIter(value));
  461. if (iter == NULL) {
  462. PyErr_SetString(PyExc_TypeError, "Value must be iterable");
  463. return NULL;
  464. }
  465. ScopedPyObjectPtr next;
  466. while ((next.reset(PyIter_Next(iter.get()))) != NULL) {
  467. if (ScopedPyObjectPtr(Append(self, next.get())) == NULL) {
  468. return NULL;
  469. }
  470. }
  471. if (PyErr_Occurred()) {
  472. return NULL;
  473. }
  474. Py_RETURN_NONE;
  475. }
  476. static PyObject* Insert(RepeatedScalarContainer* self, PyObject* args) {
  477. Py_ssize_t index;
  478. PyObject* value;
  479. if (!PyArg_ParseTuple(args, "lO", &index, &value)) {
  480. return NULL;
  481. }
  482. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  483. ScopedPyObjectPtr new_list(Subscript(self, full_slice.get()));
  484. if (PyList_Insert(new_list.get(), index, value) < 0) {
  485. return NULL;
  486. }
  487. int ret = InternalAssignRepeatedField(self, new_list.get());
  488. if (ret < 0) {
  489. return NULL;
  490. }
  491. Py_RETURN_NONE;
  492. }
  493. static PyObject* Remove(RepeatedScalarContainer* self, PyObject* value) {
  494. Py_ssize_t match_index = -1;
  495. for (Py_ssize_t i = 0; i < Len(self); ++i) {
  496. ScopedPyObjectPtr elem(Item(self, i));
  497. if (PyObject_RichCompareBool(elem.get(), value, Py_EQ)) {
  498. match_index = i;
  499. break;
  500. }
  501. }
  502. if (match_index == -1) {
  503. PyErr_SetString(PyExc_ValueError, "remove(x): x not in container");
  504. return NULL;
  505. }
  506. if (AssignItem(self, match_index, NULL) < 0) {
  507. return NULL;
  508. }
  509. Py_RETURN_NONE;
  510. }
  511. static PyObject* RichCompare(RepeatedScalarContainer* self,
  512. PyObject* other,
  513. int opid) {
  514. if (opid != Py_EQ && opid != Py_NE) {
  515. Py_INCREF(Py_NotImplemented);
  516. return Py_NotImplemented;
  517. }
  518. // Copy the contents of this repeated scalar container, and other if it is
  519. // also a repeated scalar container, into Python lists so we can delegate
  520. // to the list's compare method.
  521. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  522. if (full_slice == NULL) {
  523. return NULL;
  524. }
  525. ScopedPyObjectPtr other_list_deleter;
  526. if (PyObject_TypeCheck(other, &RepeatedScalarContainer_Type)) {
  527. other_list_deleter.reset(Subscript(
  528. reinterpret_cast<RepeatedScalarContainer*>(other), full_slice.get()));
  529. other = other_list_deleter.get();
  530. }
  531. ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
  532. if (list == NULL) {
  533. return NULL;
  534. }
  535. return PyObject_RichCompare(list.get(), other, opid);
  536. }
  537. PyObject* Reduce(RepeatedScalarContainer* unused_self) {
  538. PyErr_Format(
  539. PickleError_class,
  540. "can't pickle repeated message fields, convert to list first");
  541. return NULL;
  542. }
  543. static PyObject* Sort(RepeatedScalarContainer* self,
  544. PyObject* args,
  545. PyObject* kwds) {
  546. // Support the old sort_function argument for backwards
  547. // compatibility.
  548. if (kwds != NULL) {
  549. PyObject* sort_func = PyDict_GetItemString(kwds, "sort_function");
  550. if (sort_func != NULL) {
  551. // Must set before deleting as sort_func is a borrowed reference
  552. // and kwds might be the only thing keeping it alive.
  553. if (PyDict_SetItemString(kwds, "cmp", sort_func) == -1)
  554. return NULL;
  555. if (PyDict_DelItemString(kwds, "sort_function") == -1)
  556. return NULL;
  557. }
  558. }
  559. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  560. if (full_slice == NULL) {
  561. return NULL;
  562. }
  563. ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
  564. if (list == NULL) {
  565. return NULL;
  566. }
  567. ScopedPyObjectPtr m(PyObject_GetAttrString(list.get(), "sort"));
  568. if (m == NULL) {
  569. return NULL;
  570. }
  571. ScopedPyObjectPtr res(PyObject_Call(m.get(), args, kwds));
  572. if (res == NULL) {
  573. return NULL;
  574. }
  575. int ret = InternalAssignRepeatedField(self, list.get());
  576. if (ret < 0) {
  577. return NULL;
  578. }
  579. Py_RETURN_NONE;
  580. }
  581. static PyObject* Pop(RepeatedScalarContainer* self,
  582. PyObject* args) {
  583. Py_ssize_t index = -1;
  584. if (!PyArg_ParseTuple(args, "|n", &index)) {
  585. return NULL;
  586. }
  587. PyObject* item = Item(self, index);
  588. if (item == NULL) {
  589. PyErr_Format(PyExc_IndexError,
  590. "list index (%zd) out of range",
  591. index);
  592. return NULL;
  593. }
  594. if (AssignItem(self, index, NULL) < 0) {
  595. return NULL;
  596. }
  597. return item;
  598. }
  599. static PyObject* ToStr(RepeatedScalarContainer* self) {
  600. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  601. if (full_slice == NULL) {
  602. return NULL;
  603. }
  604. ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
  605. if (list == NULL) {
  606. return NULL;
  607. }
  608. return PyObject_Repr(list.get());
  609. }
  610. // The private constructor of RepeatedScalarContainer objects.
  611. PyObject *NewContainer(
  612. CMessage* parent, const FieldDescriptor* parent_field_descriptor) {
  613. if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) {
  614. return NULL;
  615. }
  616. RepeatedScalarContainer* self = reinterpret_cast<RepeatedScalarContainer*>(
  617. PyType_GenericAlloc(&RepeatedScalarContainer_Type, 0));
  618. if (self == NULL) {
  619. return NULL;
  620. }
  621. self->message = parent->message;
  622. self->parent = parent;
  623. self->parent_field_descriptor = parent_field_descriptor;
  624. self->owner = parent->owner;
  625. return reinterpret_cast<PyObject*>(self);
  626. }
  627. // Initializes the underlying Message object of "to" so it becomes a new parent
  628. // repeated scalar, and copies all the values from "from" to it. A child scalar
  629. // container can be released by passing it as both from and to (e.g. making it
  630. // the recipient of the new parent message and copying the values from itself).
  631. static int InitializeAndCopyToParentContainer(
  632. RepeatedScalarContainer* from,
  633. RepeatedScalarContainer* to) {
  634. ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  635. if (full_slice == NULL) {
  636. return -1;
  637. }
  638. ScopedPyObjectPtr values(Subscript(from, full_slice.get()));
  639. if (values == NULL) {
  640. return -1;
  641. }
  642. Message* new_message = from->message->New();
  643. to->parent = NULL;
  644. to->parent_field_descriptor = from->parent_field_descriptor;
  645. to->message = new_message;
  646. to->owner.reset(new_message);
  647. if (InternalAssignRepeatedField(to, values.get()) < 0) {
  648. return -1;
  649. }
  650. return 0;
  651. }
  652. int Release(RepeatedScalarContainer* self) {
  653. return InitializeAndCopyToParentContainer(self, self);
  654. }
  655. PyObject* DeepCopy(RepeatedScalarContainer* self, PyObject* arg) {
  656. RepeatedScalarContainer* clone = reinterpret_cast<RepeatedScalarContainer*>(
  657. PyType_GenericAlloc(&RepeatedScalarContainer_Type, 0));
  658. if (clone == NULL) {
  659. return NULL;
  660. }
  661. if (InitializeAndCopyToParentContainer(self, clone) < 0) {
  662. Py_DECREF(clone);
  663. return NULL;
  664. }
  665. return reinterpret_cast<PyObject*>(clone);
  666. }
  667. static void Dealloc(RepeatedScalarContainer* self) {
  668. self->owner.reset();
  669. Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
  670. }
  671. void SetOwner(RepeatedScalarContainer* self,
  672. const shared_ptr<Message>& new_owner) {
  673. self->owner = new_owner;
  674. }
  675. static PySequenceMethods SqMethods = {
  676. (lenfunc)Len, /* sq_length */
  677. 0, /* sq_concat */
  678. 0, /* sq_repeat */
  679. (ssizeargfunc)Item, /* sq_item */
  680. 0, /* sq_slice */
  681. (ssizeobjargproc)AssignItem /* sq_ass_item */
  682. };
  683. static PyMappingMethods MpMethods = {
  684. (lenfunc)Len, /* mp_length */
  685. (binaryfunc)Subscript, /* mp_subscript */
  686. (objobjargproc)AssSubscript, /* mp_ass_subscript */
  687. };
  688. static PyMethodDef Methods[] = {
  689. { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
  690. "Makes a deep copy of the class." },
  691. { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
  692. "Outputs picklable representation of the repeated field." },
  693. { "append", (PyCFunction)Append, METH_O,
  694. "Appends an object to the repeated container." },
  695. { "extend", (PyCFunction)Extend, METH_O,
  696. "Appends objects to the repeated container." },
  697. { "insert", (PyCFunction)Insert, METH_VARARGS,
  698. "Appends objects to the repeated container." },
  699. { "pop", (PyCFunction)Pop, METH_VARARGS,
  700. "Removes an object from the repeated container and returns it." },
  701. { "remove", (PyCFunction)Remove, METH_O,
  702. "Removes an object from the repeated container." },
  703. { "sort", (PyCFunction)Sort, METH_VARARGS | METH_KEYWORDS,
  704. "Sorts the repeated container."},
  705. { NULL, NULL }
  706. };
  707. } // namespace repeated_scalar_container
  708. PyTypeObject RepeatedScalarContainer_Type = {
  709. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  710. FULL_MODULE_NAME ".RepeatedScalarContainer", // tp_name
  711. sizeof(RepeatedScalarContainer), // tp_basicsize
  712. 0, // tp_itemsize
  713. (destructor)repeated_scalar_container::Dealloc, // tp_dealloc
  714. 0, // tp_print
  715. 0, // tp_getattr
  716. 0, // tp_setattr
  717. 0, // tp_compare
  718. (reprfunc)repeated_scalar_container::ToStr, // tp_repr
  719. 0, // tp_as_number
  720. &repeated_scalar_container::SqMethods, // tp_as_sequence
  721. &repeated_scalar_container::MpMethods, // tp_as_mapping
  722. PyObject_HashNotImplemented, // tp_hash
  723. 0, // tp_call
  724. 0, // tp_str
  725. 0, // tp_getattro
  726. 0, // tp_setattro
  727. 0, // tp_as_buffer
  728. Py_TPFLAGS_DEFAULT, // tp_flags
  729. "A Repeated scalar container", // tp_doc
  730. 0, // tp_traverse
  731. 0, // tp_clear
  732. (richcmpfunc)repeated_scalar_container::RichCompare, // tp_richcompare
  733. 0, // tp_weaklistoffset
  734. 0, // tp_iter
  735. 0, // tp_iternext
  736. repeated_scalar_container::Methods, // tp_methods
  737. 0, // tp_members
  738. 0, // tp_getset
  739. 0, // tp_base
  740. 0, // tp_dict
  741. 0, // tp_descr_get
  742. 0, // tp_descr_set
  743. 0, // tp_dictoffset
  744. 0, // tp_init
  745. };
  746. } // namespace python
  747. } // namespace protobuf
  748. } // namespace google