map_container.cc 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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, std::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. std::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. std::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 = other_reflection->GetMapData(
  320. *other_message, other_map->parent_field_descriptor);
  321. field->MergeFrom(*other_field);
  322. self->version++;
  323. Py_RETURN_NONE;
  324. }
  325. PyObject* MapReflectionFriend::Contains(PyObject* _self, PyObject* key) {
  326. MapContainer* self = GetMap(_self);
  327. const Message* message = self->parent->message;
  328. const Reflection* reflection = message->GetReflection();
  329. MapKey map_key;
  330. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  331. return NULL;
  332. }
  333. if (reflection->ContainsMapKey(*message, self->parent_field_descriptor,
  334. map_key)) {
  335. Py_RETURN_TRUE;
  336. } else {
  337. Py_RETURN_FALSE;
  338. }
  339. }
  340. // ScalarMap ///////////////////////////////////////////////////////////////////
  341. MapContainer* NewScalarMapContainer(
  342. CMessage* parent, const google::protobuf::FieldDescriptor* parent_field_descriptor) {
  343. if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) {
  344. return NULL;
  345. }
  346. PyObject* obj(PyType_GenericAlloc(ScalarMapContainer_Type, 0));
  347. if (obj == NULL) {
  348. PyErr_Format(PyExc_RuntimeError,
  349. "Could not allocate new container.");
  350. return NULL;
  351. }
  352. MapContainer* self = GetMap(obj);
  353. Py_INCREF(parent);
  354. self->parent = parent;
  355. self->parent_field_descriptor = parent_field_descriptor;
  356. self->version = 0;
  357. self->key_field_descriptor =
  358. parent_field_descriptor->message_type()->FindFieldByName("key");
  359. self->value_field_descriptor =
  360. parent_field_descriptor->message_type()->FindFieldByName("value");
  361. if (self->key_field_descriptor == NULL ||
  362. self->value_field_descriptor == NULL) {
  363. PyErr_Format(PyExc_KeyError,
  364. "Map entry descriptor did not have key/value fields");
  365. return NULL;
  366. }
  367. return self;
  368. }
  369. PyObject* MapReflectionFriend::ScalarMapGetItem(PyObject* _self,
  370. PyObject* key) {
  371. MapContainer* self = GetMap(_self);
  372. Message* message = self->GetMutableMessage();
  373. const Reflection* reflection = message->GetReflection();
  374. MapKey map_key;
  375. MapValueRef value;
  376. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  377. return NULL;
  378. }
  379. if (reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
  380. map_key, &value)) {
  381. self->version++;
  382. }
  383. return MapValueRefToPython(self->value_field_descriptor, value);
  384. }
  385. int MapReflectionFriend::ScalarMapSetItem(PyObject* _self, PyObject* key,
  386. PyObject* v) {
  387. MapContainer* self = GetMap(_self);
  388. Message* message = self->GetMutableMessage();
  389. const Reflection* reflection = message->GetReflection();
  390. MapKey map_key;
  391. MapValueRef value;
  392. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  393. return -1;
  394. }
  395. self->version++;
  396. if (v) {
  397. // Set item to v.
  398. reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
  399. map_key, &value);
  400. return PythonToMapValueRef(v, self->value_field_descriptor,
  401. reflection->SupportsUnknownEnumValues(), &value)
  402. ? 0
  403. : -1;
  404. } else {
  405. // Delete key from map.
  406. if (reflection->DeleteMapValue(message, self->parent_field_descriptor,
  407. map_key)) {
  408. return 0;
  409. } else {
  410. PyErr_Format(PyExc_KeyError, "Key not present in map");
  411. return -1;
  412. }
  413. }
  414. }
  415. static PyObject* ScalarMapGet(PyObject* self, PyObject* args,
  416. PyObject* kwargs) {
  417. static char* kwlist[] = {"key", "default", nullptr};
  418. PyObject* key;
  419. PyObject* default_value = NULL;
  420. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &key,
  421. &default_value)) {
  422. return NULL;
  423. }
  424. ScopedPyObjectPtr is_present(MapReflectionFriend::Contains(self, key));
  425. if (is_present.get() == NULL) {
  426. return NULL;
  427. }
  428. if (PyObject_IsTrue(is_present.get())) {
  429. return MapReflectionFriend::ScalarMapGetItem(self, key);
  430. } else {
  431. if (default_value != NULL) {
  432. Py_INCREF(default_value);
  433. return default_value;
  434. } else {
  435. Py_RETURN_NONE;
  436. }
  437. }
  438. }
  439. PyObject* MapReflectionFriend::ScalarMapToStr(PyObject* _self) {
  440. ScopedPyObjectPtr dict(PyDict_New());
  441. if (dict == NULL) {
  442. return NULL;
  443. }
  444. ScopedPyObjectPtr key;
  445. ScopedPyObjectPtr value;
  446. MapContainer* self = GetMap(_self);
  447. Message* message = self->GetMutableMessage();
  448. const Reflection* reflection = message->GetReflection();
  449. for (google::protobuf::MapIterator it = reflection->MapBegin(
  450. message, self->parent_field_descriptor);
  451. it != reflection->MapEnd(message, self->parent_field_descriptor);
  452. ++it) {
  453. key.reset(MapKeyToPython(self->key_field_descriptor,
  454. it.GetKey()));
  455. if (key == NULL) {
  456. return NULL;
  457. }
  458. value.reset(MapValueRefToPython(self->value_field_descriptor,
  459. it.GetValueRef()));
  460. if (value == NULL) {
  461. return NULL;
  462. }
  463. if (PyDict_SetItem(dict.get(), key.get(), value.get()) < 0) {
  464. return NULL;
  465. }
  466. }
  467. return PyObject_Repr(dict.get());
  468. }
  469. static void ScalarMapDealloc(PyObject* _self) {
  470. MapContainer* self = GetMap(_self);
  471. self->RemoveFromParentCache();
  472. PyTypeObject *type = Py_TYPE(_self);
  473. type->tp_free(_self);
  474. if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
  475. // With Python3, the Map class is not static, and must be managed.
  476. Py_DECREF(type);
  477. }
  478. }
  479. static PyMethodDef ScalarMapMethods[] = {
  480. {"__contains__", MapReflectionFriend::Contains, METH_O,
  481. "Tests whether a key is a member of the map."},
  482. {"clear", (PyCFunction)Clear, METH_NOARGS,
  483. "Removes all elements from the map."},
  484. {"get", (PyCFunction)ScalarMapGet, METH_VARARGS | METH_KEYWORDS,
  485. "Gets the value for the given key if present, or otherwise a default"},
  486. {"GetEntryClass", (PyCFunction)GetEntryClass, METH_NOARGS,
  487. "Return the class used to build Entries of (key, value) pairs."},
  488. {"MergeFrom", (PyCFunction)MapReflectionFriend::MergeFrom, METH_O,
  489. "Merges a map into the current map."},
  490. /*
  491. { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
  492. "Makes a deep copy of the class." },
  493. { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
  494. "Outputs picklable representation of the repeated field." },
  495. */
  496. {NULL, NULL},
  497. };
  498. PyTypeObject *ScalarMapContainer_Type;
  499. #if PY_MAJOR_VERSION >= 3
  500. static PyType_Slot ScalarMapContainer_Type_slots[] = {
  501. {Py_tp_dealloc, (void *)ScalarMapDealloc},
  502. {Py_mp_length, (void *)MapReflectionFriend::Length},
  503. {Py_mp_subscript, (void *)MapReflectionFriend::ScalarMapGetItem},
  504. {Py_mp_ass_subscript, (void *)MapReflectionFriend::ScalarMapSetItem},
  505. {Py_tp_methods, (void *)ScalarMapMethods},
  506. {Py_tp_iter, (void *)MapReflectionFriend::GetIterator},
  507. {Py_tp_repr, (void *)MapReflectionFriend::ScalarMapToStr},
  508. {0, 0},
  509. };
  510. PyType_Spec ScalarMapContainer_Type_spec = {
  511. FULL_MODULE_NAME ".ScalarMapContainer",
  512. sizeof(MapContainer),
  513. 0,
  514. Py_TPFLAGS_DEFAULT,
  515. ScalarMapContainer_Type_slots
  516. };
  517. #else
  518. static PyMappingMethods ScalarMapMappingMethods = {
  519. MapReflectionFriend::Length, // mp_length
  520. MapReflectionFriend::ScalarMapGetItem, // mp_subscript
  521. MapReflectionFriend::ScalarMapSetItem, // mp_ass_subscript
  522. };
  523. PyTypeObject _ScalarMapContainer_Type = {
  524. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  525. FULL_MODULE_NAME ".ScalarMapContainer", // tp_name
  526. sizeof(MapContainer), // tp_basicsize
  527. 0, // tp_itemsize
  528. ScalarMapDealloc, // tp_dealloc
  529. 0, // tp_print
  530. 0, // tp_getattr
  531. 0, // tp_setattr
  532. 0, // tp_compare
  533. MapReflectionFriend::ScalarMapToStr, // tp_repr
  534. 0, // tp_as_number
  535. 0, // tp_as_sequence
  536. &ScalarMapMappingMethods, // tp_as_mapping
  537. 0, // tp_hash
  538. 0, // tp_call
  539. 0, // tp_str
  540. 0, // tp_getattro
  541. 0, // tp_setattro
  542. 0, // tp_as_buffer
  543. Py_TPFLAGS_DEFAULT, // tp_flags
  544. "A scalar map container", // tp_doc
  545. 0, // tp_traverse
  546. 0, // tp_clear
  547. 0, // tp_richcompare
  548. 0, // tp_weaklistoffset
  549. MapReflectionFriend::GetIterator, // tp_iter
  550. 0, // tp_iternext
  551. ScalarMapMethods, // tp_methods
  552. 0, // tp_members
  553. 0, // tp_getset
  554. 0, // tp_base
  555. 0, // tp_dict
  556. 0, // tp_descr_get
  557. 0, // tp_descr_set
  558. 0, // tp_dictoffset
  559. 0, // tp_init
  560. };
  561. #endif
  562. // MessageMap //////////////////////////////////////////////////////////////////
  563. static MessageMapContainer* GetMessageMap(PyObject* obj) {
  564. return reinterpret_cast<MessageMapContainer*>(obj);
  565. }
  566. static PyObject* GetCMessage(MessageMapContainer* self, Message* message) {
  567. // Get or create the CMessage object corresponding to this message.
  568. return self->parent
  569. ->BuildSubMessageFromPointer(self->parent_field_descriptor, message,
  570. self->message_class)
  571. ->AsPyObject();
  572. }
  573. MessageMapContainer* NewMessageMapContainer(
  574. CMessage* parent, const google::protobuf::FieldDescriptor* parent_field_descriptor,
  575. CMessageClass* message_class) {
  576. if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) {
  577. return NULL;
  578. }
  579. PyObject* obj = PyType_GenericAlloc(MessageMapContainer_Type, 0);
  580. if (obj == NULL) {
  581. PyErr_SetString(PyExc_RuntimeError, "Could not allocate new container.");
  582. return NULL;
  583. }
  584. MessageMapContainer* self = GetMessageMap(obj);
  585. Py_INCREF(parent);
  586. self->parent = parent;
  587. self->parent_field_descriptor = parent_field_descriptor;
  588. self->version = 0;
  589. self->key_field_descriptor =
  590. parent_field_descriptor->message_type()->FindFieldByName("key");
  591. self->value_field_descriptor =
  592. parent_field_descriptor->message_type()->FindFieldByName("value");
  593. Py_INCREF(message_class);
  594. self->message_class = message_class;
  595. if (self->key_field_descriptor == NULL ||
  596. self->value_field_descriptor == NULL) {
  597. Py_DECREF(self);
  598. PyErr_SetString(PyExc_KeyError,
  599. "Map entry descriptor did not have key/value fields");
  600. return NULL;
  601. }
  602. return self;
  603. }
  604. int MapReflectionFriend::MessageMapSetItem(PyObject* _self, PyObject* key,
  605. PyObject* v) {
  606. if (v) {
  607. PyErr_Format(PyExc_ValueError,
  608. "Direct assignment of submessage not allowed");
  609. return -1;
  610. }
  611. // Now we know that this is a delete, not a set.
  612. MessageMapContainer* self = GetMessageMap(_self);
  613. Message* message = self->GetMutableMessage();
  614. const Reflection* reflection = message->GetReflection();
  615. MapKey map_key;
  616. MapValueRef value;
  617. self->version++;
  618. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  619. return -1;
  620. }
  621. // Delete key from map.
  622. if (reflection->ContainsMapKey(*message, self->parent_field_descriptor,
  623. map_key)) {
  624. // Delete key from CMessage dict.
  625. MapValueRef value;
  626. reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
  627. map_key, &value);
  628. Message* sub_message = value.MutableMessageValue();
  629. // If there is a living weak reference to an item, we "Release" it,
  630. // otherwise we just discard the C++ value.
  631. if (CMessage* released =
  632. self->parent->MaybeReleaseSubMessage(sub_message)) {
  633. Message* msg = released->message;
  634. released->message = msg->New();
  635. msg->GetReflection()->Swap(msg, released->message);
  636. }
  637. // Delete key from map.
  638. reflection->DeleteMapValue(message, self->parent_field_descriptor,
  639. map_key);
  640. return 0;
  641. } else {
  642. PyErr_Format(PyExc_KeyError, "Key not present in map");
  643. return -1;
  644. }
  645. }
  646. PyObject* MapReflectionFriend::MessageMapGetItem(PyObject* _self,
  647. PyObject* key) {
  648. MessageMapContainer* self = GetMessageMap(_self);
  649. Message* message = self->GetMutableMessage();
  650. const Reflection* reflection = message->GetReflection();
  651. MapKey map_key;
  652. MapValueRef value;
  653. if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
  654. return NULL;
  655. }
  656. if (reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
  657. map_key, &value)) {
  658. self->version++;
  659. }
  660. return GetCMessage(self, value.MutableMessageValue());
  661. }
  662. PyObject* MapReflectionFriend::MessageMapToStr(PyObject* _self) {
  663. ScopedPyObjectPtr dict(PyDict_New());
  664. if (dict == NULL) {
  665. return NULL;
  666. }
  667. ScopedPyObjectPtr key;
  668. ScopedPyObjectPtr value;
  669. MessageMapContainer* self = GetMessageMap(_self);
  670. Message* message = self->GetMutableMessage();
  671. const Reflection* reflection = message->GetReflection();
  672. for (google::protobuf::MapIterator it = reflection->MapBegin(
  673. message, self->parent_field_descriptor);
  674. it != reflection->MapEnd(message, self->parent_field_descriptor);
  675. ++it) {
  676. key.reset(MapKeyToPython(self->key_field_descriptor,
  677. it.GetKey()));
  678. if (key == NULL) {
  679. return NULL;
  680. }
  681. value.reset(GetCMessage(self, it.MutableValueRef()->MutableMessageValue()));
  682. if (value == NULL) {
  683. return NULL;
  684. }
  685. if (PyDict_SetItem(dict.get(), key.get(), value.get()) < 0) {
  686. return NULL;
  687. }
  688. }
  689. return PyObject_Repr(dict.get());
  690. }
  691. PyObject* MessageMapGet(PyObject* self, PyObject* args, PyObject* kwargs) {
  692. static char* kwlist[] = {"key", "default", nullptr};
  693. PyObject* key;
  694. PyObject* default_value = NULL;
  695. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &key,
  696. &default_value)) {
  697. return NULL;
  698. }
  699. ScopedPyObjectPtr is_present(MapReflectionFriend::Contains(self, key));
  700. if (is_present.get() == NULL) {
  701. return NULL;
  702. }
  703. if (PyObject_IsTrue(is_present.get())) {
  704. return MapReflectionFriend::MessageMapGetItem(self, key);
  705. } else {
  706. if (default_value != NULL) {
  707. Py_INCREF(default_value);
  708. return default_value;
  709. } else {
  710. Py_RETURN_NONE;
  711. }
  712. }
  713. }
  714. static void MessageMapDealloc(PyObject* _self) {
  715. MessageMapContainer* self = GetMessageMap(_self);
  716. self->RemoveFromParentCache();
  717. Py_DECREF(self->message_class);
  718. PyTypeObject *type = Py_TYPE(_self);
  719. type->tp_free(_self);
  720. if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
  721. // With Python3, the Map class is not static, and must be managed.
  722. Py_DECREF(type);
  723. }
  724. }
  725. static PyMethodDef MessageMapMethods[] = {
  726. {"__contains__", (PyCFunction)MapReflectionFriend::Contains, METH_O,
  727. "Tests whether the map contains this element."},
  728. {"clear", (PyCFunction)Clear, METH_NOARGS,
  729. "Removes all elements from the map."},
  730. {"get", (PyCFunction)MessageMapGet, METH_VARARGS | METH_KEYWORDS,
  731. "Gets the value for the given key if present, or otherwise a default"},
  732. {"get_or_create", MapReflectionFriend::MessageMapGetItem, METH_O,
  733. "Alias for getitem, useful to make explicit that the map is mutated."},
  734. {"GetEntryClass", (PyCFunction)GetEntryClass, METH_NOARGS,
  735. "Return the class used to build Entries of (key, value) pairs."},
  736. {"MergeFrom", (PyCFunction)MapReflectionFriend::MergeFrom, METH_O,
  737. "Merges a map into the current map."},
  738. /*
  739. { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
  740. "Makes a deep copy of the class." },
  741. { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
  742. "Outputs picklable representation of the repeated field." },
  743. */
  744. {NULL, NULL},
  745. };
  746. PyTypeObject *MessageMapContainer_Type;
  747. #if PY_MAJOR_VERSION >= 3
  748. static PyType_Slot MessageMapContainer_Type_slots[] = {
  749. {Py_tp_dealloc, (void *)MessageMapDealloc},
  750. {Py_mp_length, (void *)MapReflectionFriend::Length},
  751. {Py_mp_subscript, (void *)MapReflectionFriend::MessageMapGetItem},
  752. {Py_mp_ass_subscript, (void *)MapReflectionFriend::MessageMapSetItem},
  753. {Py_tp_methods, (void *)MessageMapMethods},
  754. {Py_tp_iter, (void *)MapReflectionFriend::GetIterator},
  755. {Py_tp_repr, (void *)MapReflectionFriend::MessageMapToStr},
  756. {0, 0}
  757. };
  758. PyType_Spec MessageMapContainer_Type_spec = {
  759. FULL_MODULE_NAME ".MessageMapContainer",
  760. sizeof(MessageMapContainer),
  761. 0,
  762. Py_TPFLAGS_DEFAULT,
  763. MessageMapContainer_Type_slots
  764. };
  765. #else
  766. static PyMappingMethods MessageMapMappingMethods = {
  767. MapReflectionFriend::Length, // mp_length
  768. MapReflectionFriend::MessageMapGetItem, // mp_subscript
  769. MapReflectionFriend::MessageMapSetItem, // mp_ass_subscript
  770. };
  771. PyTypeObject _MessageMapContainer_Type = {
  772. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  773. FULL_MODULE_NAME ".MessageMapContainer", // tp_name
  774. sizeof(MessageMapContainer), // tp_basicsize
  775. 0, // tp_itemsize
  776. MessageMapDealloc, // tp_dealloc
  777. 0, // tp_print
  778. 0, // tp_getattr
  779. 0, // tp_setattr
  780. 0, // tp_compare
  781. MapReflectionFriend::MessageMapToStr, // tp_repr
  782. 0, // tp_as_number
  783. 0, // tp_as_sequence
  784. &MessageMapMappingMethods, // tp_as_mapping
  785. 0, // tp_hash
  786. 0, // tp_call
  787. 0, // tp_str
  788. 0, // tp_getattro
  789. 0, // tp_setattro
  790. 0, // tp_as_buffer
  791. Py_TPFLAGS_DEFAULT, // tp_flags
  792. "A map container for message", // tp_doc
  793. 0, // tp_traverse
  794. 0, // tp_clear
  795. 0, // tp_richcompare
  796. 0, // tp_weaklistoffset
  797. MapReflectionFriend::GetIterator, // tp_iter
  798. 0, // tp_iternext
  799. MessageMapMethods, // tp_methods
  800. 0, // tp_members
  801. 0, // tp_getset
  802. 0, // tp_base
  803. 0, // tp_dict
  804. 0, // tp_descr_get
  805. 0, // tp_descr_set
  806. 0, // tp_dictoffset
  807. 0, // tp_init
  808. };
  809. #endif
  810. // MapIterator /////////////////////////////////////////////////////////////////
  811. static MapIterator* GetIter(PyObject* obj) {
  812. return reinterpret_cast<MapIterator*>(obj);
  813. }
  814. PyObject* MapReflectionFriend::GetIterator(PyObject *_self) {
  815. MapContainer* self = GetMap(_self);
  816. ScopedPyObjectPtr obj(PyType_GenericAlloc(&MapIterator_Type, 0));
  817. if (obj == NULL) {
  818. return PyErr_Format(PyExc_KeyError, "Could not allocate iterator");
  819. }
  820. MapIterator* iter = GetIter(obj.get());
  821. Py_INCREF(self);
  822. iter->container = self;
  823. iter->version = self->version;
  824. Py_INCREF(self->parent);
  825. iter->parent = self->parent;
  826. if (MapReflectionFriend::Length(_self) > 0) {
  827. Message* message = self->GetMutableMessage();
  828. const Reflection* reflection = message->GetReflection();
  829. iter->iter.reset(new ::google::protobuf::MapIterator(
  830. reflection->MapBegin(message, self->parent_field_descriptor)));
  831. }
  832. return obj.release();
  833. }
  834. PyObject* MapReflectionFriend::IterNext(PyObject* _self) {
  835. MapIterator* self = GetIter(_self);
  836. // This won't catch mutations to the map performed by MergeFrom(); no easy way
  837. // to address that.
  838. if (self->version != self->container->version) {
  839. return PyErr_Format(PyExc_RuntimeError,
  840. "Map modified during iteration.");
  841. }
  842. if (self->parent != self->container->parent) {
  843. return PyErr_Format(PyExc_RuntimeError,
  844. "Map cleared during iteration.");
  845. }
  846. if (self->iter.get() == NULL) {
  847. return NULL;
  848. }
  849. Message* message = self->container->GetMutableMessage();
  850. const Reflection* reflection = message->GetReflection();
  851. if (*self->iter ==
  852. reflection->MapEnd(message, self->container->parent_field_descriptor)) {
  853. return NULL;
  854. }
  855. PyObject* ret = MapKeyToPython(self->container->key_field_descriptor,
  856. self->iter->GetKey());
  857. ++(*self->iter);
  858. return ret;
  859. }
  860. static void DeallocMapIterator(PyObject* _self) {
  861. MapIterator* self = GetIter(_self);
  862. self->iter.reset();
  863. Py_CLEAR(self->container);
  864. Py_CLEAR(self->parent);
  865. Py_TYPE(_self)->tp_free(_self);
  866. }
  867. PyTypeObject MapIterator_Type = {
  868. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  869. FULL_MODULE_NAME ".MapIterator", // tp_name
  870. sizeof(MapIterator), // tp_basicsize
  871. 0, // tp_itemsize
  872. DeallocMapIterator, // tp_dealloc
  873. 0, // tp_print
  874. 0, // tp_getattr
  875. 0, // tp_setattr
  876. 0, // tp_compare
  877. 0, // tp_repr
  878. 0, // tp_as_number
  879. 0, // tp_as_sequence
  880. 0, // tp_as_mapping
  881. 0, // tp_hash
  882. 0, // tp_call
  883. 0, // tp_str
  884. 0, // tp_getattro
  885. 0, // tp_setattro
  886. 0, // tp_as_buffer
  887. Py_TPFLAGS_DEFAULT, // tp_flags
  888. "A scalar map iterator", // tp_doc
  889. 0, // tp_traverse
  890. 0, // tp_clear
  891. 0, // tp_richcompare
  892. 0, // tp_weaklistoffset
  893. PyObject_SelfIter, // tp_iter
  894. MapReflectionFriend::IterNext, // tp_iternext
  895. 0, // tp_methods
  896. 0, // tp_members
  897. 0, // tp_getset
  898. 0, // tp_base
  899. 0, // tp_dict
  900. 0, // tp_descr_get
  901. 0, // tp_descr_set
  902. 0, // tp_dictoffset
  903. 0, // tp_init
  904. };
  905. bool InitMapContainers() {
  906. // ScalarMapContainer_Type derives from our MutableMapping type.
  907. ScopedPyObjectPtr containers(PyImport_ImportModule(
  908. "google.protobuf.internal.containers"));
  909. if (containers == NULL) {
  910. return false;
  911. }
  912. ScopedPyObjectPtr mutable_mapping(
  913. PyObject_GetAttrString(containers.get(), "MutableMapping"));
  914. if (mutable_mapping == NULL) {
  915. return false;
  916. }
  917. Py_INCREF(mutable_mapping.get());
  918. #if PY_MAJOR_VERSION >= 3
  919. ScopedPyObjectPtr bases(PyTuple_Pack(1, mutable_mapping.get()));
  920. if (bases == NULL) {
  921. return false;
  922. }
  923. ScalarMapContainer_Type = reinterpret_cast<PyTypeObject*>(
  924. PyType_FromSpecWithBases(&ScalarMapContainer_Type_spec, bases.get()));
  925. #else
  926. _ScalarMapContainer_Type.tp_base =
  927. reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
  928. if (PyType_Ready(&_ScalarMapContainer_Type) < 0) {
  929. return false;
  930. }
  931. ScalarMapContainer_Type = &_ScalarMapContainer_Type;
  932. #endif
  933. if (PyType_Ready(&MapIterator_Type) < 0) {
  934. return false;
  935. }
  936. #if PY_MAJOR_VERSION >= 3
  937. MessageMapContainer_Type = reinterpret_cast<PyTypeObject*>(
  938. PyType_FromSpecWithBases(&MessageMapContainer_Type_spec, bases.get()));
  939. #else
  940. Py_INCREF(mutable_mapping.get());
  941. _MessageMapContainer_Type.tp_base =
  942. reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
  943. if (PyType_Ready(&_MessageMapContainer_Type) < 0) {
  944. return false;
  945. }
  946. MessageMapContainer_Type = &_MessageMapContainer_Type;
  947. #endif
  948. return true;
  949. }
  950. } // namespace python
  951. } // namespace protobuf
  952. } // namespace google