aboutsummaryrefslogtreecommitdiff
path: root/python/google/protobuf/pyext/descriptor_containers.cc
blob: bc007f7efa551b1b5430bce6ba05a24f5bea50a1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Mappings and Sequences of descriptors.
// Used by Descriptor.fields_by_name, EnumDescriptor.values...
//
// They avoid the allocation of a full dictionary or a full list: they simply
// store a pointer to the parent descriptor, use the C++ Descriptor methods (see
// google/protobuf/descriptor.h) to retrieve other descriptors, and create
// Python objects on the fly.
//
// The containers fully conform to abc.Mapping and abc.Sequence, and behave just
// like read-only dictionaries and lists.
//
// Because the interface of C++ Descriptors is quite regular, this file actually
// defines only three types, the exact behavior of a container is controlled by
// a DescriptorContainerDef structure, which contains functions that uses the
// public Descriptor API.
//
// Note: This DescriptorContainerDef is similar to the "virtual methods table"
// that a C++ compiler generates for a class. We have to make it explicit
// because the Python API is based on C, and does not play well with C++
// inheritance.

#include <Python.h>

#include <google/protobuf/descriptor.h>
#include <google/protobuf/pyext/descriptor_containers.h>
#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>

#if PY_MAJOR_VERSION >= 3
  #define PyString_FromStringAndSize PyUnicode_FromStringAndSize
  #define PyString_FromFormat PyUnicode_FromFormat
  #define PyInt_FromLong PyLong_FromLong
  #if PY_VERSION_HEX < 0x03030000
    #error "Python 3.0 - 3.2 are not supported."
  #endif
  #define PyString_AsStringAndSize(ob, charpp, sizep) \
    (PyUnicode_Check(ob)? \
       ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
       PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#endif

namespace google {
namespace protobuf {
namespace python {

struct PyContainer;

typedef int (*CountMethod)(PyContainer* self);
typedef const void* (*GetByIndexMethod)(PyContainer* self, int index);
typedef const void* (*GetByNameMethod)(PyContainer* self, const string& name);
typedef const void* (*GetByCamelcaseNameMethod)(PyContainer* self,
                                                const string& name);
typedef const void* (*GetByNumberMethod)(PyContainer* self, int index);
typedef PyObject* (*NewObjectFromItemMethod)(const void* descriptor);
typedef const string& (*GetItemNameMethod)(const void* descriptor);
typedef const string& (*GetItemCamelcaseNameMethod)(const void* descriptor);
typedef int (*GetItemNumberMethod)(const void* descriptor);
typedef int (*GetItemIndexMethod)(const void* descriptor);

struct DescriptorContainerDef {
  const char* mapping_name;
  // Returns the number of items in the container.
  CountMethod count_fn;
  // Retrieve item by index (usually the order of declaration in the proto file)
  // Used by sequences, but also iterators. 0 <= index < Count().
  GetByIndexMethod get_by_index_fn;
  // Retrieve item by name (usually a call to some 'FindByName' method).
  // Used by "by_name" mappings.
  GetByNameMethod get_by_name_fn;
  // Retrieve item by camelcase name (usually a call to some
  // 'FindByCamelcaseName' method). Used by "by_camelcase_name" mappings.
  GetByCamelcaseNameMethod get_by_camelcase_name_fn;
  // Retrieve item by declared number (field tag, or enum value).
  // Used by "by_number" mappings.
  GetByNumberMethod get_by_number_fn;
  // Converts a item C++ descriptor to a Python object. Returns a new reference.
  NewObjectFromItemMethod new_object_from_item_fn;
  // Retrieve the name of an item. Used by iterators on "by_name" mappings.
  GetItemNameMethod get_item_name_fn;
  // Retrieve the camelcase name of an item. Used by iterators on
  // "by_camelcase_name" mappings.
  GetItemCamelcaseNameMethod get_item_camelcase_name_fn;
  // Retrieve the number of an item. Used by iterators on "by_number" mappings.
  GetItemNumberMethod get_item_number_fn;
  // Retrieve the index of an item for the container type.
  // Used by "__contains__".
  // If not set, "x in sequence" will do a linear search.
  GetItemIndexMethod get_item_index_fn;
};

struct PyContainer {
  PyObject_HEAD

  // The proto2 descriptor this container belongs to the global DescriptorPool.
  const void* descriptor;

  // A pointer to a static structure with function pointers that control the
  // behavior of the container. Very similar to the table of virtual functions
  // of a C++ class.
  const DescriptorContainerDef* container_def;

  // The kind of container: list, or dict by name or value.
  enum ContainerKind {
    KIND_SEQUENCE,
    KIND_BYNAME,
    KIND_BYCAMELCASENAME,
    KIND_BYNUMBER,
  } kind;
};

struct PyContainerIterator {
  PyObject_HEAD

  // The container we are iterating over. Own a reference.
  PyContainer* container;

  // The current index in the iterator.
  int index;

  // The kind of container: list, or dict by name or value.
  enum IterKind {
    KIND_ITERKEY,
    KIND_ITERVALUE,
    KIND_ITERITEM,
    KIND_ITERVALUE_REVERSED,  // For sequences
  } kind;
};

namespace descriptor {

// Returns the C++ item descriptor for a given Python key.
// When the descriptor is found, return true and set *item.
// When the descriptor is not found, return true, but set *item to NULL.
// On error, returns false with an exception set.
static bool _GetItemByKey(PyContainer* self, PyObject* key, const void** item) {
  switch (self->kind) {
    case PyContainer::KIND_BYNAME:
      {
        char* name;
        Py_ssize_t name_size;
        if (PyString_AsStringAndSize(key, &name, &name_size) < 0) {
          if (PyErr_ExceptionMatches(PyExc_TypeError)) {
            // Not a string, cannot be in the container.
            PyErr_Clear();
            *item = NULL;
            return true;
          }
          return false;
        }
        *item = self->container_def->get_by_name_fn(
            self, string(name, name_size));
        return true;
      }
    case PyContainer::KIND_BYCAMELCASENAME:
      {
        char* camelcase_name;
        Py_ssize_t name_size;
        if (PyString_AsStringAndSize(key, &camelcase_name, &name_size) < 0) {
          if (PyErr_ExceptionMatches(PyExc_TypeError)) {
            // Not a string, cannot be in the container.
            PyErr_Clear();
            *item = NULL;
            return true;
          }
          return false;
        }
        *item = self->container_def->get_by_camelcase_name_fn(
            self, string(camelcase_name, name_size));
        return true;
      }
    case PyContainer::KIND_BYNUMBER:
      {
        Py_ssize_t number = PyNumber_AsSsize_t(key, NULL);
        if (number == -1 && PyErr_Occurred()) {
          if (PyErr_ExceptionMatches(PyExc_TypeError)) {
            // Not a number, cannot be in the container.
            PyErr_Clear();
            *item = NULL;
            return true;
          }
          return false;
        }
        *item = self->container_def->get_by_number_fn(self, number);
        return true;
      }
    default:
      PyErr_SetNone(PyExc_NotImplementedError);
      return false;
  }
}

// Returns the key of the object at the given index.
// Used when iterating over mappings.
static PyObject* _NewKey_ByIndex(PyContainer* self, Py_ssize_t index) {
  const void* item = self->container_def->get_by_index_fn(self, index);
  switch (self->kind) {
    case PyContainer::KIND_BYNAME:
      {
        const string& name(self->container_def->get_item_name_fn(item));
        return PyString_FromStringAndSize(name.c_str(), name.size());
      }
    case PyContainer::KIND_BYCAMELCASENAME:
      {
        const string& name(
            self->container_def->get_item_camelcase_name_fn(item));
        return PyString_FromStringAndSize(name.c_str(), name.size());
      }
    case PyContainer::KIND_BYNUMBER:
      {
        int value = self->container_def->get_item_number_fn(item);
        return PyInt_FromLong(value);
      }
    default:
      PyErr_SetNone(PyExc_NotImplementedError);
      return NULL;
  }
}

// Returns the object at the given index.
// Also used when iterating over mappings.
static PyObject* _NewObj_ByIndex(PyContainer* self, Py_ssize_t index) {
  return self->container_def->new_object_from_item_fn(
      self->container_def->get_by_index_fn(self, index));
}

static Py_ssize_t Length(PyContainer* self) {
  return self->container_def->count_fn(self);
}

// The DescriptorMapping type.

static PyObject* Subscript(PyContainer* self, PyObject* key) {
  const void* item = NULL;
  if (!_GetItemByKey(self, key, &item)) {
    return NULL;
  }
  if (!item) {
    PyErr_SetObject(PyExc_KeyError, key);
    return NULL;
  }
  return self->container_def->new_object_from_item_fn(item);
}

static int AssSubscript(PyContainer* self, PyObject* key, PyObject* value) {
  if (_CalledFromGeneratedFile(0)) {
    return 0;
  }
  PyErr_Format(PyExc_TypeError,
               "'%.200s' object does not support item assignment",
               Py_TYPE(self)->tp_name);
  return -1;
}

static PyMappingMethods MappingMappingMethods = {
  (lenfunc)Length,               // mp_length
  (binaryfunc)Subscript,         // mp_subscript
  (objobjargproc)AssSubscript,   // mp_ass_subscript
};

static int Contains(PyContainer* self, PyObject* key) {
  const void* item = NULL;
  if (!_GetItemByKey(self, key, &item)) {
    return -1;
  }
  if (item) {
    return 1;
  } else {
    return 0;
  }
}

static PyObject* ContainerRepr(PyContainer* self) {
  const char* kind = "";
  switch (self->kind) {
    case PyContainer::KIND_SEQUENCE:
      kind = "sequence";
      break;
    case PyContainer::KIND_BYNAME:
      kind = "mapping by name";
      break;
    case PyContainer::KIND_BYCAMELCASENAME:
      kind = "mapping by camelCase name";
      break;
    case PyContainer::KIND_BYNUMBER:
      kind = "mapping by number";
      break;
  }
  return PyString_FromFormat(
      "<%s %s>", self->container_def->mapping_name, kind);
}

extern PyTypeObject DescriptorMapping_Type;
extern PyTypeObject DescriptorSequence_Type;

// A sequence container can only be equal to another sequence container, or (for
// backward compatibility) to a list containing the same items.
// Returns 1 if equal, 0 if unequal, -1 on error.
static int DescriptorSequence_Equal(PyContainer* self, PyObject* other) {
  // Check the identity of C++ pointers.
  if (PyObject_TypeCheck(other, &DescriptorSequence_Type)) {
    PyContainer* other_container = reinterpret_cast<PyContainer*>(other);
    if (self->descriptor == other_container->descriptor &&
        self->container_def == other_container->container_def &&
        self->kind == other_container->kind) {
      return 1;
    } else {
      return 0;
    }
  }

  // If other is a list
  if (PyList_Check(other)) {
    // return list(self) == other
    int size = Length(self);
    if (size != PyList_Size(other)) {
      return false;
    }
    for (int index = 0; index < size; index++) {
      ScopedPyObjectPtr value1(_NewObj_ByIndex(self, index));
      if (value1 == NULL) {
        return -1;
      }
      PyObject* value2 = PyList_GetItem(other, index);
      if (value2 == NULL) {
        return -1;
      }
      int cmp = PyObject_RichCompareBool(value1.get(), value2, Py_EQ);
      if (cmp != 1)  // error or not equal
          return cmp;
    }
    // All items were found and equal
    return 1;
  }

  // Any other object is different.
  return 0;
}

// A mapping container can only be equal to another mapping container, or (for
// backward compatibility) to a dict containing the same items.
// Returns 1 if equal, 0 if unequal, -1 on error.
static int DescriptorMapping_Equal(PyContainer* self, PyObject* other) {
  // Check the identity of C++ pointers.
  if (PyObject_TypeCheck(other, &DescriptorMapping_Type)) {
    PyContainer* other_container = reinterpret_cast<PyContainer*>(other);
    if (self->descriptor == other_container->descriptor &&
        self->container_def == other_container->container_def &&
        self->kind == other_container->kind) {
      return 1;
    } else {
      return 0;
    }
  }

  // If other is a dict
  if (PyDict_Check(other)) {
    // equivalent to dict(self.items()) == other
    int size = Length(self);
    if (size != PyDict_Size(other)) {
      return false;
    }
    for (int index = 0; index < size; index++) {
      ScopedPyObjectPtr key(_NewKey_ByIndex(self, index));
      if (key == NULL) {
        return -1;
      }
      ScopedPyObjectPtr value1(_NewObj_ByIndex(self, index));
      if (value1 == NULL) {
        return -1;
      }
      PyObject* value2 = PyDict_GetItem(other, key.get());
      if (value2 == NULL) {
        // Not found in the other dictionary
        return 0;
      }
      int cmp = PyObject_RichCompareBool(value1.get(), value2, Py_EQ);
      if (cmp != 1)  // error or not equal
          return cmp;
    }
    // All items were found and equal
    return 1;
  }

  // Any other object is different.
  return 0;
}

static PyObject* RichCompare(PyContainer* self, PyObject* other, int opid) {
  if (opid != Py_EQ && opid != Py_NE) {
    Py_INCREF(Py_NotImplemented);
    return Py_NotImplemented;
  }

  int result;

  if (self->kind == PyContainer::KIND_SEQUENCE) {
    result = DescriptorSequence_Equal(self, other);
  } else {
    result = DescriptorMapping_Equal(self, other);
  }
  if (result < 0) {
    return NULL;
  }
  if (result ^ (opid == Py_NE)) {
    Py_RETURN_TRUE;
  } else {
    Py_RETURN_FALSE;
  }
}

static PySequenceMethods MappingSequenceMethods = {
    0,                      // sq_length
    0,                      // sq_concat
    0,                      // sq_repeat
    0,                      // sq_item
    0,                      // sq_slice
    0,                      // sq_ass_item
    0,                      // sq_ass_slice
    (objobjproc)Contains,   // sq_contains
};

static PyObject* Get(PyContainer* self, PyObject* args) {
  PyObject* key;
  PyObject* default_value = Py_None;
  if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &default_value)) {
    return NULL;
  }

  const void* item;
  if (!_GetItemByKey(self, key, &item)) {
    return NULL;
  }
  if (item == NULL) {
    Py_INCREF(default_value);
    return default_value;
  }
  return self->container_def->new_object_from_item_fn(item);
}

static PyObject* Keys(PyContainer* self, PyObject* args) {
  Py_ssize_t count = Length(self);
  ScopedPyObjectPtr list(PyList_New(count));
  if (list == NULL) {
    return NULL;
  }
  for (Py_ssize_t index = 0; index < count; ++index) {
    PyObject* key = _NewKey_ByIndex(self, index);
    if (key == NULL) {
      return NULL;
    }
    PyList_SET_ITEM(list.get(), index, key);
  }
  return list.release();
}

static PyObject* Values(PyContainer* self, PyObject* args) {
  Py_ssize_t count = Length(self);
  ScopedPyObjectPtr list(PyList_New(count));
  if (list == NULL) {
    return NULL;
  }
  for (Py_ssize_t index = 0; index < count; ++index) {
    PyObject* value = _NewObj_ByIndex(self, index);
    if (value == NULL) {
      return NULL;
    }
    PyList_SET_ITEM(list.get(), index, value);
  }
  return list.release();
}

static PyObject* Items(PyContainer* self, PyObject* args) {
  Py_ssize_t count = Length(self);
  ScopedPyObjectPtr list(PyList_New(count));
  if (list == NULL) {
    return NULL;
  }
  for (Py_ssize_t index = 0; index < count; ++index) {
    ScopedPyObjectPtr obj(PyTuple_New(2));
    if (obj == NULL) {
      return NULL;
    }
    PyObject* key = _NewKey_ByIndex(self, index);
    if (key == NULL) {
      return NULL;
    }
    PyTuple_SET_ITEM(obj.get(), 0, key);
    PyObject* value = _NewObj_ByIndex(self, index);
    if (value == NULL) {
      return NULL;
    }
    PyTuple_SET_ITEM(obj.get(), 1, value);
    PyList_SET_ITEM(list.get(), index, obj.release());
  }
  return list.release();
}

static PyObject* NewContainerIterator(PyContainer* mapping,
                                      PyContainerIterator::IterKind kind);

static PyObject* Iter(PyContainer* self) {
  return NewContainerIterator(self, PyContainerIterator::KIND_ITERKEY);
}
static PyObject* IterKeys(PyContainer* self, PyObject* args) {
  return NewContainerIterator(self, PyContainerIterator::KIND_ITERKEY);
}
static PyObject* IterValues(PyContainer* self, PyObject* args) {
  return NewContainerIterator(self, PyContainerIterator::KIND_ITERVALUE);
}
static PyObject* IterItems(PyContainer* self, PyObject* args) {
  return NewContainerIterator(self, PyContainerIterator::KIND_ITERITEM);
}

static PyMethodDef MappingMethods[] = {
  { "get", (PyCFunction)Get, METH_VARARGS, },
  { "keys", (PyCFunction)Keys, METH_NOARGS, },
  { "values", (PyCFunction)Values, METH_NOARGS, },
  { "items", (PyCFunction)Items, METH_NOARGS, },
  { "iterkeys", (PyCFunction)IterKeys, METH_NOARGS, },
  { "itervalues", (PyCFunction)IterValues, METH_NOARGS, },
  { "iteritems", (PyCFunction)IterItems, METH_NOARGS, },
  {NULL}
};

PyTypeObject DescriptorMapping_Type = {
  PyVarObject_HEAD_INIT(&PyType_Type, 0)
  "DescriptorMapping",                  // tp_name
  sizeof(PyContainer),                  // tp_basicsize
  0,                                    // tp_itemsize
  0,                                    // tp_dealloc
  0,                                    // tp_print
  0,                                    // tp_getattr
  0,                                    // tp_setattr
  0,                                    // tp_compare
  (reprfunc)ContainerRepr,              // tp_repr
  0,                                    // tp_as_number
  &MappingSequenceMethods,              // tp_as_sequence
  &MappingMappingMethods,               // tp_as_mapping
  0,                                    // tp_hash
  0,                                    // tp_call
  0,                                    // tp_str
  0,                                    // tp_getattro
  0,                                    // tp_setattro
  0,                                    // tp_as_buffer
  Py_TPFLAGS_DEFAULT,                   // tp_flags
  0,                                    // tp_doc
  0,                                    // tp_traverse
  0,                                    // tp_clear
  (richcmpfunc)RichCompare,             // tp_richcompare
  0,                                    // tp_weaklistoffset
  (getiterfunc)Iter,                    // tp_iter
  0,                                    // tp_iternext
  MappingMethods,                       // tp_methods
  0,                                    // tp_members
  0,                                    // tp_getset
  0,                                    // tp_base
  0,                                    // tp_dict
  0,                                    // tp_descr_get
  0,                                    // tp_descr_set
  0,                                    // tp_dictoffset
  0,                                    // tp_init
  0,                                    // tp_alloc
  0,                                    // tp_new
  0,                                    // tp_free
};

// The DescriptorSequence type.

static PyObject* GetItem(PyContainer* self, Py_ssize_t index) {
  if (index < 0) {
    index += Length(self);
  }
  if (index < 0 || index >= Length(self)) {
    PyErr_SetString(PyExc_IndexError, "index out of range");
    return NULL;
  }
  return _NewObj_ByIndex(self, index);
}

static PyObject *
SeqSubscript(PyContainer* self, PyObject* item) {
  if (PyIndex_Check(item)) {
      Py_ssize_t index;
      index = PyNumber_AsSsize_t(item, PyExc_IndexError);
      if (index == -1 && PyErr_Occurred())
          return NULL;
      return GetItem(self, index);
  }
  // Materialize the list and delegate the operation to it.
  ScopedPyObjectPtr list(PyObject_CallFunctionObjArgs(
      reinterpret_cast<PyObject*>(&PyList_Type), self, NULL));
  if (list == NULL) {
    return NULL;
  }
  return Py_TYPE(list.get())->tp_as_mapping->mp_subscript(list.get(), item);
}

// Returns the position of the item in the sequence, of -1 if not found.
// This function never fails.
int Find(PyContainer* self, PyObject* item) {
  // The item can only be in one position: item.index.
  // Check that self[item.index] == item, it's faster than a linear search.
  //
  // This assumes that sequences are only defined by syntax of the .proto file:
  // a specific item belongs to only one sequence, depending on its position in
  // the .proto file definition.
  const void* descriptor_ptr = PyDescriptor_AsVoidPtr(item);
  if (descriptor_ptr == NULL) {
    // Not a descriptor, it cannot be in the list.
    return -1;
  }
  if (self->container_def->get_item_index_fn) {
    int index = self->container_def->get_item_index_fn(descriptor_ptr);
    if (index < 0 || index >= Length(self)) {
      // This index is not from this collection.
      return -1;
    }
    if (self->container_def->get_by_index_fn(self, index) != descriptor_ptr) {
      // The descriptor at this index is not the same.
      return -1;
    }
    // self[item.index] == item, so return the index.
    return index;
  } else {
    // Fall back to linear search.
    int length = Length(self);
    for (int index=0; index < length; index++) {
      if (self->container_def->get_by_index_fn(self, index) == descriptor_ptr) {
        return index;
      }
    }
    // Not found
    return -1;
  }
}

// Implements list.index(): the position of the item is in the sequence.
static PyObject* Index(PyContainer* self, PyObject* item) {
  int position = Find(self, item);
  if (position < 0) {
    // Not found
    PyErr_SetNone(PyExc_ValueError);
    return NULL;
  } else {
    return PyInt_FromLong(position);
  }
}
// Implements "list.__contains__()": is the object in the sequence.
static int SeqContains(PyContainer* self, PyObject* item) {
  int position = Find(self, item);
  if (position < 0) {
    return 0;
  } else {
    return 1;
  }
}

// Implements list.count(): number of occurrences of the item in the sequence.
// An item can only appear once in a sequence. If it exists, return 1.
static PyObject* Count(PyContainer* self, PyObject* item) {
  int position = Find(self, item);
  if (position < 0) {
    return PyInt_FromLong(0);
  } else {
    return PyInt_FromLong(1);
  }
}

static PyObject* Append(PyContainer* self, PyObject* args) {
  if (_CalledFromGeneratedFile(0)) {
    Py_RETURN_NONE;
  }
  PyErr_Format(PyExc_TypeError,
               "'%.200s' object is not a mutable sequence",
               Py_TYPE(self)->tp_name);
  return NULL;
}

static PyObject* Reversed(PyContainer* self, PyObject* args) {
  return NewContainerIterator(self,
                              PyContainerIterator::KIND_ITERVALUE_REVERSED);
}

static PyMethodDef SeqMethods[] = {
  { "index", (PyCFunction)Index, METH_O, },
  { "count", (PyCFunction)Count, METH_O, },
  { "append", (PyCFunction)Append, METH_O, },
  { "__reversed__", (PyCFunction)Reversed, METH_NOARGS, },
  {NULL}
};

static PySequenceMethods SeqSequenceMethods = {
  (lenfunc)Length,          // sq_length
  0,                        // sq_concat
  0,                        // sq_repeat
  (ssizeargfunc)GetItem,    // sq_item
  0,                        // sq_slice
  0,                        // sq_ass_item
  0,                        // sq_ass_slice
  (objobjproc)SeqContains,  // sq_contains
};

static PyMappingMethods SeqMappingMethods = {
  (lenfunc)Length,           // mp_length
  (binaryfunc)SeqSubscript,  // mp_subscript
  0,                         // mp_ass_subscript
};

PyTypeObject DescriptorSequence_Type = {
  PyVarObject_HEAD_INIT(&PyType_Type, 0)
  "DescriptorSequence",                 // tp_name
  sizeof(PyContainer),                  // tp_basicsize
  0,                                    // tp_itemsize
  0,                                    // tp_dealloc
  0,                                    // tp_print
  0,                                    // tp_getattr
  0,                                    // tp_setattr
  0,                                    // tp_compare
  (reprfunc)ContainerRepr,              // tp_repr
  0,                                    // tp_as_number
  &SeqSequenceMethods,                  // tp_as_sequence
  &SeqMappingMethods,                   // tp_as_mapping
  0,                                    // tp_hash
  0,                                    // tp_call
  0,                                    // tp_str
  0,                                    // tp_getattro
  0,                                    // tp_setattro
  0,                                    // tp_as_buffer
  Py_TPFLAGS_DEFAULT,                   // tp_flags
  0,                                    // tp_doc
  0,                                    // tp_traverse
  0,                                    // tp_clear
  (richcmpfunc)RichCompare,             // tp_richcompare
  0,                                    // tp_weaklistoffset
  0,                                    // tp_iter
  0,                                    // tp_iternext
  SeqMethods,                           // tp_methods
  0,                                    // tp_members
  0,                                    // tp_getset
  0,                                    // tp_base
  0,                                    // tp_dict
  0,                                    // tp_descr_get
  0,                                    // tp_descr_set
  0,                                    // tp_dictoffset
  0,                                    // tp_init
  0,                                    // tp_alloc
  0,                                    // tp_new
  0,                                    // tp_free
};

static PyObject* NewMappingByName(
    DescriptorContainerDef* container_def, const void* descriptor) {
  PyContainer* self = PyObject_New(PyContainer, &DescriptorMapping_Type);
  if (self == NULL) {
    return NULL;
  }
  self->descriptor = descriptor;
  self->container_def = container_def;
  self->kind = PyContainer::KIND_BYNAME;
  return reinterpret_cast<PyObject*>(self);
}

static PyObject* NewMappingByCamelcaseName(
    DescriptorContainerDef* container_def, const void* descriptor) {
  PyContainer* self = PyObject_New(PyContainer, &DescriptorMapping_Type);
  if (self == NULL) {
    return NULL;
  }
  self->descriptor = descriptor;
  self->container_def = container_def;
  self->kind = PyContainer::KIND_BYCAMELCASENAME;
  return reinterpret_cast<PyObject*>(self);
}

static PyObject* NewMappingByNumber(
    DescriptorContainerDef* container_def, const void* descriptor) {
  if (container_def->get_by_number_fn == NULL ||
      container_def->get_item_number_fn == NULL) {
    PyErr_SetNone(PyExc_NotImplementedError);
    return NULL;
  }
  PyContainer* self = PyObject_New(PyContainer, &DescriptorMapping_Type);
  if (self == NULL) {
    return NULL;
  }
  self->descriptor = descriptor;
  self->container_def = container_def;
  self->kind = PyContainer::KIND_BYNUMBER;
  return reinterpret_cast<PyObject*>(self);
}

static PyObject* NewSequence(
    DescriptorContainerDef* container_def, const void* descriptor) {
  PyContainer* self = PyObject_New(PyContainer, &DescriptorSequence_Type);
  if (self == NULL) {
    return NULL;
  }
  self->descriptor = descriptor;
  self->container_def = container_def;
  self->kind = PyContainer::KIND_SEQUENCE;
  return reinterpret_cast<PyObject*>(self);
}

// Implement iterators over PyContainers.

static void Iterator_Dealloc(PyContainerIterator* self) {
  Py_CLEAR(self->container);
  Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}

static PyObject* Iterator_Next(PyContainerIterator* self) {
  int count = self->container->container_def->count_fn(self->container);
  if (self->index >= count) {
    // Return NULL with no exception to indicate the end.
    return NULL;
  }
  int index = self->index;
  self->index += 1;
  switch (self->kind) {
    case PyContainerIterator::KIND_ITERKEY:
      return _NewKey_ByIndex(self->container, index);
    case PyContainerIterator::KIND_ITERVALUE:
      return _NewObj_ByIndex(self->container, index);
    case PyContainerIterator::KIND_ITERVALUE_REVERSED:
      return _NewObj_ByIndex(self->container, count - index - 1);
    case PyContainerIterator::KIND_ITERITEM:
      {
        PyObject* obj = PyTuple_New(2);
        if (obj == NULL) {
          return NULL;
        }
        PyObject* key = _NewKey_ByIndex(self->container, index);
        if (key == NULL) {
          Py_DECREF(obj);
          return NULL;
        }
        PyTuple_SET_ITEM(obj, 0, key);
        PyObject* value = _NewObj_ByIndex(self->container, index);
        if (value == NULL) {
          Py_DECREF(obj);
          return NULL;
        }
        PyTuple_SET_ITEM(obj, 1, value);
        return obj;
      }
    default:
      PyErr_SetNone(PyExc_NotImplementedError);
      return NULL;
  }
}

static PyTypeObject ContainerIterator_Type = {
  PyVarObject_HEAD_INIT(&PyType_Type, 0)
  "DescriptorContainerIterator",        // tp_name
  sizeof(PyContainerIterator),          // tp_basicsize
  0,                                    // tp_itemsize
  (destructor)Iterator_Dealloc,         // tp_dealloc
  0,                                    // tp_print
  0,                                    // tp_getattr
  0,                                    // tp_setattr
  0,                                    // tp_compare
  0,                                    // tp_repr
  0,                                    // tp_as_number
  0,                                    // tp_as_sequence
  0,                                    // tp_as_mapping
  0,                                    // tp_hash
  0,                                    // tp_call
  0,                                    // tp_str
  0,                                    // tp_getattro
  0,                                    // tp_setattro
  0,                                    // tp_as_buffer
  Py_TPFLAGS_DEFAULT,                   // tp_flags
  0,                                    // tp_doc
  0,                                    // tp_traverse
  0,                                    // tp_clear
  0,                                    // tp_richcompare
  0,                                    // tp_weaklistoffset
  PyObject_SelfIter,                    // tp_iter
  (iternextfunc)Iterator_Next,          // tp_iternext
  0,                                    // tp_methods
  0,                                    // tp_members
  0,                                    // tp_getset
  0,                                    // tp_base
  0,                                    // tp_dict
  0,                                    // tp_descr_get
  0,                                    // tp_descr_set
  0,                                    // tp_dictoffset
  0,                                    // tp_init
  0,                                    // tp_alloc
  0,                                    // tp_new
  0,                                    // tp_free
};

static PyObject* NewContainerIterator(PyContainer* container,
                                      PyContainerIterator::IterKind kind) {
  PyContainerIterator* self = PyObject_New(PyContainerIterator,
                                           &ContainerIterator_Type);
  if (self == NULL) {
    return NULL;
  }
  Py_INCREF(container);
  self->container = container;
  self->kind = kind;
  self->index = 0;

  return reinterpret_cast<PyObject*>(self);
}

}  // namespace descriptor

// Now define the real collections!

namespace message_descriptor {

typedef const Descriptor* ParentDescriptor;

static ParentDescriptor GetDescriptor(PyContainer* self) {
  return reinterpret_cast<ParentDescriptor>(self->descriptor);
}

namespace fields {

typedef const FieldDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->field_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindFieldByName(name);
}

static const void* GetByCamelcaseName(PyContainer* self,
                                         const string& name) {
  return GetDescriptor(self)->FindFieldByCamelcaseName(name);
}

static const void* GetByNumber(PyContainer* self, int number) {
  return GetDescriptor(self)->FindFieldByNumber(number);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->field(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static const string& GetItemCamelcaseName(const void* item) {
  return static_cast<ItemDescriptor>(item)->camelcase_name();
}

static int GetItemNumber(const void* item) {
  return static_cast<ItemDescriptor>(item)->number();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "MessageFields",
  Count,
  GetByIndex,
  GetByName,
  GetByCamelcaseName,
  GetByNumber,
  NewObjectFromItem,
  GetItemName,
  GetItemCamelcaseName,
  GetItemNumber,
  GetItemIndex,
};

}  // namespace fields

PyObject* NewMessageFieldsByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&fields::ContainerDef, descriptor);
}

PyObject* NewMessageFieldsByCamelcaseName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByCamelcaseName(&fields::ContainerDef,
                                               descriptor);
}

PyObject* NewMessageFieldsByNumber(ParentDescriptor descriptor) {
  return descriptor::NewMappingByNumber(&fields::ContainerDef, descriptor);
}

PyObject* NewMessageFieldsSeq(ParentDescriptor descriptor) {
  return descriptor::NewSequence(&fields::ContainerDef, descriptor);
}

namespace nested_types {

typedef const Descriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->nested_type_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindNestedTypeByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->nested_type(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyMessageDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "MessageNestedTypes",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace nested_types

PyObject* NewMessageNestedTypesSeq(ParentDescriptor descriptor) {
  return descriptor::NewSequence(&nested_types::ContainerDef, descriptor);
}

PyObject* NewMessageNestedTypesByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&nested_types::ContainerDef, descriptor);
}

namespace enums {

typedef const EnumDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->enum_type_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindEnumTypeByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->enum_type(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyEnumDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "MessageNestedEnums",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace enums

PyObject* NewMessageEnumsByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&enums::ContainerDef, descriptor);
}

PyObject* NewMessageEnumsSeq(ParentDescriptor descriptor) {
  return descriptor::NewSequence(&enums::ContainerDef, descriptor);
}

namespace enumvalues {

// This is the "enum_values_by_name" mapping, which collects values from all
// enum types in a message.
//
// Note that the behavior of the C++ descriptor is different: it will search and
// return the first value that matches the name, whereas the Python
// implementation retrieves the last one.

typedef const EnumValueDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  int count = 0;
  for (int i = 0; i < GetDescriptor(self)->enum_type_count(); ++i) {
    count += GetDescriptor(self)->enum_type(i)->value_count();
  }
  return count;
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindEnumValueByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  // This is not optimal, but the number of enums *types* in a given message
  // is small.  This function is only used when iterating over the mapping.
  const EnumDescriptor* enum_type = NULL;
  int enum_type_count = GetDescriptor(self)->enum_type_count();
  for (int i = 0; i < enum_type_count; ++i) {
    enum_type = GetDescriptor(self)->enum_type(i);
    int enum_value_count = enum_type->value_count();
    if (index < enum_value_count) {
      // Found it!
      break;
    }
    index -= enum_value_count;
  }
  // The next statement cannot overflow, because this function is only called by
  // internal iterators which ensure that 0 <= index < Count().
  return enum_type->value(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyEnumValueDescriptor_FromDescriptor(
      static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static DescriptorContainerDef ContainerDef = {
  "MessageEnumValues",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  NULL,
};

}  // namespace enumvalues

PyObject* NewMessageEnumValuesByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&enumvalues::ContainerDef, descriptor);
}

namespace extensions {

typedef const FieldDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->extension_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindExtensionByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->extension(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "MessageExtensions",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace extensions

PyObject* NewMessageExtensionsByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&extensions::ContainerDef, descriptor);
}

PyObject* NewMessageExtensionsSeq(ParentDescriptor descriptor) {
  return descriptor::NewSequence(&extensions::ContainerDef, descriptor);
}

namespace oneofs {

typedef const OneofDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->oneof_decl_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindOneofByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->oneof_decl(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyOneofDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "MessageOneofs",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace oneofs

PyObject* NewMessageOneofsByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&oneofs::ContainerDef, descriptor);
}

PyObject* NewMessageOneofsSeq(ParentDescriptor descriptor) {
  return descriptor::NewSequence(&oneofs::ContainerDef, descriptor);
}

}  // namespace message_descriptor

namespace enum_descriptor {

typedef const EnumDescriptor* ParentDescriptor;

static ParentDescriptor GetDescriptor(PyContainer* self) {
  return reinterpret_cast<ParentDescriptor>(self->descriptor);
}

namespace enumvalues {

typedef const EnumValueDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->value_count();
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->value(index);
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindValueByName(name);
}

static const void* GetByNumber(PyContainer* self, int number) {
  return GetDescriptor(self)->FindValueByNumber(number);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyEnumValueDescriptor_FromDescriptor(
      static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemNumber(const void* item) {
  return static_cast<ItemDescriptor>(item)->number();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "EnumValues",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  GetByNumber,
  NewObjectFromItem,
  GetItemName,
  NULL,
  GetItemNumber,
  GetItemIndex,
};

}  // namespace enumvalues

PyObject* NewEnumValuesByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&enumvalues::ContainerDef, descriptor);
}

PyObject* NewEnumValuesByNumber(ParentDescriptor descriptor) {
  return descriptor::NewMappingByNumber(&enumvalues::ContainerDef, descriptor);
}

PyObject* NewEnumValuesSeq(ParentDescriptor descriptor) {
  return descriptor::NewSequence(&enumvalues::ContainerDef, descriptor);
}

}  // namespace enum_descriptor

namespace oneof_descriptor {

typedef const OneofDescriptor* ParentDescriptor;

static ParentDescriptor GetDescriptor(PyContainer* self) {
  return reinterpret_cast<ParentDescriptor>(self->descriptor);
}

namespace fields {

typedef const FieldDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->field_count();
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->field(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index_in_oneof();
}

static DescriptorContainerDef ContainerDef = {
  "OneofFields",
  Count,
  GetByIndex,
  NULL,
  NULL,
  NULL,
  NewObjectFromItem,
  NULL,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace fields

PyObject* NewOneofFieldsSeq(ParentDescriptor descriptor) {
  return descriptor::NewSequence(&fields::ContainerDef, descriptor);
}

}  // namespace oneof_descriptor

namespace service_descriptor {

typedef const ServiceDescriptor* ParentDescriptor;

static ParentDescriptor GetDescriptor(PyContainer* self) {
  return reinterpret_cast<ParentDescriptor>(self->descriptor);
}

namespace methods {

typedef const MethodDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->method_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindMethodByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->method(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyMethodDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "ServiceMethods",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace methods

PyObject* NewServiceMethodsSeq(ParentDescriptor descriptor) {
  return descriptor::NewSequence(&methods::ContainerDef, descriptor);
}

PyObject* NewServiceMethodsByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&methods::ContainerDef, descriptor);
}

}  // namespace service_descriptor

namespace file_descriptor {

typedef const FileDescriptor* ParentDescriptor;

static ParentDescriptor GetDescriptor(PyContainer* self) {
  return reinterpret_cast<ParentDescriptor>(self->descriptor);
}

namespace messages {

typedef const Descriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->message_type_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindMessageTypeByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->message_type(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyMessageDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "FileMessages",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace messages

PyObject* NewFileMessageTypesByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&messages::ContainerDef, descriptor);
}

namespace enums {

typedef const EnumDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->enum_type_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindEnumTypeByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->enum_type(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyEnumDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "FileEnums",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace enums

PyObject* NewFileEnumTypesByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&enums::ContainerDef, descriptor);
}

namespace extensions {

typedef const FieldDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->extension_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindExtensionByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->extension(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyFieldDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "FileExtensions",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace extensions

PyObject* NewFileExtensionsByName(ParentDescriptor descriptor) {
  return descriptor::NewMappingByName(&extensions::ContainerDef, descriptor);
}

namespace services {

typedef const ServiceDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->service_count();
}

static const void* GetByName(PyContainer* self, const string& name) {
  return GetDescriptor(self)->FindServiceByName(name);
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->service(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyServiceDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static const string& GetItemName(const void* item) {
  return static_cast<ItemDescriptor>(item)->name();
}

static int GetItemIndex(const void* item) {
  return static_cast<ItemDescriptor>(item)->index();
}

static DescriptorContainerDef ContainerDef = {
  "FileServices",
  Count,
  GetByIndex,
  GetByName,
  NULL,
  NULL,
  NewObjectFromItem,
  GetItemName,
  NULL,
  NULL,
  GetItemIndex,
};

}  // namespace services

PyObject* NewFileServicesByName(const FileDescriptor* descriptor) {
  return descriptor::NewMappingByName(&services::ContainerDef, descriptor);
}

namespace dependencies {

typedef const FileDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->dependency_count();
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->dependency(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyFileDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static DescriptorContainerDef ContainerDef = {
  "FileDependencies",
  Count,
  GetByIndex,
  NULL,
  NULL,
  NULL,
  NewObjectFromItem,
  NULL,
  NULL,
  NULL,
  NULL,
};

}  // namespace dependencies

PyObject* NewFileDependencies(const FileDescriptor* descriptor) {
  return descriptor::NewSequence(&dependencies::ContainerDef, descriptor);
}

namespace public_dependencies {

typedef const FileDescriptor* ItemDescriptor;

static int Count(PyContainer* self) {
  return GetDescriptor(self)->public_dependency_count();
}

static const void* GetByIndex(PyContainer* self, int index) {
  return GetDescriptor(self)->public_dependency(index);
}

static PyObject* NewObjectFromItem(const void* item) {
  return PyFileDescriptor_FromDescriptor(static_cast<ItemDescriptor>(item));
}

static DescriptorContainerDef ContainerDef = {
  "FilePublicDependencies",
  Count,
  GetByIndex,
  NULL,
  NULL,
  NULL,
  NewObjectFromItem,
  NULL,
  NULL,
  NULL,
  NULL,
};

}  // namespace public_dependencies

PyObject* NewFilePublicDependencies(const FileDescriptor* descriptor) {
  return descriptor::NewSequence(&public_dependencies::ContainerDef,
                                 descriptor);
}

}  // namespace file_descriptor


// Register all implementations

bool InitDescriptorMappingTypes() {
  if (PyType_Ready(&descriptor::DescriptorMapping_Type) < 0)
    return false;
  if (PyType_Ready(&descriptor::DescriptorSequence_Type) < 0)
    return false;
  if (PyType_Ready(&descriptor::ContainerIterator_Type) < 0)
    return false;
  return true;
}

}  // namespace python
}  // namespace protobuf
}  // namespace google