map.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2014 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. #include "convert.h"
  31. #include "defs.h"
  32. #include "message.h"
  33. #include "protobuf.h"
  34. // -----------------------------------------------------------------------------
  35. // Basic map operations on top of upb_map.
  36. //
  37. // Note that we roll our own `Map` container here because, as for
  38. // `RepeatedField`, we want a strongly-typed container. This is so that any user
  39. // errors due to incorrect map key or value types are raised as close as
  40. // possible to the error site, rather than at some deferred point (e.g.,
  41. // serialization).
  42. // -----------------------------------------------------------------------------
  43. // -----------------------------------------------------------------------------
  44. // Map container type.
  45. // -----------------------------------------------------------------------------
  46. typedef struct {
  47. const upb_map *map; // Can convert to mutable when non-frozen.
  48. upb_fieldtype_t key_type;
  49. TypeInfo value_type_info;
  50. VALUE value_type_class;
  51. VALUE arena;
  52. } Map;
  53. static void Map_mark(void* _self) {
  54. Map* self = _self;
  55. rb_gc_mark(self->value_type_class);
  56. rb_gc_mark(self->arena);
  57. }
  58. const rb_data_type_t Map_type = {
  59. "Google::Protobuf::Map",
  60. { Map_mark, RUBY_DEFAULT_FREE, NULL },
  61. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  62. };
  63. VALUE cMap;
  64. static Map* ruby_to_Map(VALUE _self) {
  65. Map* self;
  66. TypedData_Get_Struct(_self, Map, &Map_type, self);
  67. return self;
  68. }
  69. static VALUE Map_alloc(VALUE klass) {
  70. Map* self = ALLOC(Map);
  71. self->map = NULL;
  72. self->value_type_class = Qnil;
  73. self->value_type_info.def.msgdef = NULL;
  74. self->arena = Qnil;
  75. return TypedData_Wrap_Struct(klass, &Map_type, self);
  76. }
  77. VALUE Map_GetRubyWrapper(upb_map* map, upb_fieldtype_t key_type,
  78. TypeInfo value_type, VALUE arena) {
  79. PBRUBY_ASSERT(map);
  80. VALUE val = ObjectCache_Get(map);
  81. if (val == Qnil) {
  82. val = Map_alloc(cMap);
  83. Map* self;
  84. ObjectCache_Add(map, val);
  85. TypedData_Get_Struct(val, Map, &Map_type, self);
  86. self->map = map;
  87. self->arena = arena;
  88. self->key_type = key_type;
  89. self->value_type_info = value_type;
  90. if (self->value_type_info.type == UPB_TYPE_MESSAGE) {
  91. const upb_msgdef *val_m = self->value_type_info.def.msgdef;
  92. self->value_type_class = Descriptor_DefToClass(val_m);
  93. }
  94. }
  95. return val;
  96. }
  97. static VALUE Map_new_this_type(Map *from) {
  98. VALUE arena_rb = Arena_new();
  99. upb_map* map = upb_map_new(Arena_get(arena_rb), from->key_type,
  100. from->value_type_info.type);
  101. VALUE ret =
  102. Map_GetRubyWrapper(map, from->key_type, from->value_type_info, arena_rb);
  103. PBRUBY_ASSERT(ruby_to_Map(ret)->value_type_class == from->value_type_class);
  104. return ret;
  105. }
  106. static TypeInfo Map_keyinfo(Map* self) {
  107. TypeInfo ret;
  108. ret.type = self->key_type;
  109. ret.def.msgdef = NULL;
  110. return ret;
  111. }
  112. static upb_map *Map_GetMutable(VALUE _self) {
  113. rb_check_frozen(_self);
  114. return (upb_map*)ruby_to_Map(_self)->map;
  115. }
  116. VALUE Map_CreateHash(const upb_map* map, upb_fieldtype_t key_type,
  117. TypeInfo val_info) {
  118. VALUE hash = rb_hash_new();
  119. size_t iter = UPB_MAP_BEGIN;
  120. TypeInfo key_info = TypeInfo_from_type(key_type);
  121. if (!map) return hash;
  122. while (upb_mapiter_next(map, &iter)) {
  123. upb_msgval key = upb_mapiter_key(map, iter);
  124. upb_msgval val = upb_mapiter_value(map, iter);
  125. VALUE key_val = Convert_UpbToRuby(key, key_info, Qnil);
  126. VALUE val_val = Scalar_CreateHash(val, val_info);
  127. rb_hash_aset(hash, key_val, val_val);
  128. }
  129. return hash;
  130. }
  131. VALUE Map_deep_copy(VALUE obj) {
  132. Map* self = ruby_to_Map(obj);
  133. VALUE new_arena_rb = Arena_new();
  134. upb_arena *arena = Arena_get(new_arena_rb);
  135. upb_map* new_map =
  136. upb_map_new(arena, self->key_type, self->value_type_info.type);
  137. size_t iter = UPB_MAP_BEGIN;
  138. while (upb_mapiter_next(self->map, &iter)) {
  139. upb_msgval key = upb_mapiter_key(self->map, iter);
  140. upb_msgval val = upb_mapiter_value(self->map, iter);
  141. upb_msgval val_copy = Msgval_DeepCopy(val, self->value_type_info, arena);
  142. upb_map_set(new_map, key, val_copy, arena);
  143. }
  144. return Map_GetRubyWrapper(new_map, self->key_type, self->value_type_info,
  145. new_arena_rb);
  146. }
  147. const upb_map* Map_GetUpbMap(VALUE val, const upb_fielddef *field) {
  148. const upb_fielddef* key_field = map_field_key(field);
  149. const upb_fielddef* value_field = map_field_value(field);
  150. TypeInfo value_type_info = TypeInfo_get(value_field);
  151. Map* self;
  152. if (!RB_TYPE_P(val, T_DATA) || !RTYPEDDATA_P(val) ||
  153. RTYPEDDATA_TYPE(val) != &Map_type) {
  154. rb_raise(cTypeError, "Expected Map instance");
  155. }
  156. self = ruby_to_Map(val);
  157. if (self->key_type != upb_fielddef_type(key_field)) {
  158. rb_raise(cTypeError, "Map key type does not match field's key type");
  159. }
  160. if (self->value_type_info.type != value_type_info.type) {
  161. rb_raise(cTypeError, "Map value type does not match field's value type");
  162. }
  163. if (self->value_type_info.def.msgdef != value_type_info.def.msgdef) {
  164. rb_raise(cTypeError, "Map value type has wrong message/enum class");
  165. }
  166. return self->map;
  167. }
  168. void Map_Inspect(StringBuilder* b, const upb_map* map, upb_fieldtype_t key_type,
  169. TypeInfo val_type) {
  170. bool first = true;
  171. TypeInfo key_type_info = {key_type};
  172. StringBuilder_Printf(b, "{");
  173. if (map) {
  174. size_t iter = UPB_MAP_BEGIN;
  175. while (upb_mapiter_next(map, &iter)) {
  176. upb_msgval key = upb_mapiter_key(map, iter);
  177. upb_msgval val = upb_mapiter_value(map, iter);
  178. if (first) {
  179. first = false;
  180. } else {
  181. StringBuilder_Printf(b, ", ");
  182. }
  183. StringBuilder_PrintMsgval(b, key, key_type_info);
  184. StringBuilder_Printf(b, "=>");
  185. StringBuilder_PrintMsgval(b, val, val_type);
  186. }
  187. }
  188. StringBuilder_Printf(b, "}");
  189. }
  190. static int merge_into_self_callback(VALUE key, VALUE val, VALUE _self) {
  191. Map* self = ruby_to_Map(_self);
  192. upb_arena *arena = Arena_get(self->arena);
  193. upb_msgval key_val = Convert_RubyToUpb(key, "", Map_keyinfo(self), arena);
  194. upb_msgval val_val = Convert_RubyToUpb(val, "", self->value_type_info, arena);
  195. upb_map_set(Map_GetMutable(_self), key_val, val_val, arena);
  196. return ST_CONTINUE;
  197. }
  198. // Used only internally -- shared by #merge and #initialize.
  199. static VALUE Map_merge_into_self(VALUE _self, VALUE hashmap) {
  200. if (TYPE(hashmap) == T_HASH) {
  201. rb_hash_foreach(hashmap, merge_into_self_callback, _self);
  202. } else if (RB_TYPE_P(hashmap, T_DATA) && RTYPEDDATA_P(hashmap) &&
  203. RTYPEDDATA_TYPE(hashmap) == &Map_type) {
  204. Map* self = ruby_to_Map(_self);
  205. Map* other = ruby_to_Map(hashmap);
  206. upb_arena *arena = Arena_get(self->arena);
  207. upb_msg *self_msg = Map_GetMutable(_self);
  208. size_t iter = UPB_MAP_BEGIN;
  209. upb_arena_fuse(arena, Arena_get(other->arena));
  210. if (self->key_type != other->key_type ||
  211. self->value_type_info.type != other->value_type_info.type ||
  212. self->value_type_class != other->value_type_class) {
  213. rb_raise(rb_eArgError, "Attempt to merge Map with mismatching types");
  214. }
  215. while (upb_mapiter_next(other->map, &iter)) {
  216. upb_msgval key = upb_mapiter_key(other->map, iter);
  217. upb_msgval val = upb_mapiter_value(other->map, iter);
  218. upb_map_set(self_msg, key, val, arena);
  219. }
  220. } else {
  221. rb_raise(rb_eArgError, "Unknown type merging into Map");
  222. }
  223. return _self;
  224. }
  225. /*
  226. * call-seq:
  227. * Map.new(key_type, value_type, value_typeclass = nil, init_hashmap = {})
  228. * => new map
  229. *
  230. * Allocates a new Map container. This constructor may be called with 2, 3, or 4
  231. * arguments. The first two arguments are always present and are symbols (taking
  232. * on the same values as field-type symbols in message descriptors) that
  233. * indicate the type of the map key and value fields.
  234. *
  235. * The supported key types are: :int32, :int64, :uint32, :uint64, :bool,
  236. * :string, :bytes.
  237. *
  238. * The supported value types are: :int32, :int64, :uint32, :uint64, :bool,
  239. * :string, :bytes, :enum, :message.
  240. *
  241. * The third argument, value_typeclass, must be present if value_type is :enum
  242. * or :message. As in RepeatedField#new, this argument must be a message class
  243. * (for :message) or enum module (for :enum).
  244. *
  245. * The last argument, if present, provides initial content for map. Note that
  246. * this may be an ordinary Ruby hashmap or another Map instance with identical
  247. * key and value types. Also note that this argument may be present whether or
  248. * not value_typeclass is present (and it is unambiguously separate from
  249. * value_typeclass because value_typeclass's presence is strictly determined by
  250. * value_type). The contents of this initial hashmap or Map instance are
  251. * shallow-copied into the new Map: the original map is unmodified, but
  252. * references to underlying objects will be shared if the value type is a
  253. * message type.
  254. */
  255. static VALUE Map_init(int argc, VALUE* argv, VALUE _self) {
  256. Map* self = ruby_to_Map(_self);
  257. VALUE init_arg;
  258. // We take either two args (:key_type, :value_type), three args (:key_type,
  259. // :value_type, "ValueMessageType"), or four args (the above plus an initial
  260. // hashmap).
  261. if (argc < 2 || argc > 4) {
  262. rb_raise(rb_eArgError, "Map constructor expects 2, 3 or 4 arguments.");
  263. }
  264. self->key_type = ruby_to_fieldtype(argv[0]);
  265. self->value_type_info =
  266. TypeInfo_FromClass(argc, argv, 1, &self->value_type_class, &init_arg);
  267. self->arena = Arena_new();
  268. // Check that the key type is an allowed type.
  269. switch (self->key_type) {
  270. case UPB_TYPE_INT32:
  271. case UPB_TYPE_INT64:
  272. case UPB_TYPE_UINT32:
  273. case UPB_TYPE_UINT64:
  274. case UPB_TYPE_BOOL:
  275. case UPB_TYPE_STRING:
  276. case UPB_TYPE_BYTES:
  277. // These are OK.
  278. break;
  279. default:
  280. rb_raise(rb_eArgError, "Invalid key type for map.");
  281. }
  282. self->map = upb_map_new(Arena_get(self->arena), self->key_type,
  283. self->value_type_info.type);
  284. ObjectCache_Add(self->map, _self);
  285. if (init_arg != Qnil) {
  286. Map_merge_into_self(_self, init_arg);
  287. }
  288. return Qnil;
  289. }
  290. /*
  291. * call-seq:
  292. * Map.each(&block)
  293. *
  294. * Invokes &block on each |key, value| pair in the map, in unspecified order.
  295. * Note that Map also includes Enumerable; map thus acts like a normal Ruby
  296. * sequence.
  297. */
  298. static VALUE Map_each(VALUE _self) {
  299. Map* self = ruby_to_Map(_self);
  300. size_t iter = UPB_MAP_BEGIN;
  301. while (upb_mapiter_next(self->map, &iter)) {
  302. upb_msgval key = upb_mapiter_key(self->map, iter);
  303. upb_msgval val = upb_mapiter_value(self->map, iter);
  304. VALUE key_val = Convert_UpbToRuby(key, Map_keyinfo(self), self->arena);
  305. VALUE val_val = Convert_UpbToRuby(val, self->value_type_info, self->arena);
  306. rb_yield_values(2, key_val, val_val);
  307. }
  308. return Qnil;
  309. }
  310. /*
  311. * call-seq:
  312. * Map.keys => [list_of_keys]
  313. *
  314. * Returns the list of keys contained in the map, in unspecified order.
  315. */
  316. static VALUE Map_keys(VALUE _self) {
  317. Map* self = ruby_to_Map(_self);
  318. size_t iter = UPB_MAP_BEGIN;
  319. VALUE ret = rb_ary_new();
  320. while (upb_mapiter_next(self->map, &iter)) {
  321. upb_msgval key = upb_mapiter_key(self->map, iter);
  322. VALUE key_val = Convert_UpbToRuby(key, Map_keyinfo(self), self->arena);
  323. rb_ary_push(ret, key_val);
  324. }
  325. return ret;
  326. }
  327. /*
  328. * call-seq:
  329. * Map.values => [list_of_values]
  330. *
  331. * Returns the list of values contained in the map, in unspecified order.
  332. */
  333. static VALUE Map_values(VALUE _self) {
  334. Map* self = ruby_to_Map(_self);
  335. size_t iter = UPB_MAP_BEGIN;
  336. VALUE ret = rb_ary_new();
  337. while (upb_mapiter_next(self->map, &iter)) {
  338. upb_msgval val = upb_mapiter_value(self->map, iter);
  339. VALUE val_val = Convert_UpbToRuby(val, self->value_type_info, self->arena);
  340. rb_ary_push(ret, val_val);
  341. }
  342. return ret;
  343. }
  344. /*
  345. * call-seq:
  346. * Map.[](key) => value
  347. *
  348. * Accesses the element at the given key. Throws an exception if the key type is
  349. * incorrect. Returns nil when the key is not present in the map.
  350. */
  351. static VALUE Map_index(VALUE _self, VALUE key) {
  352. Map* self = ruby_to_Map(_self);
  353. upb_msgval key_upb = Convert_RubyToUpb(key, "", Map_keyinfo(self), NULL);
  354. upb_msgval val;
  355. if (upb_map_get(self->map, key_upb, &val)) {
  356. return Convert_UpbToRuby(val, self->value_type_info, self->arena);
  357. } else {
  358. return Qnil;
  359. }
  360. }
  361. /*
  362. * call-seq:
  363. * Map.[]=(key, value) => value
  364. *
  365. * Inserts or overwrites the value at the given key with the given new value.
  366. * Throws an exception if the key type is incorrect. Returns the new value that
  367. * was just inserted.
  368. */
  369. static VALUE Map_index_set(VALUE _self, VALUE key, VALUE val) {
  370. Map* self = ruby_to_Map(_self);
  371. upb_arena *arena = Arena_get(self->arena);
  372. upb_msgval key_upb = Convert_RubyToUpb(key, "", Map_keyinfo(self), NULL);
  373. upb_msgval val_upb = Convert_RubyToUpb(val, "", self->value_type_info, arena);
  374. upb_map_set(Map_GetMutable(_self), key_upb, val_upb, arena);
  375. return val;
  376. }
  377. /*
  378. * call-seq:
  379. * Map.has_key?(key) => bool
  380. *
  381. * Returns true if the given key is present in the map. Throws an exception if
  382. * the key has the wrong type.
  383. */
  384. static VALUE Map_has_key(VALUE _self, VALUE key) {
  385. Map* self = ruby_to_Map(_self);
  386. upb_msgval key_upb = Convert_RubyToUpb(key, "", Map_keyinfo(self), NULL);
  387. if (upb_map_get(self->map, key_upb, NULL)) {
  388. return Qtrue;
  389. } else {
  390. return Qfalse;
  391. }
  392. }
  393. /*
  394. * call-seq:
  395. * Map.delete(key) => old_value
  396. *
  397. * Deletes the value at the given key, if any, returning either the old value or
  398. * nil if none was present. Throws an exception if the key is of the wrong type.
  399. */
  400. static VALUE Map_delete(VALUE _self, VALUE key) {
  401. Map* self = ruby_to_Map(_self);
  402. upb_msgval key_upb = Convert_RubyToUpb(key, "", Map_keyinfo(self), NULL);
  403. upb_msgval val_upb;
  404. VALUE ret;
  405. rb_check_frozen(_self);
  406. // TODO(haberman): make upb_map_delete() also capable of returning the deleted
  407. // value.
  408. if (upb_map_get(self->map, key_upb, &val_upb)) {
  409. ret = Convert_UpbToRuby(val_upb, self->value_type_info, self->arena);
  410. } else {
  411. ret = Qnil;
  412. }
  413. upb_map_delete(Map_GetMutable(_self), key_upb);
  414. return ret;
  415. }
  416. /*
  417. * call-seq:
  418. * Map.clear
  419. *
  420. * Removes all entries from the map.
  421. */
  422. static VALUE Map_clear(VALUE _self) {
  423. upb_map_clear(Map_GetMutable(_self));
  424. return Qnil;
  425. }
  426. /*
  427. * call-seq:
  428. * Map.length
  429. *
  430. * Returns the number of entries (key-value pairs) in the map.
  431. */
  432. static VALUE Map_length(VALUE _self) {
  433. Map* self = ruby_to_Map(_self);
  434. return ULL2NUM(upb_map_size(self->map));
  435. }
  436. /*
  437. * call-seq:
  438. * Map.dup => new_map
  439. *
  440. * Duplicates this map with a shallow copy. References to all non-primitive
  441. * element objects (e.g., submessages) are shared.
  442. */
  443. static VALUE Map_dup(VALUE _self) {
  444. Map* self = ruby_to_Map(_self);
  445. VALUE new_map_rb = Map_new_this_type(self);
  446. Map* new_self = ruby_to_Map(new_map_rb);
  447. size_t iter = UPB_MAP_BEGIN;
  448. upb_arena *arena = Arena_get(new_self->arena);
  449. upb_map *new_map = Map_GetMutable(new_map_rb);
  450. upb_arena_fuse(arena, Arena_get(self->arena));
  451. while (upb_mapiter_next(self->map, &iter)) {
  452. upb_msgval key = upb_mapiter_key(self->map, iter);
  453. upb_msgval val = upb_mapiter_value(self->map, iter);
  454. upb_map_set(new_map, key, val, arena);
  455. }
  456. return new_map_rb;
  457. }
  458. /*
  459. * call-seq:
  460. * Map.==(other) => boolean
  461. *
  462. * Compares this map to another. Maps are equal if they have identical key sets,
  463. * and for each key, the values in both maps compare equal. Elements are
  464. * compared as per normal Ruby semantics, by calling their :== methods (or
  465. * performing a more efficient comparison for primitive types).
  466. *
  467. * Maps with dissimilar key types or value types/typeclasses are never equal,
  468. * even if value comparison (for example, between integers and floats) would
  469. * have otherwise indicated that every element has equal value.
  470. */
  471. VALUE Map_eq(VALUE _self, VALUE _other) {
  472. Map* self = ruby_to_Map(_self);
  473. Map* other;
  474. // Allow comparisons to Ruby hashmaps by converting to a temporary Map
  475. // instance. Slow, but workable.
  476. if (TYPE(_other) == T_HASH) {
  477. VALUE other_map = Map_new_this_type(self);
  478. Map_merge_into_self(other_map, _other);
  479. _other = other_map;
  480. }
  481. other = ruby_to_Map(_other);
  482. if (self == other) {
  483. return Qtrue;
  484. }
  485. if (self->key_type != other->key_type ||
  486. self->value_type_info.type != other->value_type_info.type ||
  487. self->value_type_class != other->value_type_class) {
  488. return Qfalse;
  489. }
  490. if (upb_map_size(self->map) != upb_map_size(other->map)) {
  491. return Qfalse;
  492. }
  493. // For each member of self, check that an equal member exists at the same key
  494. // in other.
  495. size_t iter = UPB_MAP_BEGIN;
  496. while (upb_mapiter_next(self->map, &iter)) {
  497. upb_msgval key = upb_mapiter_key(self->map, iter);
  498. upb_msgval val = upb_mapiter_value(self->map, iter);
  499. upb_msgval other_val;
  500. if (!upb_map_get(other->map, key, &other_val)) {
  501. // Not present in other map.
  502. return Qfalse;
  503. }
  504. if (!Msgval_IsEqual(val, other_val, self->value_type_info)) {
  505. // Present but different value.
  506. return Qfalse;
  507. }
  508. }
  509. return Qtrue;
  510. }
  511. /*
  512. * call-seq:
  513. * Message.freeze => self
  514. *
  515. * Freezes the message object. We have to intercept this so we can pin the
  516. * Ruby object into memory so we don't forget it's frozen.
  517. */
  518. static VALUE Map_freeze(VALUE _self) {
  519. Map* self = ruby_to_Map(_self);
  520. if (!RB_OBJ_FROZEN(_self)) {
  521. Arena_Pin(self->arena, _self);
  522. RB_OBJ_FREEZE(_self);
  523. }
  524. return _self;
  525. }
  526. /*
  527. * call-seq:
  528. * Map.hash => hash_value
  529. *
  530. * Returns a hash value based on this map's contents.
  531. */
  532. VALUE Map_hash(VALUE _self) {
  533. Map* self = ruby_to_Map(_self);
  534. uint64_t hash = 0;
  535. size_t iter = UPB_MAP_BEGIN;
  536. TypeInfo key_info = {self->key_type};
  537. while (upb_mapiter_next(self->map, &iter)) {
  538. upb_msgval key = upb_mapiter_key(self->map, iter);
  539. upb_msgval val = upb_mapiter_value(self->map, iter);
  540. hash = Msgval_GetHash(key, key_info, hash);
  541. hash = Msgval_GetHash(val, self->value_type_info, hash);
  542. }
  543. return LL2NUM(hash);
  544. }
  545. /*
  546. * call-seq:
  547. * Map.to_h => {}
  548. *
  549. * Returns a Ruby Hash object containing all the values within the map
  550. */
  551. VALUE Map_to_h(VALUE _self) {
  552. Map* self = ruby_to_Map(_self);
  553. return Map_CreateHash(self->map, self->key_type, self->value_type_info);
  554. }
  555. /*
  556. * call-seq:
  557. * Map.inspect => string
  558. *
  559. * Returns a string representing this map's elements. It will be formatted as
  560. * "{key => value, key => value, ...}", with each key and value string
  561. * representation computed by its own #inspect method.
  562. */
  563. VALUE Map_inspect(VALUE _self) {
  564. Map* self = ruby_to_Map(_self);
  565. StringBuilder* builder = StringBuilder_New();
  566. Map_Inspect(builder, self->map, self->key_type, self->value_type_info);
  567. VALUE ret = StringBuilder_ToRubyString(builder);
  568. StringBuilder_Free(builder);
  569. return ret;
  570. }
  571. /*
  572. * call-seq:
  573. * Map.merge(other_map) => map
  574. *
  575. * Copies key/value pairs from other_map into a copy of this map. If a key is
  576. * set in other_map and this map, the value from other_map overwrites the value
  577. * in the new copy of this map. Returns the new copy of this map with merged
  578. * contents.
  579. */
  580. static VALUE Map_merge(VALUE _self, VALUE hashmap) {
  581. VALUE dupped = Map_dup(_self);
  582. return Map_merge_into_self(dupped, hashmap);
  583. }
  584. void Map_register(VALUE module) {
  585. VALUE klass = rb_define_class_under(module, "Map", rb_cObject);
  586. rb_define_alloc_func(klass, Map_alloc);
  587. rb_gc_register_address(&cMap);
  588. cMap = klass;
  589. rb_define_method(klass, "initialize", Map_init, -1);
  590. rb_define_method(klass, "each", Map_each, 0);
  591. rb_define_method(klass, "keys", Map_keys, 0);
  592. rb_define_method(klass, "values", Map_values, 0);
  593. rb_define_method(klass, "[]", Map_index, 1);
  594. rb_define_method(klass, "[]=", Map_index_set, 2);
  595. rb_define_method(klass, "has_key?", Map_has_key, 1);
  596. rb_define_method(klass, "delete", Map_delete, 1);
  597. rb_define_method(klass, "clear", Map_clear, 0);
  598. rb_define_method(klass, "length", Map_length, 0);
  599. rb_define_method(klass, "dup", Map_dup, 0);
  600. rb_define_method(klass, "==", Map_eq, 1);
  601. rb_define_method(klass, "freeze", Map_freeze, 0);
  602. rb_define_method(klass, "hash", Map_hash, 0);
  603. rb_define_method(klass, "to_h", Map_to_h, 0);
  604. rb_define_method(klass, "inspect", Map_inspect, 0);
  605. rb_define_method(klass, "merge", Map_merge, 1);
  606. rb_include_module(klass, rb_mEnumerable);
  607. }