map_container.cc 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: haberman@google.com (Josh Haberman)
  31. #include <google/protobuf/pyext/map_container.h>
  32. #include <memory>
  33. #include <google/protobuf/stubs/logging.h>
  34. #include <google/protobuf/stubs/common.h>
  35. #include <google/protobuf/map_field.h>
  36. #include <google/protobuf/map.h>
  37. #include <google/protobuf/message.h>
  38. #include <google/protobuf/pyext/message_factory.h>
  39. #include <google/protobuf/pyext/message.h>
  40. #include <google/protobuf/pyext/repeated_composite_container.h>
  41. #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
  42. #include <google/protobuf/stubs/map_util.h>
  43. #if PY_MAJOR_VERSION >= 3
  44. #define PyInt_FromLong PyLong_FromLong
  45. #define PyInt_FromSize_t PyLong_FromSize_t
  46. #endif
  47. namespace google {
  48. namespace protobuf {
  49. namespace python {
  50. // Functions that need access to map reflection functionality.
  51. // They need to be contained in this class because it is friended.
  52. class MapReflectionFriend {
  53. public:
  54. // Methods that are in common between the map types.
  55. static PyObject* Contains(PyObject* _self, PyObject* key);
  56. static Py_ssize_t Length(PyObject* _self);
  57. static PyObject* GetIterator(PyObject *_self);
  58. static PyObject* IterNext(PyObject* _self);
  59. static PyObject* MergeFrom(PyObject* _self, PyObject* arg);
  60. // Methods that differ between the map types.
  61. static PyObject* ScalarMapGetItem(PyObject* _self, PyObject* key);
  62. static PyObject* MessageMapGetItem(PyObject* _self, PyObject* key);
  63. static int ScalarMapSetItem(PyObject* _self, PyObject* key, PyObject* v);
  64. static int MessageMapSetItem(PyObject* _self, PyObject* key, PyObject* v);
  65. static PyObject* ScalarMapToStr(PyObject* _self);
  66. static PyObject* MessageMapToStr(PyObject* _self);
  67. };
  68. struct MapIterator {
  69. PyObject_HEAD;
  70. std::unique_ptr<::google::protobuf::MapIterator> iter;
  71. // A pointer back to the container, so we can notice changes to the version.
  72. // We own a ref on this.
  73. MapContainer* container;
  74. // We need to keep a ref on the parent Message too, because
  75. // MapIterator::~MapIterator() accesses it. Normally this would be ok because
  76. // the ref on container (above) would guarantee outlive semantics. However in
  77. // the case of ClearField(), the MapContainer points to a different message,
  78. // a copy of the original. But our iterator still points to the original,
  79. // which could now get deleted before us.
  80. //
  81. // To prevent this, we ensure that the Message will always stay alive as long
  82. // as this iterator does. This is solely for the benefit of the MapIterator
  83. // destructor -- we should never actually access the iterator in this state
  84. // except to delete it.
  85. CMessage* parent;
  86. // The version of the map when we took the iterator to it.
  87. //
  88. // We store this so that if the map is modified during iteration we can throw
  89. // an error.
  90. uint64 version;
  91. };
  92. Message* MapContainer::GetMutableMessage() {
  93. cmessage::AssureWritable(parent);
  94. return parent->message;
  95. }
  96. // Consumes a reference on the Python string object.
  97. static bool PyStringToSTL(PyObject* py_string, string* stl_string) {
  98. char *value;
  99. Py_ssize_t value_len;
  100. if (!py_string) {
  101. return false;
  102. }
  103. if (PyBytes_AsStringAndSize(py_string, &value, &value_len) < 0) {
  104. Py_DECREF(py_string);
  105. return false;
  106. } else {
  107. stl_string->assign(value, value_len);
  108. Py_DECREF(py_string);
  109. return true;
  110. }
  111. }
  112. static bool PythonToMapKey(PyObject* obj,
  113. const FieldDescriptor* field_descriptor,
  114. MapKey* key) {
  115. switch (field_descriptor->cpp_type()) {
  116. case FieldDescriptor::CPPTYPE_INT32: {
  117. GOOGLE_CHECK_GET_INT32(obj, value, false);
  118. key->SetInt32Value(value);
  119. break;
  120. }
  121. case FieldDescriptor::CPPTYPE_INT64: {
  122. GOOGLE_CHECK_GET_INT64(obj, value, false);
  123. key->SetInt64Value(value);
  124. break;
  125. }
  126. case FieldDescriptor::CPPTYPE_UINT32: {
  127. GOOGLE_CHECK_GET_UINT32(obj, value, false);
  128. key->SetUInt32Value(value);
  129. break;
  130. }
  131. case FieldDescriptor::CPPTYPE_UINT64: {
  132. GOOGLE_CHECK_GET_UINT64(obj, value, false);
  133. key->SetUInt64Value(value);
  134. break;
  135. }
  136. case FieldDescriptor::CPPTYPE_BOOL: {
  137. GOOGLE_CHECK_GET_BOOL(obj, value, false);
  138. key->SetBoolValue(value);
  139. break;
  140. }
  141. case FieldDescriptor::CPPTYPE_STRING: {
  142. string str;
  143. if (!PyStringToSTL(CheckString(obj, field_descriptor), &str)) {
  144. return false;
  145. }
  146. key->SetStringValue(str);
  147. break;
  148. }
  149. default:
  150. PyErr_Format(
  151. PyExc_SystemError, "Type %d cannot be a map key",
  152. field_descriptor->cpp_type());
  153. return false;
  154. }
  155. return true;
  156. }
  157. static PyObject* MapKeyToPython(const FieldDescriptor* field_descriptor,
  158. const MapKey& key) {
  159. switch (field_descriptor->cpp_type()) {
  160. case FieldDescriptor::CPPTYPE_INT32:
  161. return PyInt_FromLong(key.GetInt32Value());
  162. case FieldDescriptor::CPPTYPE_INT64:
  163. return PyLong_FromLongLong(key.GetInt64Value());
  164. case FieldDescriptor::CPPTYPE_UINT32:
  165. return PyInt_FromSize_t(key.GetUInt32Value());
  166. case FieldDescriptor::CPPTYPE_UINT64:
  167. return PyLong_FromUnsignedLongLong(key.GetUInt64Value());
  168. case FieldDescriptor::CPPTYPE_BOOL:
  169. return PyBool_FromLong(key.GetBoolValue());
  170. case FieldDescriptor::CPPTYPE_STRING:
  171. return ToStringObject(field_descriptor, key.GetStringValue());
  172. default:
  173. PyErr_Format(
  174. PyExc_SystemError, "Couldn't convert type %d to value",
  175. field_descriptor->cpp_type());
  176. return NULL;
  177. }
  178. }
  179. // This is only used for ScalarMap, so we don't need to handle the
  180. // CPPTYPE_MESSAGE case.
  181. PyObject* MapValueRefToPython(const FieldDescriptor* field_descriptor,
  182. const MapValueRef& value) {
  183. switch (field_descriptor->cpp_type()) {
  184. case FieldDescriptor::CPPTYPE_INT32:
  185. return PyInt_FromLong(value.GetInt32Value());
  186. case FieldDescriptor::CPPTYPE_INT64:
  187. return PyLong_FromLongLong(value.GetInt64Value());
  188. case FieldDescriptor::CPPTYPE_UINT32:
  189. return PyInt_FromSize_t(value.GetUInt32Value());
  190. case FieldDescriptor::CPPTYPE_UINT64:
  191. return PyLong_FromUnsignedLongLong(value.GetUInt64Value());
  192. case FieldDescriptor::CPPTYPE_FLOAT:
  193. return PyFloat_FromDouble(value.GetFloatValue());
  194. case FieldDescriptor::CPPTYPE_DOUBLE:
  195. return PyFloat_FromDouble(value.GetDoubleValue());
  196. case FieldDescriptor::CPPTYPE_BOOL:
  197. return PyBool_FromLong(value.GetBoolValue());
  198. case FieldDescriptor::CPPTYPE_STRING:
  199. return ToStringObject(field_descriptor, value.GetStringValue());
  200. case FieldDescriptor::CPPTYPE_ENUM:
  201. return PyInt_FromLong(value.GetEnumValue());
  202. default:
  203. PyErr_Format(
  204. PyExc_SystemError, "Couldn't convert type %d to value",
  205. field_descriptor->cpp_type());
  206. return NULL;
  207. }
  208. }
  209. // This is only used for ScalarMap, so we don't need to handle the
  210. // CPPTYPE_MESSAGE case.
  211. static bool PythonToMapValueRef(PyObject* obj,
  212. const FieldDescriptor* field_descriptor,
  213. bool allow_unknown_enum_values,
  214. MapValueRef* value_ref) {
  215. switch (field_descriptor->cpp_type()) {
  216. case FieldDescriptor::CPPTYPE_INT32: {
  217. GOOGLE_CHECK_GET_INT32(obj, value, false);
  218. value_ref->SetInt32Value(value);
  219. return true;
  220. }
  221. case FieldDescriptor::CPPTYPE_INT64: {
  222. GOOGLE_CHECK_GET_INT64(obj, value, false);
  223. value_ref->SetInt64Value(value);
  224. return true;
  225. }
  226. case FieldDescriptor::CPPTYPE_UINT32: {
  227. GOOGLE_CHECK_GET_UINT32(obj, value, false);
  228. value_ref->SetUInt32Value(value);
  229. return true;
  230. }
  231. case FieldDescriptor::CPPTYPE_UINT64: {
  232. GOOGLE_CHECK_GET_UINT64(obj, value, false);
  233. value_ref->SetUInt64Value(value);
  234. return true;
  235. }
  236. case FieldDescriptor::CPPTYPE_FLOAT: {
  237. GOOGLE_CHECK_GET_FLOAT(obj, value, false);
  238. value_ref->SetFloatValue(value);
  239. return true;
  240. }
  241. case FieldDescriptor::CPPTYPE_DOUBLE: {
  242. GOOGLE_CHECK_GET_DOUBLE(obj, value, false);
  243. value_ref->SetDoubleValue(value);
  244. return true;
  245. }
  246. case FieldDescriptor::CPPTYPE_BOOL: {
  247. GOOGLE_CHECK_GET_BOOL(obj, value, false);
  248. value_ref->SetBoolValue(value);
  249. return true;;
  250. }
  251. case FieldDescriptor::CPPTYPE_STRING: {
  252. string str;
  253. if (!PyStringToSTL(CheckString(obj, field_descriptor), &str)) {
  254. return false;
  255. }
  256. value_ref->SetStringValue(str);
  257. return true;
  258. }
  259. case FieldDescriptor::CPPTYPE_ENUM: {
  260. GOOGLE_CHECK_GET_INT32(obj, value, false);
  261. if (allow_unknown_enum_values) {
  262. value_ref->SetEnumValue(value);
  263. return true;
  264. } else {
  265. const EnumDescriptor* enum_descriptor = field_descriptor->enum_type();
  266. const EnumValueDescriptor* enum_value =
  267. enum_descriptor->FindValueByNumber(value);
  268. if (enum_value != NULL) {
  269. value_ref->SetEnumValue(value);
  270. return true;
  271. } else {
  272. PyErr_Format(PyExc_ValueError, "Unknown enum value: %d", value);
  273. return false;
  274. }
  275. }
  276. break;
  277. }
  278. default:
  279. PyErr_Format(
  280. PyExc_SystemError, "Setting value to a field of unknown type %d",
  281. field_descriptor->cpp_type());
  282. return false;
  283. }
  284. }
  285. // Map methods common to ScalarMap and MessageMap //////////////////////////////
  286. static MapContainer* GetMap(PyObject* obj) {
  287. return reinterpret_cast<MapContainer*>(obj);
  288. }
  289. Py_ssize_t MapReflectionFriend::Length(PyObject* _self) {
  290. MapContainer* self = GetMap(_self);
  291. const google::protobuf::Message* message = self->parent->message;
  292. return message->GetReflection()->MapSize(*message,
  293. self->parent_field_descriptor);
  294. }
  295. PyObject* Clear(PyObject* _self) {
  296. MapContainer* self = GetMap(_self);
  297. Message* message = self->GetMutableMessage();
  298. const Reflection* reflection = message->GetReflection();
  299. reflection->ClearField(message, self->parent_field_descriptor);
  300. Py_RETURN_NONE;
  301. }
  302. PyObject* GetEntryClass(PyObject* _self) {
  303. MapContainer* self = GetMap(_self);
  304. CMessageClass* message_class = message_factory::GetMessageClass(
  305. cmessage::GetFactoryForMessage(self->parent),
  306. self->parent_field_descriptor->message_type());
  307. Py_XINCREF(message_class);
  308. return reinterpret_cast<PyObject*>(message_class);
  309. }
  310. PyObject* MapReflectionFriend::MergeFrom(PyObject* _self, PyObject* arg) {
  311. MapContainer* self = GetMap(_self);
  312. MapContainer* other_map = GetMap(arg);
  313. Message* message = self->GetMutableMessage();
  314. const Message* other_message = other_map->parent->message;
  315. const Reflection* reflection = message->GetReflection();
  316. const Reflection* other_reflection = other_message->GetReflection();
  317. internal::MapFieldBase* field = reflection->MutableMapData(
  318. message, self->parent_field_descriptor);
  319. const internal::MapFieldBase* other_field =
  320. other_reflection->GetMapData(*other_message,
  321. self->parent_field_descriptor);
  322. field->MergeFrom(*other_field);
  323. self->version++;
  324. Py_RETURN_NONE;
  325. }
  326. PyObject* MapReflectionFriend::Contains(PyObject* _self, PyObject* key) {
  327. MapContainer* self = GetMap(_self);
  328. const Message* message = self->parent->message;
  329. const Reflection* reflection = message->GetReflection();
  330. MapKey map_key;
  331. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  332. return NULL;
  333. }
  334. if (reflection->ContainsMapKey(*message, self->parent_field_descriptor,
  335. map_key)) {
  336. Py_RETURN_TRUE;
  337. } else {
  338. Py_RETURN_FALSE;
  339. }
  340. }
  341. // ScalarMap ///////////////////////////////////////////////////////////////////
  342. MapContainer* NewScalarMapContainer(
  343. CMessage* parent, const google::protobuf::FieldDescriptor* parent_field_descriptor) {
  344. if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) {
  345. return NULL;
  346. }
  347. PyObject* obj(PyType_GenericAlloc(ScalarMapContainer_Type, 0));
  348. if (obj == NULL) {
  349. PyErr_Format(PyExc_RuntimeError,
  350. "Could not allocate new container.");
  351. return NULL;
  352. }
  353. MapContainer* self = GetMap(obj);
  354. Py_INCREF(parent);
  355. self->parent = parent;
  356. self->parent_field_descriptor = parent_field_descriptor;
  357. self->version = 0;
  358. self->key_field_descriptor =
  359. parent_field_descriptor->message_type()->FindFieldByName("key");
  360. self->value_field_descriptor =
  361. parent_field_descriptor->message_type()->FindFieldByName("value");
  362. if (self->key_field_descriptor == NULL ||
  363. self->value_field_descriptor == NULL) {
  364. PyErr_Format(PyExc_KeyError,
  365. "Map entry descriptor did not have key/value fields");
  366. return NULL;
  367. }
  368. return self;
  369. }
  370. PyObject* MapReflectionFriend::ScalarMapGetItem(PyObject* _self,
  371. PyObject* key) {
  372. MapContainer* self = GetMap(_self);
  373. Message* message = self->GetMutableMessage();
  374. const Reflection* reflection = message->GetReflection();
  375. MapKey map_key;
  376. MapValueRef value;
  377. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  378. return NULL;
  379. }
  380. if (reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
  381. map_key, &value)) {
  382. self->version++;
  383. }
  384. return MapValueRefToPython(self->value_field_descriptor, value);
  385. }
  386. int MapReflectionFriend::ScalarMapSetItem(PyObject* _self, PyObject* key,
  387. PyObject* v) {
  388. MapContainer* self = GetMap(_self);
  389. Message* message = self->GetMutableMessage();
  390. const Reflection* reflection = message->GetReflection();
  391. MapKey map_key;
  392. MapValueRef value;
  393. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  394. return -1;
  395. }
  396. self->version++;
  397. if (v) {
  398. // Set item to v.
  399. reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
  400. map_key, &value);
  401. return PythonToMapValueRef(v, self->value_field_descriptor,
  402. reflection->SupportsUnknownEnumValues(), &value)
  403. ? 0
  404. : -1;
  405. } else {
  406. // Delete key from map.
  407. if (reflection->DeleteMapValue(message, self->parent_field_descriptor,
  408. map_key)) {
  409. return 0;
  410. } else {
  411. PyErr_Format(PyExc_KeyError, "Key not present in map");
  412. return -1;
  413. }
  414. }
  415. }
  416. static PyObject* ScalarMapGet(PyObject* self, PyObject* args,
  417. PyObject* kwargs) {
  418. static char* kwlist[] = {"key", "default", nullptr};
  419. PyObject* key;
  420. PyObject* default_value = NULL;
  421. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &key,
  422. &default_value)) {
  423. return NULL;
  424. }
  425. ScopedPyObjectPtr is_present(MapReflectionFriend::Contains(self, key));
  426. if (is_present.get() == NULL) {
  427. return NULL;
  428. }
  429. if (PyObject_IsTrue(is_present.get())) {
  430. return MapReflectionFriend::ScalarMapGetItem(self, key);
  431. } else {
  432. if (default_value != NULL) {
  433. Py_INCREF(default_value);
  434. return default_value;
  435. } else {
  436. Py_RETURN_NONE;
  437. }
  438. }
  439. }
  440. PyObject* MapReflectionFriend::ScalarMapToStr(PyObject* _self) {
  441. ScopedPyObjectPtr dict(PyDict_New());
  442. if (dict == NULL) {
  443. return NULL;
  444. }
  445. ScopedPyObjectPtr key;
  446. ScopedPyObjectPtr value;
  447. MapContainer* self = GetMap(_self);
  448. Message* message = self->GetMutableMessage();
  449. const Reflection* reflection = message->GetReflection();
  450. for (google::protobuf::MapIterator it = reflection->MapBegin(
  451. message, self->parent_field_descriptor);
  452. it != reflection->MapEnd(message, self->parent_field_descriptor);
  453. ++it) {
  454. key.reset(MapKeyToPython(self->key_field_descriptor,
  455. it.GetKey()));
  456. if (key == NULL) {
  457. return NULL;
  458. }
  459. value.reset(MapValueRefToPython(self->value_field_descriptor,
  460. it.GetValueRef()));
  461. if (value == NULL) {
  462. return NULL;
  463. }
  464. if (PyDict_SetItem(dict.get(), key.get(), value.get()) < 0) {
  465. return NULL;
  466. }
  467. }
  468. return PyObject_Repr(dict.get());
  469. }
  470. static void ScalarMapDealloc(PyObject* _self) {
  471. MapContainer* self = GetMap(_self);
  472. self->RemoveFromParentCache();
  473. PyTypeObject *type = Py_TYPE(_self);
  474. type->tp_free(_self);
  475. if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
  476. // With Python3, the Map class is not static, and must be managed.
  477. Py_DECREF(type);
  478. }
  479. }
  480. static PyMethodDef ScalarMapMethods[] = {
  481. {"__contains__", MapReflectionFriend::Contains, METH_O,
  482. "Tests whether a key is a member of the map."},
  483. {"clear", (PyCFunction)Clear, METH_NOARGS,
  484. "Removes all elements from the map."},
  485. {"get", (PyCFunction)ScalarMapGet, METH_VARARGS | METH_KEYWORDS,
  486. "Gets the value for the given key if present, or otherwise a default"},
  487. {"GetEntryClass", (PyCFunction)GetEntryClass, METH_NOARGS,
  488. "Return the class used to build Entries of (key, value) pairs."},
  489. {"MergeFrom", (PyCFunction)MapReflectionFriend::MergeFrom, METH_O,
  490. "Merges a map into the current map."},
  491. /*
  492. { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
  493. "Makes a deep copy of the class." },
  494. { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
  495. "Outputs picklable representation of the repeated field." },
  496. */
  497. {NULL, NULL},
  498. };
  499. PyTypeObject *ScalarMapContainer_Type;
  500. #if PY_MAJOR_VERSION >= 3
  501. static PyType_Slot ScalarMapContainer_Type_slots[] = {
  502. {Py_tp_dealloc, (void *)ScalarMapDealloc},
  503. {Py_mp_length, (void *)MapReflectionFriend::Length},
  504. {Py_mp_subscript, (void *)MapReflectionFriend::ScalarMapGetItem},
  505. {Py_mp_ass_subscript, (void *)MapReflectionFriend::ScalarMapSetItem},
  506. {Py_tp_methods, (void *)ScalarMapMethods},
  507. {Py_tp_iter, (void *)MapReflectionFriend::GetIterator},
  508. {Py_tp_repr, (void *)MapReflectionFriend::ScalarMapToStr},
  509. {0, 0},
  510. };
  511. PyType_Spec ScalarMapContainer_Type_spec = {
  512. FULL_MODULE_NAME ".ScalarMapContainer",
  513. sizeof(MapContainer),
  514. 0,
  515. Py_TPFLAGS_DEFAULT,
  516. ScalarMapContainer_Type_slots
  517. };
  518. #else
  519. static PyMappingMethods ScalarMapMappingMethods = {
  520. MapReflectionFriend::Length, // mp_length
  521. MapReflectionFriend::ScalarMapGetItem, // mp_subscript
  522. MapReflectionFriend::ScalarMapSetItem, // mp_ass_subscript
  523. };
  524. PyTypeObject _ScalarMapContainer_Type = {
  525. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  526. FULL_MODULE_NAME ".ScalarMapContainer", // tp_name
  527. sizeof(MapContainer), // tp_basicsize
  528. 0, // tp_itemsize
  529. ScalarMapDealloc, // tp_dealloc
  530. 0, // tp_print
  531. 0, // tp_getattr
  532. 0, // tp_setattr
  533. 0, // tp_compare
  534. MapReflectionFriend::ScalarMapToStr, // tp_repr
  535. 0, // tp_as_number
  536. 0, // tp_as_sequence
  537. &ScalarMapMappingMethods, // tp_as_mapping
  538. 0, // tp_hash
  539. 0, // tp_call
  540. 0, // tp_str
  541. 0, // tp_getattro
  542. 0, // tp_setattro
  543. 0, // tp_as_buffer
  544. Py_TPFLAGS_DEFAULT, // tp_flags
  545. "A scalar map container", // tp_doc
  546. 0, // tp_traverse
  547. 0, // tp_clear
  548. 0, // tp_richcompare
  549. 0, // tp_weaklistoffset
  550. MapReflectionFriend::GetIterator, // tp_iter
  551. 0, // tp_iternext
  552. ScalarMapMethods, // tp_methods
  553. 0, // tp_members
  554. 0, // tp_getset
  555. 0, // tp_base
  556. 0, // tp_dict
  557. 0, // tp_descr_get
  558. 0, // tp_descr_set
  559. 0, // tp_dictoffset
  560. 0, // tp_init
  561. };
  562. #endif
  563. // MessageMap //////////////////////////////////////////////////////////////////
  564. static MessageMapContainer* GetMessageMap(PyObject* obj) {
  565. return reinterpret_cast<MessageMapContainer*>(obj);
  566. }
  567. static PyObject* GetCMessage(MessageMapContainer* self, Message* message) {
  568. // Get or create the CMessage object corresponding to this message.
  569. return self->parent
  570. ->BuildSubMessageFromPointer(self->parent_field_descriptor, message,
  571. self->message_class)
  572. ->AsPyObject();
  573. }
  574. MessageMapContainer* NewMessageMapContainer(
  575. CMessage* parent, const google::protobuf::FieldDescriptor* parent_field_descriptor,
  576. CMessageClass* message_class) {
  577. if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) {
  578. return NULL;
  579. }
  580. PyObject* obj = PyType_GenericAlloc(MessageMapContainer_Type, 0);
  581. if (obj == NULL) {
  582. PyErr_SetString(PyExc_RuntimeError, "Could not allocate new container.");
  583. return NULL;
  584. }
  585. MessageMapContainer* self = GetMessageMap(obj);
  586. Py_INCREF(parent);
  587. self->parent = parent;
  588. self->parent_field_descriptor = parent_field_descriptor;
  589. self->version = 0;
  590. self->key_field_descriptor =
  591. parent_field_descriptor->message_type()->FindFieldByName("key");
  592. self->value_field_descriptor =
  593. parent_field_descriptor->message_type()->FindFieldByName("value");
  594. Py_INCREF(message_class);
  595. self->message_class = message_class;
  596. if (self->key_field_descriptor == NULL ||
  597. self->value_field_descriptor == NULL) {
  598. Py_DECREF(self);
  599. PyErr_SetString(PyExc_KeyError,
  600. "Map entry descriptor did not have key/value fields");
  601. return NULL;
  602. }
  603. return self;
  604. }
  605. int MapReflectionFriend::MessageMapSetItem(PyObject* _self, PyObject* key,
  606. PyObject* v) {
  607. if (v) {
  608. PyErr_Format(PyExc_ValueError,
  609. "Direct assignment of submessage not allowed");
  610. return -1;
  611. }
  612. // Now we know that this is a delete, not a set.
  613. MessageMapContainer* self = GetMessageMap(_self);
  614. Message* message = self->GetMutableMessage();
  615. const Reflection* reflection = message->GetReflection();
  616. MapKey map_key;
  617. MapValueRef value;
  618. self->version++;
  619. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  620. return -1;
  621. }
  622. // Delete key from map.
  623. if (reflection->ContainsMapKey(*message, self->parent_field_descriptor,
  624. map_key)) {
  625. // Delete key from CMessage dict.
  626. MapValueRef value;
  627. reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
  628. map_key, &value);
  629. Message* sub_message = value.MutableMessageValue();
  630. // If there is a living weak reference to an item, we "Release" it,
  631. // otherwise we just discard the C++ value.
  632. if (CMessage* released =
  633. self->parent->MaybeReleaseSubMessage(sub_message)) {
  634. Message* msg = released->message;
  635. released->message = msg->New();
  636. msg->GetReflection()->Swap(msg, released->message);
  637. }
  638. // Delete key from map.
  639. reflection->DeleteMapValue(message, self->parent_field_descriptor,
  640. map_key);
  641. return 0;
  642. } else {
  643. PyErr_Format(PyExc_KeyError, "Key not present in map");
  644. return -1;
  645. }
  646. }
  647. PyObject* MapReflectionFriend::MessageMapGetItem(PyObject* _self,
  648. PyObject* key) {
  649. MessageMapContainer* self = GetMessageMap(_self);
  650. Message* message = self->GetMutableMessage();
  651. const Reflection* reflection = message->GetReflection();
  652. MapKey map_key;
  653. MapValueRef value;
  654. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  655. return NULL;
  656. }
  657. if (reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
  658. map_key, &value)) {
  659. self->version++;
  660. }
  661. return GetCMessage(self, value.MutableMessageValue());
  662. }
  663. PyObject* MapReflectionFriend::MessageMapToStr(PyObject* _self) {
  664. ScopedPyObjectPtr dict(PyDict_New());
  665. if (dict == NULL) {
  666. return NULL;
  667. }
  668. ScopedPyObjectPtr key;
  669. ScopedPyObjectPtr value;
  670. MessageMapContainer* self = GetMessageMap(_self);
  671. Message* message = self->GetMutableMessage();
  672. const Reflection* reflection = message->GetReflection();
  673. for (google::protobuf::MapIterator it = reflection->MapBegin(
  674. message, self->parent_field_descriptor);
  675. it != reflection->MapEnd(message, self->parent_field_descriptor);
  676. ++it) {
  677. key.reset(MapKeyToPython(self->key_field_descriptor,
  678. it.GetKey()));
  679. if (key == NULL) {
  680. return NULL;
  681. }
  682. value.reset(GetCMessage(self, it.MutableValueRef()->MutableMessageValue()));
  683. if (value == NULL) {
  684. return NULL;
  685. }
  686. if (PyDict_SetItem(dict.get(), key.get(), value.get()) < 0) {
  687. return NULL;
  688. }
  689. }
  690. return PyObject_Repr(dict.get());
  691. }
  692. PyObject* MessageMapGet(PyObject* self, PyObject* args, PyObject* kwargs) {
  693. static char* kwlist[] = {"key", "default", nullptr};
  694. PyObject* key;
  695. PyObject* default_value = NULL;
  696. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &key,
  697. &default_value)) {
  698. return NULL;
  699. }
  700. ScopedPyObjectPtr is_present(MapReflectionFriend::Contains(self, key));
  701. if (is_present.get() == NULL) {
  702. return NULL;
  703. }
  704. if (PyObject_IsTrue(is_present.get())) {
  705. return MapReflectionFriend::MessageMapGetItem(self, key);
  706. } else {
  707. if (default_value != NULL) {
  708. Py_INCREF(default_value);
  709. return default_value;
  710. } else {
  711. Py_RETURN_NONE;
  712. }
  713. }
  714. }
  715. static void MessageMapDealloc(PyObject* _self) {
  716. MessageMapContainer* self = GetMessageMap(_self);
  717. self->RemoveFromParentCache();
  718. Py_DECREF(self->message_class);
  719. PyTypeObject *type = Py_TYPE(_self);
  720. type->tp_free(_self);
  721. if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
  722. // With Python3, the Map class is not static, and must be managed.
  723. Py_DECREF(type);
  724. }
  725. }
  726. static PyMethodDef MessageMapMethods[] = {
  727. {"__contains__", (PyCFunction)MapReflectionFriend::Contains, METH_O,
  728. "Tests whether the map contains this element."},
  729. {"clear", (PyCFunction)Clear, METH_NOARGS,
  730. "Removes all elements from the map."},
  731. {"get", (PyCFunction)MessageMapGet, METH_VARARGS | METH_KEYWORDS,
  732. "Gets the value for the given key if present, or otherwise a default"},
  733. {"get_or_create", MapReflectionFriend::MessageMapGetItem, METH_O,
  734. "Alias for getitem, useful to make explicit that the map is mutated."},
  735. {"GetEntryClass", (PyCFunction)GetEntryClass, METH_NOARGS,
  736. "Return the class used to build Entries of (key, value) pairs."},
  737. {"MergeFrom", (PyCFunction)MapReflectionFriend::MergeFrom, METH_O,
  738. "Merges a map into the current map."},
  739. /*
  740. { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
  741. "Makes a deep copy of the class." },
  742. { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
  743. "Outputs picklable representation of the repeated field." },
  744. */
  745. {NULL, NULL},
  746. };
  747. PyTypeObject *MessageMapContainer_Type;
  748. #if PY_MAJOR_VERSION >= 3
  749. static PyType_Slot MessageMapContainer_Type_slots[] = {
  750. {Py_tp_dealloc, (void *)MessageMapDealloc},
  751. {Py_mp_length, (void *)MapReflectionFriend::Length},
  752. {Py_mp_subscript, (void *)MapReflectionFriend::MessageMapGetItem},
  753. {Py_mp_ass_subscript, (void *)MapReflectionFriend::MessageMapSetItem},
  754. {Py_tp_methods, (void *)MessageMapMethods},
  755. {Py_tp_iter, (void *)MapReflectionFriend::GetIterator},
  756. {Py_tp_repr, (void *)MapReflectionFriend::MessageMapToStr},
  757. {0, 0}
  758. };
  759. PyType_Spec MessageMapContainer_Type_spec = {
  760. FULL_MODULE_NAME ".MessageMapContainer",
  761. sizeof(MessageMapContainer),
  762. 0,
  763. Py_TPFLAGS_DEFAULT,
  764. MessageMapContainer_Type_slots
  765. };
  766. #else
  767. static PyMappingMethods MessageMapMappingMethods = {
  768. MapReflectionFriend::Length, // mp_length
  769. MapReflectionFriend::MessageMapGetItem, // mp_subscript
  770. MapReflectionFriend::MessageMapSetItem, // mp_ass_subscript
  771. };
  772. PyTypeObject _MessageMapContainer_Type = {
  773. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  774. FULL_MODULE_NAME ".MessageMapContainer", // tp_name
  775. sizeof(MessageMapContainer), // tp_basicsize
  776. 0, // tp_itemsize
  777. MessageMapDealloc, // tp_dealloc
  778. 0, // tp_print
  779. 0, // tp_getattr
  780. 0, // tp_setattr
  781. 0, // tp_compare
  782. MapReflectionFriend::MessageMapToStr, // tp_repr
  783. 0, // tp_as_number
  784. 0, // tp_as_sequence
  785. &MessageMapMappingMethods, // tp_as_mapping
  786. 0, // tp_hash
  787. 0, // tp_call
  788. 0, // tp_str
  789. 0, // tp_getattro
  790. 0, // tp_setattro
  791. 0, // tp_as_buffer
  792. Py_TPFLAGS_DEFAULT, // tp_flags
  793. "A map container for message", // tp_doc
  794. 0, // tp_traverse
  795. 0, // tp_clear
  796. 0, // tp_richcompare
  797. 0, // tp_weaklistoffset
  798. MapReflectionFriend::GetIterator, // tp_iter
  799. 0, // tp_iternext
  800. MessageMapMethods, // tp_methods
  801. 0, // tp_members
  802. 0, // tp_getset
  803. 0, // tp_base
  804. 0, // tp_dict
  805. 0, // tp_descr_get
  806. 0, // tp_descr_set
  807. 0, // tp_dictoffset
  808. 0, // tp_init
  809. };
  810. #endif
  811. // MapIterator /////////////////////////////////////////////////////////////////
  812. static MapIterator* GetIter(PyObject* obj) {
  813. return reinterpret_cast<MapIterator*>(obj);
  814. }
  815. PyObject* MapReflectionFriend::GetIterator(PyObject *_self) {
  816. MapContainer* self = GetMap(_self);
  817. ScopedPyObjectPtr obj(PyType_GenericAlloc(&MapIterator_Type, 0));
  818. if (obj == NULL) {
  819. return PyErr_Format(PyExc_KeyError, "Could not allocate iterator");
  820. }
  821. MapIterator* iter = GetIter(obj.get());
  822. Py_INCREF(self);
  823. iter->container = self;
  824. iter->version = self->version;
  825. Py_INCREF(self->parent);
  826. iter->parent = self->parent;
  827. if (MapReflectionFriend::Length(_self) > 0) {
  828. Message* message = self->GetMutableMessage();
  829. const Reflection* reflection = message->GetReflection();
  830. iter->iter.reset(new ::google::protobuf::MapIterator(
  831. reflection->MapBegin(message, self->parent_field_descriptor)));
  832. }
  833. return obj.release();
  834. }
  835. PyObject* MapReflectionFriend::IterNext(PyObject* _self) {
  836. MapIterator* self = GetIter(_self);
  837. // This won't catch mutations to the map performed by MergeFrom(); no easy way
  838. // to address that.
  839. if (self->version != self->container->version) {
  840. return PyErr_Format(PyExc_RuntimeError,
  841. "Map modified during iteration.");
  842. }
  843. if (self->parent != self->container->parent) {
  844. return PyErr_Format(PyExc_RuntimeError,
  845. "Map cleared during iteration.");
  846. }
  847. if (self->iter.get() == NULL) {
  848. return NULL;
  849. }
  850. Message* message = self->container->GetMutableMessage();
  851. const Reflection* reflection = message->GetReflection();
  852. if (*self->iter ==
  853. reflection->MapEnd(message, self->container->parent_field_descriptor)) {
  854. return NULL;
  855. }
  856. PyObject* ret = MapKeyToPython(self->container->key_field_descriptor,
  857. self->iter->GetKey());
  858. ++(*self->iter);
  859. return ret;
  860. }
  861. static void DeallocMapIterator(PyObject* _self) {
  862. MapIterator* self = GetIter(_self);
  863. self->iter.reset();
  864. Py_CLEAR(self->container);
  865. Py_CLEAR(self->parent);
  866. Py_TYPE(_self)->tp_free(_self);
  867. }
  868. PyTypeObject MapIterator_Type = {
  869. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  870. FULL_MODULE_NAME ".MapIterator", // tp_name
  871. sizeof(MapIterator), // tp_basicsize
  872. 0, // tp_itemsize
  873. DeallocMapIterator, // tp_dealloc
  874. 0, // tp_print
  875. 0, // tp_getattr
  876. 0, // tp_setattr
  877. 0, // tp_compare
  878. 0, // tp_repr
  879. 0, // tp_as_number
  880. 0, // tp_as_sequence
  881. 0, // tp_as_mapping
  882. 0, // tp_hash
  883. 0, // tp_call
  884. 0, // tp_str
  885. 0, // tp_getattro
  886. 0, // tp_setattro
  887. 0, // tp_as_buffer
  888. Py_TPFLAGS_DEFAULT, // tp_flags
  889. "A scalar map iterator", // tp_doc
  890. 0, // tp_traverse
  891. 0, // tp_clear
  892. 0, // tp_richcompare
  893. 0, // tp_weaklistoffset
  894. PyObject_SelfIter, // tp_iter
  895. MapReflectionFriend::IterNext, // tp_iternext
  896. 0, // tp_methods
  897. 0, // tp_members
  898. 0, // tp_getset
  899. 0, // tp_base
  900. 0, // tp_dict
  901. 0, // tp_descr_get
  902. 0, // tp_descr_set
  903. 0, // tp_dictoffset
  904. 0, // tp_init
  905. };
  906. bool InitMapContainers() {
  907. // ScalarMapContainer_Type derives from our MutableMapping type.
  908. ScopedPyObjectPtr containers(PyImport_ImportModule(
  909. "google.protobuf.internal.containers"));
  910. if (containers == NULL) {
  911. return false;
  912. }
  913. ScopedPyObjectPtr mutable_mapping(
  914. PyObject_GetAttrString(containers.get(), "MutableMapping"));
  915. if (mutable_mapping == NULL) {
  916. return false;
  917. }
  918. Py_INCREF(mutable_mapping.get());
  919. #if PY_MAJOR_VERSION >= 3
  920. ScopedPyObjectPtr bases(PyTuple_Pack(1, mutable_mapping.get()));
  921. if (bases == NULL) {
  922. return false;
  923. }
  924. ScalarMapContainer_Type = reinterpret_cast<PyTypeObject*>(
  925. PyType_FromSpecWithBases(&ScalarMapContainer_Type_spec, bases.get()));
  926. #else
  927. _ScalarMapContainer_Type.tp_base =
  928. reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
  929. if (PyType_Ready(&_ScalarMapContainer_Type) < 0) {
  930. return false;
  931. }
  932. ScalarMapContainer_Type = &_ScalarMapContainer_Type;
  933. #endif
  934. if (PyType_Ready(&MapIterator_Type) < 0) {
  935. return false;
  936. }
  937. #if PY_MAJOR_VERSION >= 3
  938. MessageMapContainer_Type = reinterpret_cast<PyTypeObject*>(
  939. PyType_FromSpecWithBases(&MessageMapContainer_Type_spec, bases.get()));
  940. #else
  941. Py_INCREF(mutable_mapping.get());
  942. _MessageMapContainer_Type.tp_base =
  943. reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
  944. if (PyType_Ready(&_MessageMapContainer_Type) < 0) {
  945. return false;
  946. }
  947. MessageMapContainer_Type = &_MessageMapContainer_Type;
  948. #endif
  949. return true;
  950. }
  951. } // namespace python
  952. } // namespace protobuf
  953. } // namespace google