店播爬取Python脚本

descriptor_containers.cc 53KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  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. // Mappings and Sequences of descriptors.
  31. // Used by Descriptor.fields_by_name, EnumDescriptor.values...
  32. //
  33. // They avoid the allocation of a full dictionary or a full list: they simply
  34. // store a pointer to the parent descriptor, use the C++ Descriptor methods (see
  35. // net/proto2/public/descriptor.h) to retrieve other descriptors, and create
  36. // Python objects on the fly.
  37. //
  38. // The containers fully conform to abc.Mapping and abc.Sequence, and behave just
  39. // like read-only dictionaries and lists.
  40. //
  41. // Because the interface of C++ Descriptors is quite regular, this file actually
  42. // defines only three types, the exact behavior of a container is controlled by
  43. // a DescriptorContainerDef structure, which contains functions that uses the
  44. // public Descriptor API.
  45. //
  46. // Note: This DescriptorContainerDef is similar to the "virtual methods table"
  47. // that a C++ compiler generates for a class. We have to make it explicit
  48. // because the Python API is based on C, and does not play well with C++
  49. // inheritance.
  50. #include <Python.h>
  51. #include <google/protobuf/descriptor.h>
  52. #include <google/protobuf/pyext/descriptor_containers.h>
  53. #include <google/protobuf/pyext/descriptor_pool.h>
  54. #include <google/protobuf/pyext/descriptor.h>
  55. #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
  56. #if PY_MAJOR_VERSION >= 3
  57. #define PyString_FromStringAndSize PyUnicode_FromStringAndSize
  58. #define PyString_FromFormat PyUnicode_FromFormat
  59. #define PyInt_FromLong PyLong_FromLong
  60. #if PY_VERSION_HEX < 0x03030000
  61. #error "Python 3.0 - 3.2 are not supported."
  62. #endif
  63. #define PyString_AsStringAndSize(ob, charpp, sizep) \
  64. (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
  65. PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
  66. ? -1 \
  67. : 0) \
  68. : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
  69. #endif
  70. namespace google {
  71. namespace protobuf {
  72. namespace python {
  73. struct PyContainer;
  74. typedef int (*CountMethod)(PyContainer* self);
  75. typedef const void* (*GetByIndexMethod)(PyContainer* self, int index);
  76. typedef const void* (*GetByNameMethod)(PyContainer* self,
  77. ConstStringParam name);
  78. typedef const void* (*GetByCamelcaseNameMethod)(PyContainer* self,
  79. ConstStringParam name);
  80. typedef const void* (*GetByNumberMethod)(PyContainer* self, int index);
  81. typedef PyObject* (*NewObjectFromItemMethod)(const void* descriptor);
  82. typedef const std::string& (*GetItemNameMethod)(const void* descriptor);
  83. typedef const std::string& (*GetItemCamelcaseNameMethod)(
  84. const void* descriptor);
  85. typedef int (*GetItemNumberMethod)(const void* descriptor);
  86. typedef int (*GetItemIndexMethod)(const void* descriptor);
  87. struct DescriptorContainerDef {
  88. const char* mapping_name;
  89. // Returns the number of items in the container.
  90. CountMethod count_fn;
  91. // Retrieve item by index (usually the order of declaration in the proto file)
  92. // Used by sequences, but also iterators. 0 <= index < Count().
  93. GetByIndexMethod get_by_index_fn;
  94. // Retrieve item by name (usually a call to some 'FindByName' method).
  95. // Used by "by_name" mappings.
  96. GetByNameMethod get_by_name_fn;
  97. // Retrieve item by camelcase name (usually a call to some
  98. // 'FindByCamelcaseName' method). Used by "by_camelcase_name" mappings.
  99. GetByCamelcaseNameMethod get_by_camelcase_name_fn;
  100. // Retrieve item by declared number (field tag, or enum value).
  101. // Used by "by_number" mappings.
  102. GetByNumberMethod get_by_number_fn;
  103. // Converts a item C++ descriptor to a Python object. Returns a new reference.
  104. NewObjectFromItemMethod new_object_from_item_fn;
  105. // Retrieve the name of an item. Used by iterators on "by_name" mappings.
  106. GetItemNameMethod get_item_name_fn;
  107. // Retrieve the camelcase name of an item. Used by iterators on
  108. // "by_camelcase_name" mappings.
  109. GetItemCamelcaseNameMethod get_item_camelcase_name_fn;
  110. // Retrieve the number of an item. Used by iterators on "by_number" mappings.
  111. GetItemNumberMethod get_item_number_fn;
  112. // Retrieve the index of an item for the container type.
  113. // Used by "__contains__".
  114. // If not set, "x in sequence" will do a linear search.
  115. GetItemIndexMethod get_item_index_fn;
  116. };
  117. struct PyContainer {
  118. PyObject_HEAD
  119. // The proto2 descriptor this container belongs to the global DescriptorPool.
  120. const void* descriptor;
  121. // A pointer to a static structure with function pointers that control the
  122. // behavior of the container. Very similar to the table of virtual functions
  123. // of a C++ class.
  124. const DescriptorContainerDef* container_def;
  125. // The kind of container: list, or dict by name or value.
  126. enum ContainerKind {
  127. KIND_SEQUENCE,
  128. KIND_BYNAME,
  129. KIND_BYCAMELCASENAME,
  130. KIND_BYNUMBER,
  131. } kind;
  132. };
  133. struct PyContainerIterator {
  134. PyObject_HEAD
  135. // The container we are iterating over. Own a reference.
  136. PyContainer* container;
  137. // The current index in the iterator.
  138. int index;
  139. // The kind of container: list, or dict by name or value.
  140. enum IterKind {
  141. KIND_ITERKEY,
  142. KIND_ITERVALUE,
  143. KIND_ITERITEM,
  144. KIND_ITERVALUE_REVERSED, // For sequences
  145. } kind;
  146. };
  147. namespace descriptor {
  148. // Returns the C++ item descriptor for a given Python key.
  149. // When the descriptor is found, return true and set *item.
  150. // When the descriptor is not found, return true, but set *item to NULL.
  151. // On error, returns false with an exception set.
  152. static bool _GetItemByKey(PyContainer* self, PyObject* key, const void** item) {
  153. switch (self->kind) {
  154. case PyContainer::KIND_BYNAME:
  155. {
  156. char* name;
  157. Py_ssize_t name_size;
  158. if (PyString_AsStringAndSize(key, &name, &name_size) < 0) {
  159. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  160. // Not a string, cannot be in the container.
  161. PyErr_Clear();
  162. *item = NULL;
  163. return true;
  164. }
  165. return false;
  166. }
  167. *item = self->container_def->get_by_name_fn(
  168. self, StringParam(name, name_size));
  169. return true;
  170. }
  171. case PyContainer::KIND_BYCAMELCASENAME:
  172. {
  173. char* camelcase_name;
  174. Py_ssize_t name_size;
  175. if (PyString_AsStringAndSize(key, &camelcase_name, &name_size) < 0) {
  176. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  177. // Not a string, cannot be in the container.
  178. PyErr_Clear();
  179. *item = NULL;
  180. return true;
  181. }
  182. return false;
  183. }
  184. *item = self->container_def->get_by_camelcase_name_fn(
  185. self, StringParam(camelcase_name, name_size));
  186. return true;
  187. }
  188. case PyContainer::KIND_BYNUMBER:
  189. {
  190. Py_ssize_t number = PyNumber_AsSsize_t(key, NULL);
  191. if (number == -1 && PyErr_Occurred()) {
  192. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  193. // Not a number, cannot be in the container.
  194. PyErr_Clear();
  195. *item = NULL;
  196. return true;
  197. }
  198. return false;
  199. }
  200. *item = self->container_def->get_by_number_fn(self, number);
  201. return true;
  202. }
  203. default:
  204. PyErr_SetNone(PyExc_NotImplementedError);
  205. return false;
  206. }
  207. }
  208. // Returns the key of the object at the given index.
  209. // Used when iterating over mappings.
  210. static PyObject* _NewKey_ByIndex(PyContainer* self, Py_ssize_t index) {
  211. const void* item = self->container_def->get_by_index_fn(self, index);
  212. switch (self->kind) {
  213. case PyContainer::KIND_BYNAME:
  214. {
  215. const std::string& name(self->container_def->get_item_name_fn(item));
  216. return PyString_FromStringAndSize(name.c_str(), name.size());
  217. }
  218. case PyContainer::KIND_BYCAMELCASENAME:
  219. {
  220. const std::string& name(
  221. self->container_def->get_item_camelcase_name_fn(item));
  222. return PyString_FromStringAndSize(name.c_str(), name.size());
  223. }
  224. case PyContainer::KIND_BYNUMBER:
  225. {
  226. int value = self->container_def->get_item_number_fn(item);
  227. return PyInt_FromLong(value);
  228. }
  229. default:
  230. PyErr_SetNone(PyExc_NotImplementedError);
  231. return NULL;
  232. }
  233. }
  234. // Returns the object at the given index.
  235. // Also used when iterating over mappings.
  236. static PyObject* _NewObj_ByIndex(PyContainer* self, Py_ssize_t index) {
  237. return self->container_def->new_object_from_item_fn(
  238. self->container_def->get_by_index_fn(self, index));
  239. }
  240. static Py_ssize_t Length(PyContainer* self) {
  241. return self->container_def->count_fn(self);
  242. }
  243. // The DescriptorMapping type.
  244. static PyObject* Subscript(PyContainer* self, PyObject* key) {
  245. const void* item = NULL;
  246. if (!_GetItemByKey(self, key, &item)) {
  247. return NULL;
  248. }
  249. if (!item) {
  250. PyErr_SetObject(PyExc_KeyError, key);
  251. return NULL;
  252. }
  253. return self->container_def->new_object_from_item_fn(item);
  254. }
  255. static int AssSubscript(PyContainer* self, PyObject* key, PyObject* value) {
  256. if (_CalledFromGeneratedFile(0)) {
  257. return 0;
  258. }
  259. PyErr_Format(PyExc_TypeError,
  260. "'%.200s' object does not support item assignment",
  261. Py_TYPE(self)->tp_name);
  262. return -1;
  263. }
  264. static PyMappingMethods MappingMappingMethods = {
  265. (lenfunc)Length, // mp_length
  266. (binaryfunc)Subscript, // mp_subscript
  267. (objobjargproc)AssSubscript, // mp_ass_subscript
  268. };
  269. static int Contains(PyContainer* self, PyObject* key) {
  270. const void* item = NULL;
  271. if (!_GetItemByKey(self, key, &item)) {
  272. return -1;
  273. }
  274. if (item) {
  275. return 1;
  276. } else {
  277. return 0;
  278. }
  279. }
  280. static PyObject* ContainerRepr(PyContainer* self) {
  281. const char* kind = "";
  282. switch (self->kind) {
  283. case PyContainer::KIND_SEQUENCE:
  284. kind = "sequence";
  285. break;
  286. case PyContainer::KIND_BYNAME:
  287. kind = "mapping by name";
  288. break;
  289. case PyContainer::KIND_BYCAMELCASENAME:
  290. kind = "mapping by camelCase name";
  291. break;
  292. case PyContainer::KIND_BYNUMBER:
  293. kind = "mapping by number";
  294. break;
  295. }
  296. return PyString_FromFormat(
  297. "<%s %s>", self->container_def->mapping_name, kind);
  298. }
  299. extern PyTypeObject DescriptorMapping_Type;
  300. extern PyTypeObject DescriptorSequence_Type;
  301. // A sequence container can only be equal to another sequence container, or (for
  302. // backward compatibility) to a list containing the same items.
  303. // Returns 1 if equal, 0 if unequal, -1 on error.
  304. static int DescriptorSequence_Equal(PyContainer* self, PyObject* other) {
  305. // Check the identity of C++ pointers.
  306. if (PyObject_TypeCheck(other, &DescriptorSequence_Type)) {
  307. PyContainer* other_container = reinterpret_cast<PyContainer*>(other);
  308. if (self->descriptor == other_container->descriptor &&
  309. self->container_def == other_container->container_def &&
  310. self->kind == other_container->kind) {
  311. return 1;
  312. } else {
  313. return 0;
  314. }
  315. }
  316. // If other is a list
  317. if (PyList_Check(other)) {
  318. // return list(self) == other
  319. int size = Length(self);
  320. if (size != PyList_Size(other)) {
  321. return false;
  322. }
  323. for (int index = 0; index < size; index++) {
  324. ScopedPyObjectPtr value1(_NewObj_ByIndex(self, index));
  325. if (value1 == NULL) {
  326. return -1;
  327. }
  328. PyObject* value2 = PyList_GetItem(other, index);
  329. if (value2 == NULL) {
  330. return -1;
  331. }
  332. int cmp = PyObject_RichCompareBool(value1.get(), value2, Py_EQ);
  333. if (cmp != 1) // error or not equal
  334. return cmp;
  335. }
  336. // All items were found and equal
  337. return 1;
  338. }
  339. // Any other object is different.
  340. return 0;
  341. }
  342. // A mapping container can only be equal to another mapping container, or (for
  343. // backward compatibility) to a dict containing the same items.
  344. // Returns 1 if equal, 0 if unequal, -1 on error.
  345. static int DescriptorMapping_Equal(PyContainer* self, PyObject* other) {
  346. // Check the identity of C++ pointers.
  347. if (PyObject_TypeCheck(other, &DescriptorMapping_Type)) {
  348. PyContainer* other_container = reinterpret_cast<PyContainer*>(other);
  349. if (self->descriptor == other_container->descriptor &&
  350. self->container_def == other_container->container_def &&
  351. self->kind == other_container->kind) {
  352. return 1;
  353. } else {
  354. return 0;
  355. }
  356. }
  357. // If other is a dict
  358. if (PyDict_Check(other)) {
  359. // equivalent to dict(self.items()) == other
  360. int size = Length(self);
  361. if (size != PyDict_Size(other)) {
  362. return false;
  363. }
  364. for (int index = 0; index < size; index++) {
  365. ScopedPyObjectPtr key(_NewKey_ByIndex(self, index));
  366. if (key == NULL) {
  367. return -1;
  368. }
  369. ScopedPyObjectPtr value1(_NewObj_ByIndex(self, index));
  370. if (value1 == NULL) {
  371. return -1;
  372. }
  373. PyObject* value2 = PyDict_GetItem(other, key.get());
  374. if (value2 == NULL) {
  375. // Not found in the other dictionary
  376. return 0;
  377. }
  378. int cmp = PyObject_RichCompareBool(value1.get(), value2, Py_EQ);
  379. if (cmp != 1) // error or not equal
  380. return cmp;
  381. }
  382. // All items were found and equal
  383. return 1;
  384. }
  385. // Any other object is different.
  386. return 0;
  387. }
  388. static PyObject* RichCompare(PyContainer* self, PyObject* other, int opid) {
  389. if (opid != Py_EQ && opid != Py_NE) {
  390. Py_INCREF(Py_NotImplemented);
  391. return Py_NotImplemented;
  392. }
  393. int result;
  394. if (self->kind == PyContainer::KIND_SEQUENCE) {
  395. result = DescriptorSequence_Equal(self, other);
  396. } else {
  397. result = DescriptorMapping_Equal(self, other);
  398. }
  399. if (result < 0) {
  400. return NULL;
  401. }
  402. if (result ^ (opid == Py_NE)) {
  403. Py_RETURN_TRUE;
  404. } else {
  405. Py_RETURN_FALSE;
  406. }
  407. }
  408. static PySequenceMethods MappingSequenceMethods = {
  409. 0, // sq_length
  410. 0, // sq_concat
  411. 0, // sq_repeat
  412. 0, // sq_item
  413. 0, // sq_slice
  414. 0, // sq_ass_item
  415. 0, // sq_ass_slice
  416. (objobjproc)Contains, // sq_contains
  417. };
  418. static PyObject* Get(PyContainer* self, PyObject* args) {
  419. PyObject* key;
  420. PyObject* default_value = Py_None;
  421. if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &default_value)) {
  422. return NULL;
  423. }
  424. const void* item;
  425. if (!_GetItemByKey(self, key, &item)) {
  426. return NULL;
  427. }
  428. if (item == NULL) {
  429. Py_INCREF(default_value);
  430. return default_value;
  431. }
  432. return self->container_def->new_object_from_item_fn(item);
  433. }
  434. static PyObject* Keys(PyContainer* self, PyObject* args) {
  435. Py_ssize_t count = Length(self);
  436. ScopedPyObjectPtr list(PyList_New(count));
  437. if (list == NULL) {
  438. return NULL;
  439. }
  440. for (Py_ssize_t index = 0; index < count; ++index) {
  441. PyObject* key = _NewKey_ByIndex(self, index);
  442. if (key == NULL) {
  443. return NULL;
  444. }
  445. PyList_SET_ITEM(list.get(), index, key);
  446. }
  447. return list.release();
  448. }
  449. static PyObject* Values(PyContainer* self, PyObject* args) {
  450. Py_ssize_t count = Length(self);
  451. ScopedPyObjectPtr list(PyList_New(count));
  452. if (list == NULL) {
  453. return NULL;
  454. }
  455. for (Py_ssize_t index = 0; index < count; ++index) {
  456. PyObject* value = _NewObj_ByIndex(self, index);
  457. if (value == NULL) {
  458. return NULL;
  459. }
  460. PyList_SET_ITEM(list.get(), index, value);
  461. }
  462. return list.release();
  463. }
  464. static PyObject* Items(PyContainer* self, PyObject* args) {
  465. Py_ssize_t count = Length(self);
  466. ScopedPyObjectPtr list(PyList_New(count));
  467. if (list == NULL) {
  468. return NULL;
  469. }
  470. for (Py_ssize_t index = 0; index < count; ++index) {
  471. ScopedPyObjectPtr obj(PyTuple_New(2));
  472. if (obj == NULL) {
  473. return NULL;
  474. }
  475. PyObject* key = _NewKey_ByIndex(self, index);
  476. if (key == NULL) {
  477. return NULL;
  478. }
  479. PyTuple_SET_ITEM(obj.get(), 0, key);
  480. PyObject* value = _NewObj_ByIndex(self, index);
  481. if (value == NULL) {
  482. return NULL;
  483. }
  484. PyTuple_SET_ITEM(obj.get(), 1, value);
  485. PyList_SET_ITEM(list.get(), index, obj.release());
  486. }
  487. return list.release();
  488. }
  489. static PyObject* NewContainerIterator(PyContainer* mapping,
  490. PyContainerIterator::IterKind kind);
  491. static PyObject* Iter(PyContainer* self) {
  492. return NewContainerIterator(self, PyContainerIterator::KIND_ITERKEY);
  493. }
  494. static PyObject* IterKeys(PyContainer* self, PyObject* args) {
  495. return NewContainerIterator(self, PyContainerIterator::KIND_ITERKEY);
  496. }
  497. static PyObject* IterValues(PyContainer* self, PyObject* args) {
  498. return NewContainerIterator(self, PyContainerIterator::KIND_ITERVALUE);
  499. }
  500. static PyObject* IterItems(PyContainer* self, PyObject* args) {
  501. return NewContainerIterator(self, PyContainerIterator::KIND_ITERITEM);
  502. }
  503. static PyMethodDef MappingMethods[] = {
  504. { "get", (PyCFunction)Get, METH_VARARGS, },
  505. { "keys", (PyCFunction)Keys, METH_NOARGS, },
  506. { "values", (PyCFunction)Values, METH_NOARGS, },
  507. { "items", (PyCFunction)Items, METH_NOARGS, },
  508. { "iterkeys", (PyCFunction)IterKeys, METH_NOARGS, },
  509. { "itervalues", (PyCFunction)IterValues, METH_NOARGS, },
  510. { "iteritems", (PyCFunction)IterItems, METH_NOARGS, },
  511. {NULL}
  512. };
  513. PyTypeObject DescriptorMapping_Type = {
  514. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  515. "DescriptorMapping", // tp_name
  516. sizeof(PyContainer), // tp_basicsize
  517. 0, // tp_itemsize
  518. 0, // tp_dealloc
  519. 0, // tp_print
  520. 0, // tp_getattr
  521. 0, // tp_setattr
  522. 0, // tp_compare
  523. (reprfunc)ContainerRepr, // tp_repr
  524. 0, // tp_as_number
  525. &MappingSequenceMethods, // tp_as_sequence
  526. &MappingMappingMethods, // tp_as_mapping
  527. 0, // tp_hash
  528. 0, // tp_call
  529. 0, // tp_str
  530. 0, // tp_getattro
  531. 0, // tp_setattro
  532. 0, // tp_as_buffer
  533. Py_TPFLAGS_DEFAULT, // tp_flags
  534. 0, // tp_doc
  535. 0, // tp_traverse
  536. 0, // tp_clear
  537. (richcmpfunc)RichCompare, // tp_richcompare
  538. 0, // tp_weaklistoffset
  539. (getiterfunc)Iter, // tp_iter
  540. 0, // tp_iternext
  541. MappingMethods, // tp_methods
  542. 0, // tp_members
  543. 0, // tp_getset
  544. 0, // tp_base
  545. 0, // tp_dict
  546. 0, // tp_descr_get
  547. 0, // tp_descr_set
  548. 0, // tp_dictoffset
  549. 0, // tp_init
  550. 0, // tp_alloc
  551. 0, // tp_new
  552. 0, // tp_free
  553. };
  554. // The DescriptorSequence type.
  555. static PyObject* GetItem(PyContainer* self, Py_ssize_t index) {
  556. if (index < 0) {
  557. index += Length(self);
  558. }
  559. if (index < 0 || index >= Length(self)) {
  560. PyErr_SetString(PyExc_IndexError, "index out of range");
  561. return NULL;
  562. }
  563. return _NewObj_ByIndex(self, index);
  564. }
  565. static PyObject *
  566. SeqSubscript(PyContainer* self, PyObject* item) {
  567. if (PyIndex_Check(item)) {
  568. Py_ssize_t index;
  569. index = PyNumber_AsSsize_t(item, PyExc_IndexError);
  570. if (index == -1 && PyErr_Occurred())
  571. return NULL;
  572. return GetItem(self, index);
  573. }
  574. // Materialize the list and delegate the operation to it.
  575. ScopedPyObjectPtr list(PyObject_CallFunctionObjArgs(
  576. reinterpret_cast<PyObject*>(&PyList_Type), self, NULL));
  577. if (list == NULL) {
  578. return NULL;
  579. }
  580. return Py_TYPE(list.get())->tp_as_mapping->mp_subscript(list.get(), item);
  581. }
  582. // Returns the position of the item in the sequence, of -1 if not found.
  583. // This function never fails.
  584. int Find(PyContainer* self, PyObject* item) {
  585. // The item can only be in one position: item.index.
  586. // Check that self[item.index] == item, it's faster than a linear search.
  587. //
  588. // This assumes that sequences are only defined by syntax of the .proto file:
  589. // a specific item belongs to only one sequence, depending on its position in
  590. // the .proto file definition.
  591. const void* descriptor_ptr = PyDescriptor_AsVoidPtr(item);
  592. if (descriptor_ptr == NULL) {
  593. PyErr_Clear();
  594. // Not a descriptor, it cannot be in the list.
  595. return -1;
  596. }
  597. if (self->container_def->get_item_index_fn) {
  598. int index = self->container_def->get_item_index_fn(descriptor_ptr);
  599. if (index < 0 || index >= Length(self)) {
  600. // This index is not from this collection.
  601. return -1;
  602. }
  603. if (self->container_def->get_by_index_fn(self, index) != descriptor_ptr) {
  604. // The descriptor at this index is not the same.
  605. return -1;
  606. }
  607. // self[item.index] == item, so return the index.
  608. return index;
  609. } else {
  610. // Fall back to linear search.
  611. int length = Length(self);
  612. for (int index=0; index < length; index++) {
  613. if (self->container_def->get_by_index_fn(self, index) == descriptor_ptr) {
  614. return index;
  615. }
  616. }
  617. // Not found
  618. return -1;
  619. }
  620. }
  621. // Implements list.index(): the position of the item is in the sequence.
  622. static PyObject* Index(PyContainer* self, PyObject* item) {
  623. int position = Find(self, item);
  624. if (position < 0) {
  625. // Not found
  626. PyErr_SetNone(PyExc_ValueError);
  627. return NULL;
  628. } else {
  629. return PyInt_FromLong(position);
  630. }
  631. }
  632. // Implements "list.__contains__()": is the object in the sequence.
  633. static int SeqContains(PyContainer* self, PyObject* item) {
  634. int position = Find(self, item);
  635. if (position < 0) {
  636. return 0;
  637. } else {
  638. return 1;
  639. }
  640. }
  641. // Implements list.count(): number of occurrences of the item in the sequence.
  642. // An item can only appear once in a sequence. If it exists, return 1.
  643. static PyObject* Count(PyContainer* self, PyObject* item) {
  644. int position = Find(self, item);
  645. if (position < 0) {
  646. return PyInt_FromLong(0);
  647. } else {
  648. return PyInt_FromLong(1);
  649. }
  650. }
  651. static PyObject* Append(PyContainer* self, PyObject* args) {
  652. if (_CalledFromGeneratedFile(0)) {
  653. Py_RETURN_NONE;
  654. }
  655. PyErr_Format(PyExc_TypeError,
  656. "'%.200s' object is not a mutable sequence",
  657. Py_TYPE(self)->tp_name);
  658. return NULL;
  659. }
  660. static PyObject* Reversed(PyContainer* self, PyObject* args) {
  661. return NewContainerIterator(self,
  662. PyContainerIterator::KIND_ITERVALUE_REVERSED);
  663. }
  664. static PyMethodDef SeqMethods[] = {
  665. { "index", (PyCFunction)Index, METH_O, },
  666. { "count", (PyCFunction)Count, METH_O, },
  667. { "append", (PyCFunction)Append, METH_O, },
  668. { "__reversed__", (PyCFunction)Reversed, METH_NOARGS, },
  669. {NULL}
  670. };
  671. static PySequenceMethods SeqSequenceMethods = {
  672. (lenfunc)Length, // sq_length
  673. 0, // sq_concat
  674. 0, // sq_repeat
  675. (ssizeargfunc)GetItem, // sq_item
  676. 0, // sq_slice
  677. 0, // sq_ass_item
  678. 0, // sq_ass_slice
  679. (objobjproc)SeqContains, // sq_contains
  680. };
  681. static PyMappingMethods SeqMappingMethods = {
  682. (lenfunc)Length, // mp_length
  683. (binaryfunc)SeqSubscript, // mp_subscript
  684. 0, // mp_ass_subscript
  685. };
  686. PyTypeObject DescriptorSequence_Type = {
  687. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  688. "DescriptorSequence", // tp_name
  689. sizeof(PyContainer), // tp_basicsize
  690. 0, // tp_itemsize
  691. 0, // tp_dealloc
  692. 0, // tp_print
  693. 0, // tp_getattr
  694. 0, // tp_setattr
  695. 0, // tp_compare
  696. (reprfunc)ContainerRepr, // tp_repr
  697. 0, // tp_as_number
  698. &SeqSequenceMethods, // tp_as_sequence
  699. &SeqMappingMethods, // tp_as_mapping
  700. 0, // tp_hash
  701. 0, // tp_call
  702. 0, // tp_str
  703. 0, // tp_getattro
  704. 0, // tp_setattro
  705. 0, // tp_as_buffer
  706. Py_TPFLAGS_DEFAULT, // tp_flags
  707. 0, // tp_doc
  708. 0, // tp_traverse
  709. 0, // tp_clear
  710. (richcmpfunc)RichCompare, // tp_richcompare
  711. 0, // tp_weaklistoffset
  712. 0, // tp_iter
  713. 0, // tp_iternext
  714. SeqMethods, // tp_methods
  715. 0, // tp_members
  716. 0, // tp_getset
  717. 0, // tp_base
  718. 0, // tp_dict
  719. 0, // tp_descr_get
  720. 0, // tp_descr_set
  721. 0, // tp_dictoffset
  722. 0, // tp_init
  723. 0, // tp_alloc
  724. 0, // tp_new
  725. 0, // tp_free
  726. };
  727. static PyObject* NewMappingByName(
  728. DescriptorContainerDef* container_def, const void* descriptor) {
  729. PyContainer* self = PyObject_New(PyContainer, &DescriptorMapping_Type);
  730. if (self == NULL) {
  731. return NULL;
  732. }
  733. self->descriptor = descriptor;
  734. self->container_def = container_def;
  735. self->kind = PyContainer::KIND_BYNAME;
  736. return reinterpret_cast<PyObject*>(self);
  737. }
  738. static PyObject* NewMappingByCamelcaseName(
  739. DescriptorContainerDef* container_def, const void* descriptor) {
  740. PyContainer* self = PyObject_New(PyContainer, &DescriptorMapping_Type);
  741. if (self == NULL) {
  742. return NULL;
  743. }
  744. self->descriptor = descriptor;
  745. self->container_def = container_def;
  746. self->kind = PyContainer::KIND_BYCAMELCASENAME;
  747. return reinterpret_cast<PyObject*>(self);
  748. }
  749. static PyObject* NewMappingByNumber(
  750. DescriptorContainerDef* container_def, const void* descriptor) {
  751. if (container_def->get_by_number_fn == NULL ||
  752. container_def->get_item_number_fn == NULL) {
  753. PyErr_SetNone(PyExc_NotImplementedError);
  754. return NULL;
  755. }
  756. PyContainer* self = PyObject_New(PyContainer, &DescriptorMapping_Type);
  757. if (self == NULL) {
  758. return NULL;
  759. }
  760. self->descriptor = descriptor;
  761. self->container_def = container_def;
  762. self->kind = PyContainer::KIND_BYNUMBER;
  763. return reinterpret_cast<PyObject*>(self);
  764. }
  765. static PyObject* NewSequence(
  766. DescriptorContainerDef* container_def, const void* descriptor) {
  767. PyContainer* self = PyObject_New(PyContainer, &DescriptorSequence_Type);
  768. if (self == NULL) {
  769. return NULL;
  770. }
  771. self->descriptor = descriptor;
  772. self->container_def = container_def;
  773. self->kind = PyContainer::KIND_SEQUENCE;
  774. return reinterpret_cast<PyObject*>(self);
  775. }
  776. // Implement iterators over PyContainers.
  777. static void Iterator_Dealloc(PyContainerIterator* self) {
  778. Py_CLEAR(self->container);
  779. Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
  780. }
  781. static PyObject* Iterator_Next(PyContainerIterator* self) {
  782. int count = self->container->container_def->count_fn(self->container);
  783. if (self->index >= count) {
  784. // Return NULL with no exception to indicate the end.
  785. return NULL;
  786. }
  787. int index = self->index;
  788. self->index += 1;
  789. switch (self->kind) {
  790. case PyContainerIterator::KIND_ITERKEY:
  791. return _NewKey_ByIndex(self->container, index);
  792. case PyContainerIterator::KIND_ITERVALUE:
  793. return _NewObj_ByIndex(self->container, index);
  794. case PyContainerIterator::KIND_ITERVALUE_REVERSED:
  795. return _NewObj_ByIndex(self->container, count - index - 1);
  796. case PyContainerIterator::KIND_ITERITEM:
  797. {
  798. PyObject* obj = PyTuple_New(2);
  799. if (obj == NULL) {
  800. return NULL;
  801. }
  802. PyObject* key = _NewKey_ByIndex(self->container, index);
  803. if (key == NULL) {
  804. Py_DECREF(obj);
  805. return NULL;
  806. }
  807. PyTuple_SET_ITEM(obj, 0, key);
  808. PyObject* value = _NewObj_ByIndex(self->container, index);
  809. if (value == NULL) {
  810. Py_DECREF(obj);
  811. return NULL;
  812. }
  813. PyTuple_SET_ITEM(obj, 1, value);
  814. return obj;
  815. }
  816. default:
  817. PyErr_SetNone(PyExc_NotImplementedError);
  818. return NULL;
  819. }
  820. }
  821. static PyTypeObject ContainerIterator_Type = {
  822. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  823. "DescriptorContainerIterator", // tp_name
  824. sizeof(PyContainerIterator), // tp_basicsize
  825. 0, // tp_itemsize
  826. (destructor)Iterator_Dealloc, // tp_dealloc
  827. 0, // tp_print
  828. 0, // tp_getattr
  829. 0, // tp_setattr
  830. 0, // tp_compare
  831. 0, // tp_repr
  832. 0, // tp_as_number
  833. 0, // tp_as_sequence
  834. 0, // tp_as_mapping
  835. 0, // tp_hash
  836. 0, // tp_call
  837. 0, // tp_str
  838. 0, // tp_getattro
  839. 0, // tp_setattro
  840. 0, // tp_as_buffer
  841. Py_TPFLAGS_DEFAULT, // tp_flags
  842. 0, // tp_doc
  843. 0, // tp_traverse
  844. 0, // tp_clear
  845. 0, // tp_richcompare
  846. 0, // tp_weaklistoffset
  847. PyObject_SelfIter, // tp_iter
  848. (iternextfunc)Iterator_Next, // tp_iternext
  849. 0, // tp_methods
  850. 0, // tp_members
  851. 0, // tp_getset
  852. 0, // tp_base
  853. 0, // tp_dict
  854. 0, // tp_descr_get
  855. 0, // tp_descr_set
  856. 0, // tp_dictoffset
  857. 0, // tp_init
  858. 0, // tp_alloc
  859. 0, // tp_new
  860. 0, // tp_free
  861. };
  862. static PyObject* NewContainerIterator(PyContainer* container,
  863. PyContainerIterator::IterKind kind) {
  864. PyContainerIterator* self = PyObject_New(PyContainerIterator,
  865. &ContainerIterator_Type);
  866. if (self == NULL) {
  867. return NULL;
  868. }
  869. Py_INCREF(container);
  870. self->container = container;
  871. self->kind = kind;
  872. self->index = 0;
  873. return reinterpret_cast<PyObject*>(self);
  874. }
  875. } // namespace descriptor
  876. // Now define the real collections!
  877. namespace message_descriptor {
  878. typedef const Descriptor* ParentDescriptor;
  879. static ParentDescriptor GetDescriptor(PyContainer* self) {
  880. return reinterpret_cast<ParentDescriptor>(self->descriptor);
  881. }
  882. namespace fields {
  883. typedef const FieldDescriptor* ItemDescriptor;
  884. static int Count(PyContainer* self) {
  885. return GetDescriptor(self)->field_count();
  886. }
  887. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  888. return GetDescriptor(self)->FindFieldByName(name);
  889. }
  890. static const void* GetByCamelcaseName(PyContainer* self,
  891. ConstStringParam name) {
  892. return GetDescriptor(self)->FindFieldByCamelcaseName(name);
  893. }
  894. static const void* GetByNumber(PyContainer* self, int number) {
  895. return GetDescriptor(self)->FindFieldByNumber(number);
  896. }
  897. static const void* GetByIndex(PyContainer* self, int index) {
  898. return GetDescriptor(self)->field(index);
  899. }
  900. static PyObject* NewObjectFromItem(const void* item) {
  901. return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  902. }
  903. static const std::string& GetItemName(const void* item) {
  904. return static_cast<ItemDescriptor>(item)->name();
  905. }
  906. static const std::string& GetItemCamelcaseName(const void* item) {
  907. return static_cast<ItemDescriptor>(item)->camelcase_name();
  908. }
  909. static int GetItemNumber(const void* item) {
  910. return static_cast<ItemDescriptor>(item)->number();
  911. }
  912. static int GetItemIndex(const void* item) {
  913. return static_cast<ItemDescriptor>(item)->index();
  914. }
  915. static DescriptorContainerDef ContainerDef = {
  916. "MessageFields",
  917. Count,
  918. GetByIndex,
  919. GetByName,
  920. GetByCamelcaseName,
  921. GetByNumber,
  922. NewObjectFromItem,
  923. GetItemName,
  924. GetItemCamelcaseName,
  925. GetItemNumber,
  926. GetItemIndex,
  927. };
  928. } // namespace fields
  929. PyObject* NewMessageFieldsByName(ParentDescriptor descriptor) {
  930. return descriptor::NewMappingByName(&fields::ContainerDef, descriptor);
  931. }
  932. PyObject* NewMessageFieldsByCamelcaseName(ParentDescriptor descriptor) {
  933. return descriptor::NewMappingByCamelcaseName(&fields::ContainerDef,
  934. descriptor);
  935. }
  936. PyObject* NewMessageFieldsByNumber(ParentDescriptor descriptor) {
  937. return descriptor::NewMappingByNumber(&fields::ContainerDef, descriptor);
  938. }
  939. PyObject* NewMessageFieldsSeq(ParentDescriptor descriptor) {
  940. return descriptor::NewSequence(&fields::ContainerDef, descriptor);
  941. }
  942. namespace nested_types {
  943. typedef const Descriptor* ItemDescriptor;
  944. static int Count(PyContainer* self) {
  945. return GetDescriptor(self)->nested_type_count();
  946. }
  947. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  948. return GetDescriptor(self)->FindNestedTypeByName(name);
  949. }
  950. static const void* GetByIndex(PyContainer* self, int index) {
  951. return GetDescriptor(self)->nested_type(index);
  952. }
  953. static PyObject* NewObjectFromItem(const void* item) {
  954. return PyMessageDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  955. }
  956. static const std::string& GetItemName(const void* item) {
  957. return static_cast<ItemDescriptor>(item)->name();
  958. }
  959. static int GetItemIndex(const void* item) {
  960. return static_cast<ItemDescriptor>(item)->index();
  961. }
  962. static DescriptorContainerDef ContainerDef = {
  963. "MessageNestedTypes",
  964. Count,
  965. GetByIndex,
  966. GetByName,
  967. NULL,
  968. NULL,
  969. NewObjectFromItem,
  970. GetItemName,
  971. NULL,
  972. NULL,
  973. GetItemIndex,
  974. };
  975. } // namespace nested_types
  976. PyObject* NewMessageNestedTypesSeq(ParentDescriptor descriptor) {
  977. return descriptor::NewSequence(&nested_types::ContainerDef, descriptor);
  978. }
  979. PyObject* NewMessageNestedTypesByName(ParentDescriptor descriptor) {
  980. return descriptor::NewMappingByName(&nested_types::ContainerDef, descriptor);
  981. }
  982. namespace enums {
  983. typedef const EnumDescriptor* ItemDescriptor;
  984. static int Count(PyContainer* self) {
  985. return GetDescriptor(self)->enum_type_count();
  986. }
  987. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  988. return GetDescriptor(self)->FindEnumTypeByName(name);
  989. }
  990. static const void* GetByIndex(PyContainer* self, int index) {
  991. return GetDescriptor(self)->enum_type(index);
  992. }
  993. static PyObject* NewObjectFromItem(const void* item) {
  994. return PyEnumDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  995. }
  996. static const std::string& GetItemName(const void* item) {
  997. return static_cast<ItemDescriptor>(item)->name();
  998. }
  999. static int GetItemIndex(const void* item) {
  1000. return static_cast<ItemDescriptor>(item)->index();
  1001. }
  1002. static DescriptorContainerDef ContainerDef = {
  1003. "MessageNestedEnums",
  1004. Count,
  1005. GetByIndex,
  1006. GetByName,
  1007. NULL,
  1008. NULL,
  1009. NewObjectFromItem,
  1010. GetItemName,
  1011. NULL,
  1012. NULL,
  1013. GetItemIndex,
  1014. };
  1015. } // namespace enums
  1016. PyObject* NewMessageEnumsByName(ParentDescriptor descriptor) {
  1017. return descriptor::NewMappingByName(&enums::ContainerDef, descriptor);
  1018. }
  1019. PyObject* NewMessageEnumsSeq(ParentDescriptor descriptor) {
  1020. return descriptor::NewSequence(&enums::ContainerDef, descriptor);
  1021. }
  1022. namespace enumvalues {
  1023. // This is the "enum_values_by_name" mapping, which collects values from all
  1024. // enum types in a message.
  1025. //
  1026. // Note that the behavior of the C++ descriptor is different: it will search and
  1027. // return the first value that matches the name, whereas the Python
  1028. // implementation retrieves the last one.
  1029. typedef const EnumValueDescriptor* ItemDescriptor;
  1030. static int Count(PyContainer* self) {
  1031. int count = 0;
  1032. for (int i = 0; i < GetDescriptor(self)->enum_type_count(); ++i) {
  1033. count += GetDescriptor(self)->enum_type(i)->value_count();
  1034. }
  1035. return count;
  1036. }
  1037. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  1038. return GetDescriptor(self)->FindEnumValueByName(name);
  1039. }
  1040. static const void* GetByIndex(PyContainer* self, int index) {
  1041. // This is not optimal, but the number of enums *types* in a given message
  1042. // is small. This function is only used when iterating over the mapping.
  1043. const EnumDescriptor* enum_type = NULL;
  1044. int enum_type_count = GetDescriptor(self)->enum_type_count();
  1045. for (int i = 0; i < enum_type_count; ++i) {
  1046. enum_type = GetDescriptor(self)->enum_type(i);
  1047. int enum_value_count = enum_type->value_count();
  1048. if (index < enum_value_count) {
  1049. // Found it!
  1050. break;
  1051. }
  1052. index -= enum_value_count;
  1053. }
  1054. // The next statement cannot overflow, because this function is only called by
  1055. // internal iterators which ensure that 0 <= index < Count().
  1056. return enum_type->value(index);
  1057. }
  1058. static PyObject* NewObjectFromItem(const void* item) {
  1059. return PyEnumValueDescriptor_FromDescriptor(
  1060. static_cast<ItemDescriptor>(item));
  1061. }
  1062. static const std::string& GetItemName(const void* item) {
  1063. return static_cast<ItemDescriptor>(item)->name();
  1064. }
  1065. static DescriptorContainerDef ContainerDef = {
  1066. "MessageEnumValues",
  1067. Count,
  1068. GetByIndex,
  1069. GetByName,
  1070. NULL,
  1071. NULL,
  1072. NewObjectFromItem,
  1073. GetItemName,
  1074. NULL,
  1075. NULL,
  1076. NULL,
  1077. };
  1078. } // namespace enumvalues
  1079. PyObject* NewMessageEnumValuesByName(ParentDescriptor descriptor) {
  1080. return descriptor::NewMappingByName(&enumvalues::ContainerDef, descriptor);
  1081. }
  1082. namespace extensions {
  1083. typedef const FieldDescriptor* ItemDescriptor;
  1084. static int Count(PyContainer* self) {
  1085. return GetDescriptor(self)->extension_count();
  1086. }
  1087. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  1088. return GetDescriptor(self)->FindExtensionByName(name);
  1089. }
  1090. static const void* GetByIndex(PyContainer* self, int index) {
  1091. return GetDescriptor(self)->extension(index);
  1092. }
  1093. static PyObject* NewObjectFromItem(const void* item) {
  1094. return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1095. }
  1096. static const std::string& GetItemName(const void* item) {
  1097. return static_cast<ItemDescriptor>(item)->name();
  1098. }
  1099. static int GetItemIndex(const void* item) {
  1100. return static_cast<ItemDescriptor>(item)->index();
  1101. }
  1102. static DescriptorContainerDef ContainerDef = {
  1103. "MessageExtensions",
  1104. Count,
  1105. GetByIndex,
  1106. GetByName,
  1107. NULL,
  1108. NULL,
  1109. NewObjectFromItem,
  1110. GetItemName,
  1111. NULL,
  1112. NULL,
  1113. GetItemIndex,
  1114. };
  1115. } // namespace extensions
  1116. PyObject* NewMessageExtensionsByName(ParentDescriptor descriptor) {
  1117. return descriptor::NewMappingByName(&extensions::ContainerDef, descriptor);
  1118. }
  1119. PyObject* NewMessageExtensionsSeq(ParentDescriptor descriptor) {
  1120. return descriptor::NewSequence(&extensions::ContainerDef, descriptor);
  1121. }
  1122. namespace oneofs {
  1123. typedef const OneofDescriptor* ItemDescriptor;
  1124. static int Count(PyContainer* self) {
  1125. return GetDescriptor(self)->oneof_decl_count();
  1126. }
  1127. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  1128. return GetDescriptor(self)->FindOneofByName(name);
  1129. }
  1130. static const void* GetByIndex(PyContainer* self, int index) {
  1131. return GetDescriptor(self)->oneof_decl(index);
  1132. }
  1133. static PyObject* NewObjectFromItem(const void* item) {
  1134. return PyOneofDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1135. }
  1136. static const std::string& GetItemName(const void* item) {
  1137. return static_cast<ItemDescriptor>(item)->name();
  1138. }
  1139. static int GetItemIndex(const void* item) {
  1140. return static_cast<ItemDescriptor>(item)->index();
  1141. }
  1142. static DescriptorContainerDef ContainerDef = {
  1143. "MessageOneofs",
  1144. Count,
  1145. GetByIndex,
  1146. GetByName,
  1147. NULL,
  1148. NULL,
  1149. NewObjectFromItem,
  1150. GetItemName,
  1151. NULL,
  1152. NULL,
  1153. GetItemIndex,
  1154. };
  1155. } // namespace oneofs
  1156. PyObject* NewMessageOneofsByName(ParentDescriptor descriptor) {
  1157. return descriptor::NewMappingByName(&oneofs::ContainerDef, descriptor);
  1158. }
  1159. PyObject* NewMessageOneofsSeq(ParentDescriptor descriptor) {
  1160. return descriptor::NewSequence(&oneofs::ContainerDef, descriptor);
  1161. }
  1162. } // namespace message_descriptor
  1163. namespace enum_descriptor {
  1164. typedef const EnumDescriptor* ParentDescriptor;
  1165. static ParentDescriptor GetDescriptor(PyContainer* self) {
  1166. return reinterpret_cast<ParentDescriptor>(self->descriptor);
  1167. }
  1168. namespace enumvalues {
  1169. typedef const EnumValueDescriptor* ItemDescriptor;
  1170. static int Count(PyContainer* self) {
  1171. return GetDescriptor(self)->value_count();
  1172. }
  1173. static const void* GetByIndex(PyContainer* self, int index) {
  1174. return GetDescriptor(self)->value(index);
  1175. }
  1176. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  1177. return GetDescriptor(self)->FindValueByName(name);
  1178. }
  1179. static const void* GetByNumber(PyContainer* self, int number) {
  1180. return GetDescriptor(self)->FindValueByNumber(number);
  1181. }
  1182. static PyObject* NewObjectFromItem(const void* item) {
  1183. return PyEnumValueDescriptor_FromDescriptor(
  1184. static_cast<ItemDescriptor>(item));
  1185. }
  1186. static const std::string& GetItemName(const void* item) {
  1187. return static_cast<ItemDescriptor>(item)->name();
  1188. }
  1189. static int GetItemNumber(const void* item) {
  1190. return static_cast<ItemDescriptor>(item)->number();
  1191. }
  1192. static int GetItemIndex(const void* item) {
  1193. return static_cast<ItemDescriptor>(item)->index();
  1194. }
  1195. static DescriptorContainerDef ContainerDef = {
  1196. "EnumValues",
  1197. Count,
  1198. GetByIndex,
  1199. GetByName,
  1200. NULL,
  1201. GetByNumber,
  1202. NewObjectFromItem,
  1203. GetItemName,
  1204. NULL,
  1205. GetItemNumber,
  1206. GetItemIndex,
  1207. };
  1208. } // namespace enumvalues
  1209. PyObject* NewEnumValuesByName(ParentDescriptor descriptor) {
  1210. return descriptor::NewMappingByName(&enumvalues::ContainerDef, descriptor);
  1211. }
  1212. PyObject* NewEnumValuesByNumber(ParentDescriptor descriptor) {
  1213. return descriptor::NewMappingByNumber(&enumvalues::ContainerDef, descriptor);
  1214. }
  1215. PyObject* NewEnumValuesSeq(ParentDescriptor descriptor) {
  1216. return descriptor::NewSequence(&enumvalues::ContainerDef, descriptor);
  1217. }
  1218. } // namespace enum_descriptor
  1219. namespace oneof_descriptor {
  1220. typedef const OneofDescriptor* ParentDescriptor;
  1221. static ParentDescriptor GetDescriptor(PyContainer* self) {
  1222. return reinterpret_cast<ParentDescriptor>(self->descriptor);
  1223. }
  1224. namespace fields {
  1225. typedef const FieldDescriptor* ItemDescriptor;
  1226. static int Count(PyContainer* self) {
  1227. return GetDescriptor(self)->field_count();
  1228. }
  1229. static const void* GetByIndex(PyContainer* self, int index) {
  1230. return GetDescriptor(self)->field(index);
  1231. }
  1232. static PyObject* NewObjectFromItem(const void* item) {
  1233. return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1234. }
  1235. static int GetItemIndex(const void* item) {
  1236. return static_cast<ItemDescriptor>(item)->index_in_oneof();
  1237. }
  1238. static DescriptorContainerDef ContainerDef = {
  1239. "OneofFields",
  1240. Count,
  1241. GetByIndex,
  1242. NULL,
  1243. NULL,
  1244. NULL,
  1245. NewObjectFromItem,
  1246. NULL,
  1247. NULL,
  1248. NULL,
  1249. GetItemIndex,
  1250. };
  1251. } // namespace fields
  1252. PyObject* NewOneofFieldsSeq(ParentDescriptor descriptor) {
  1253. return descriptor::NewSequence(&fields::ContainerDef, descriptor);
  1254. }
  1255. } // namespace oneof_descriptor
  1256. namespace service_descriptor {
  1257. typedef const ServiceDescriptor* ParentDescriptor;
  1258. static ParentDescriptor GetDescriptor(PyContainer* self) {
  1259. return reinterpret_cast<ParentDescriptor>(self->descriptor);
  1260. }
  1261. namespace methods {
  1262. typedef const MethodDescriptor* ItemDescriptor;
  1263. static int Count(PyContainer* self) {
  1264. return GetDescriptor(self)->method_count();
  1265. }
  1266. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  1267. return GetDescriptor(self)->FindMethodByName(name);
  1268. }
  1269. static const void* GetByIndex(PyContainer* self, int index) {
  1270. return GetDescriptor(self)->method(index);
  1271. }
  1272. static PyObject* NewObjectFromItem(const void* item) {
  1273. return PyMethodDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1274. }
  1275. static const std::string& GetItemName(const void* item) {
  1276. return static_cast<ItemDescriptor>(item)->name();
  1277. }
  1278. static int GetItemIndex(const void* item) {
  1279. return static_cast<ItemDescriptor>(item)->index();
  1280. }
  1281. static DescriptorContainerDef ContainerDef = {
  1282. "ServiceMethods",
  1283. Count,
  1284. GetByIndex,
  1285. GetByName,
  1286. NULL,
  1287. NULL,
  1288. NewObjectFromItem,
  1289. GetItemName,
  1290. NULL,
  1291. NULL,
  1292. GetItemIndex,
  1293. };
  1294. } // namespace methods
  1295. PyObject* NewServiceMethodsSeq(ParentDescriptor descriptor) {
  1296. return descriptor::NewSequence(&methods::ContainerDef, descriptor);
  1297. }
  1298. PyObject* NewServiceMethodsByName(ParentDescriptor descriptor) {
  1299. return descriptor::NewMappingByName(&methods::ContainerDef, descriptor);
  1300. }
  1301. } // namespace service_descriptor
  1302. namespace file_descriptor {
  1303. typedef const FileDescriptor* ParentDescriptor;
  1304. static ParentDescriptor GetDescriptor(PyContainer* self) {
  1305. return reinterpret_cast<ParentDescriptor>(self->descriptor);
  1306. }
  1307. namespace messages {
  1308. typedef const Descriptor* ItemDescriptor;
  1309. static int Count(PyContainer* self) {
  1310. return GetDescriptor(self)->message_type_count();
  1311. }
  1312. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  1313. return GetDescriptor(self)->FindMessageTypeByName(name);
  1314. }
  1315. static const void* GetByIndex(PyContainer* self, int index) {
  1316. return GetDescriptor(self)->message_type(index);
  1317. }
  1318. static PyObject* NewObjectFromItem(const void* item) {
  1319. return PyMessageDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1320. }
  1321. static const std::string& GetItemName(const void* item) {
  1322. return static_cast<ItemDescriptor>(item)->name();
  1323. }
  1324. static int GetItemIndex(const void* item) {
  1325. return static_cast<ItemDescriptor>(item)->index();
  1326. }
  1327. static DescriptorContainerDef ContainerDef = {
  1328. "FileMessages",
  1329. Count,
  1330. GetByIndex,
  1331. GetByName,
  1332. NULL,
  1333. NULL,
  1334. NewObjectFromItem,
  1335. GetItemName,
  1336. NULL,
  1337. NULL,
  1338. GetItemIndex,
  1339. };
  1340. } // namespace messages
  1341. PyObject* NewFileMessageTypesByName(ParentDescriptor descriptor) {
  1342. return descriptor::NewMappingByName(&messages::ContainerDef, descriptor);
  1343. }
  1344. namespace enums {
  1345. typedef const EnumDescriptor* ItemDescriptor;
  1346. static int Count(PyContainer* self) {
  1347. return GetDescriptor(self)->enum_type_count();
  1348. }
  1349. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  1350. return GetDescriptor(self)->FindEnumTypeByName(name);
  1351. }
  1352. static const void* GetByIndex(PyContainer* self, int index) {
  1353. return GetDescriptor(self)->enum_type(index);
  1354. }
  1355. static PyObject* NewObjectFromItem(const void* item) {
  1356. return PyEnumDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1357. }
  1358. static const std::string& GetItemName(const void* item) {
  1359. return static_cast<ItemDescriptor>(item)->name();
  1360. }
  1361. static int GetItemIndex(const void* item) {
  1362. return static_cast<ItemDescriptor>(item)->index();
  1363. }
  1364. static DescriptorContainerDef ContainerDef = {
  1365. "FileEnums",
  1366. Count,
  1367. GetByIndex,
  1368. GetByName,
  1369. NULL,
  1370. NULL,
  1371. NewObjectFromItem,
  1372. GetItemName,
  1373. NULL,
  1374. NULL,
  1375. GetItemIndex,
  1376. };
  1377. } // namespace enums
  1378. PyObject* NewFileEnumTypesByName(ParentDescriptor descriptor) {
  1379. return descriptor::NewMappingByName(&enums::ContainerDef, descriptor);
  1380. }
  1381. namespace extensions {
  1382. typedef const FieldDescriptor* ItemDescriptor;
  1383. static int Count(PyContainer* self) {
  1384. return GetDescriptor(self)->extension_count();
  1385. }
  1386. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  1387. return GetDescriptor(self)->FindExtensionByName(name);
  1388. }
  1389. static const void* GetByIndex(PyContainer* self, int index) {
  1390. return GetDescriptor(self)->extension(index);
  1391. }
  1392. static PyObject* NewObjectFromItem(const void* item) {
  1393. return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1394. }
  1395. static const std::string& GetItemName(const void* item) {
  1396. return static_cast<ItemDescriptor>(item)->name();
  1397. }
  1398. static int GetItemIndex(const void* item) {
  1399. return static_cast<ItemDescriptor>(item)->index();
  1400. }
  1401. static DescriptorContainerDef ContainerDef = {
  1402. "FileExtensions",
  1403. Count,
  1404. GetByIndex,
  1405. GetByName,
  1406. NULL,
  1407. NULL,
  1408. NewObjectFromItem,
  1409. GetItemName,
  1410. NULL,
  1411. NULL,
  1412. GetItemIndex,
  1413. };
  1414. } // namespace extensions
  1415. PyObject* NewFileExtensionsByName(ParentDescriptor descriptor) {
  1416. return descriptor::NewMappingByName(&extensions::ContainerDef, descriptor);
  1417. }
  1418. namespace services {
  1419. typedef const ServiceDescriptor* ItemDescriptor;
  1420. static int Count(PyContainer* self) {
  1421. return GetDescriptor(self)->service_count();
  1422. }
  1423. static const void* GetByName(PyContainer* self, ConstStringParam name) {
  1424. return GetDescriptor(self)->FindServiceByName(name);
  1425. }
  1426. static const void* GetByIndex(PyContainer* self, int index) {
  1427. return GetDescriptor(self)->service(index);
  1428. }
  1429. static PyObject* NewObjectFromItem(const void* item) {
  1430. return PyServiceDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1431. }
  1432. static const std::string& GetItemName(const void* item) {
  1433. return static_cast<ItemDescriptor>(item)->name();
  1434. }
  1435. static int GetItemIndex(const void* item) {
  1436. return static_cast<ItemDescriptor>(item)->index();
  1437. }
  1438. static DescriptorContainerDef ContainerDef = {
  1439. "FileServices",
  1440. Count,
  1441. GetByIndex,
  1442. GetByName,
  1443. NULL,
  1444. NULL,
  1445. NewObjectFromItem,
  1446. GetItemName,
  1447. NULL,
  1448. NULL,
  1449. GetItemIndex,
  1450. };
  1451. } // namespace services
  1452. PyObject* NewFileServicesByName(const FileDescriptor* descriptor) {
  1453. return descriptor::NewMappingByName(&services::ContainerDef, descriptor);
  1454. }
  1455. namespace dependencies {
  1456. typedef const FileDescriptor* ItemDescriptor;
  1457. static int Count(PyContainer* self) {
  1458. return GetDescriptor(self)->dependency_count();
  1459. }
  1460. static const void* GetByIndex(PyContainer* self, int index) {
  1461. return GetDescriptor(self)->dependency(index);
  1462. }
  1463. static PyObject* NewObjectFromItem(const void* item) {
  1464. return PyFileDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1465. }
  1466. static DescriptorContainerDef ContainerDef = {
  1467. "FileDependencies",
  1468. Count,
  1469. GetByIndex,
  1470. NULL,
  1471. NULL,
  1472. NULL,
  1473. NewObjectFromItem,
  1474. NULL,
  1475. NULL,
  1476. NULL,
  1477. NULL,
  1478. };
  1479. } // namespace dependencies
  1480. PyObject* NewFileDependencies(const FileDescriptor* descriptor) {
  1481. return descriptor::NewSequence(&dependencies::ContainerDef, descriptor);
  1482. }
  1483. namespace public_dependencies {
  1484. typedef const FileDescriptor* ItemDescriptor;
  1485. static int Count(PyContainer* self) {
  1486. return GetDescriptor(self)->public_dependency_count();
  1487. }
  1488. static const void* GetByIndex(PyContainer* self, int index) {
  1489. return GetDescriptor(self)->public_dependency(index);
  1490. }
  1491. static PyObject* NewObjectFromItem(const void* item) {
  1492. return PyFileDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
  1493. }
  1494. static DescriptorContainerDef ContainerDef = {
  1495. "FilePublicDependencies",
  1496. Count,
  1497. GetByIndex,
  1498. NULL,
  1499. NULL,
  1500. NULL,
  1501. NewObjectFromItem,
  1502. NULL,
  1503. NULL,
  1504. NULL,
  1505. NULL,
  1506. };
  1507. } // namespace public_dependencies
  1508. PyObject* NewFilePublicDependencies(const FileDescriptor* descriptor) {
  1509. return descriptor::NewSequence(&public_dependencies::ContainerDef,
  1510. descriptor);
  1511. }
  1512. } // namespace file_descriptor
  1513. // Register all implementations
  1514. bool InitDescriptorMappingTypes() {
  1515. if (PyType_Ready(&descriptor::DescriptorMapping_Type) < 0)
  1516. return false;
  1517. if (PyType_Ready(&descriptor::DescriptorSequence_Type) < 0)
  1518. return false;
  1519. if (PyType_Ready(&descriptor::ContainerIterator_Type) < 0)
  1520. return false;
  1521. return true;
  1522. }
  1523. } // namespace python
  1524. } // namespace protobuf
  1525. } // namespace google