map.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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 "protobuf.h"
  31. // -----------------------------------------------------------------------------
  32. // Basic map operations on top of upb's strtable.
  33. //
  34. // Note that we roll our own `Map` container here because, as for
  35. // `RepeatedField`, we want a strongly-typed container. This is so that any user
  36. // errors due to incorrect map key or value types are raised as close as
  37. // possible to the error site, rather than at some deferred point (e.g.,
  38. // serialization).
  39. //
  40. // We build our `Map` on top of upb_strtable so that we're able to take
  41. // advantage of the native_slot storage abstraction, as RepeatedField does.
  42. // (This is not quite a perfect mapping -- see the key conversions below -- but
  43. // gives us full support and error-checking for all value types for free.)
  44. // -----------------------------------------------------------------------------
  45. // Map values are stored using the native_slot abstraction (as with repeated
  46. // field values), but keys are a bit special. Since we use a strtable, we need
  47. // to store keys as sequences of bytes such that equality of those bytes maps
  48. // one-to-one to equality of keys. We store strings directly (i.e., they map to
  49. // their own bytes) and integers as native integers (using the native_slot
  50. // abstraction).
  51. // Note that there is another tradeoff here in keeping string keys as native
  52. // strings rather than Ruby strings: traversing the Map requires conversion to
  53. // Ruby string values on every traversal, potentially creating more garbage. We
  54. // should consider ways to cache a Ruby version of the key if this becomes an
  55. // issue later.
  56. // Forms a key to use with the underlying strtable from a Ruby key value. |buf|
  57. // must point to TABLE_KEY_BUF_LENGTH bytes of temporary space, used to
  58. // construct a key byte sequence if needed. |out_key| and |out_length| provide
  59. // the resulting key data/length.
  60. #define TABLE_KEY_BUF_LENGTH 8 // sizeof(uint64_t)
  61. static VALUE table_key(Map* self, VALUE key,
  62. char* buf,
  63. const char** out_key,
  64. size_t* out_length) {
  65. switch (self->key_type) {
  66. case UPB_TYPE_BYTES:
  67. case UPB_TYPE_STRING:
  68. // Strings: use string content directly.
  69. if (TYPE(key) == T_SYMBOL) {
  70. key = rb_id2str(SYM2ID(key));
  71. }
  72. Check_Type(key, T_STRING);
  73. key = native_slot_encode_and_freeze_string(self->key_type, key);
  74. *out_key = RSTRING_PTR(key);
  75. *out_length = RSTRING_LEN(key);
  76. break;
  77. case UPB_TYPE_BOOL:
  78. case UPB_TYPE_INT32:
  79. case UPB_TYPE_INT64:
  80. case UPB_TYPE_UINT32:
  81. case UPB_TYPE_UINT64:
  82. native_slot_set("", self->key_type, Qnil, buf, key);
  83. *out_key = buf;
  84. *out_length = native_slot_size(self->key_type);
  85. break;
  86. default:
  87. // Map constructor should not allow a Map with another key type to be
  88. // constructed.
  89. assert(false);
  90. break;
  91. }
  92. return key;
  93. }
  94. static VALUE table_key_to_ruby(Map* self, const char* buf, size_t length) {
  95. switch (self->key_type) {
  96. case UPB_TYPE_BYTES:
  97. case UPB_TYPE_STRING: {
  98. VALUE ret = rb_str_new(buf, length);
  99. rb_enc_associate(ret,
  100. (self->key_type == UPB_TYPE_BYTES) ?
  101. kRubyString8bitEncoding : kRubyStringUtf8Encoding);
  102. return ret;
  103. }
  104. case UPB_TYPE_BOOL:
  105. case UPB_TYPE_INT32:
  106. case UPB_TYPE_INT64:
  107. case UPB_TYPE_UINT32:
  108. case UPB_TYPE_UINT64:
  109. return native_slot_get(self->key_type, Qnil, buf);
  110. default:
  111. assert(false);
  112. return Qnil;
  113. }
  114. }
  115. static void* value_memory(upb_value* v) {
  116. return (void*)(&v->val);
  117. }
  118. // -----------------------------------------------------------------------------
  119. // Map container type.
  120. // -----------------------------------------------------------------------------
  121. const rb_data_type_t Map_type = {
  122. "Google::Protobuf::Map",
  123. { Map_mark, Map_free, NULL },
  124. };
  125. VALUE cMap;
  126. Map* ruby_to_Map(VALUE _self) {
  127. Map* self;
  128. TypedData_Get_Struct(_self, Map, &Map_type, self);
  129. return self;
  130. }
  131. void Map_mark(void* _self) {
  132. Map* self = _self;
  133. rb_gc_mark(self->value_type_class);
  134. rb_gc_mark(self->parse_frame);
  135. if (self->value_type == UPB_TYPE_STRING ||
  136. self->value_type == UPB_TYPE_BYTES ||
  137. self->value_type == UPB_TYPE_MESSAGE) {
  138. upb_strtable_iter it;
  139. for (upb_strtable_begin(&it, &self->table);
  140. !upb_strtable_done(&it);
  141. upb_strtable_next(&it)) {
  142. upb_value v = upb_strtable_iter_value(&it);
  143. void* mem = value_memory(&v);
  144. native_slot_mark(self->value_type, mem);
  145. }
  146. }
  147. }
  148. void Map_free(void* _self) {
  149. Map* self = _self;
  150. upb_strtable_uninit(&self->table);
  151. xfree(self);
  152. }
  153. VALUE Map_alloc(VALUE klass) {
  154. Map* self = ALLOC(Map);
  155. memset(self, 0, sizeof(Map));
  156. self->value_type_class = Qnil;
  157. return TypedData_Wrap_Struct(klass, &Map_type, self);
  158. }
  159. VALUE Map_set_frame(VALUE map, VALUE val) {
  160. Map* self = ruby_to_Map(map);
  161. self->parse_frame = val;
  162. return val;
  163. }
  164. static bool needs_typeclass(upb_fieldtype_t type) {
  165. switch (type) {
  166. case UPB_TYPE_MESSAGE:
  167. case UPB_TYPE_ENUM:
  168. return true;
  169. default:
  170. return false;
  171. }
  172. }
  173. /*
  174. * call-seq:
  175. * Map.new(key_type, value_type, value_typeclass = nil, init_hashmap = {})
  176. * => new map
  177. *
  178. * Allocates a new Map container. This constructor may be called with 2, 3, or 4
  179. * arguments. The first two arguments are always present and are symbols (taking
  180. * on the same values as field-type symbols in message descriptors) that
  181. * indicate the type of the map key and value fields.
  182. *
  183. * The supported key types are: :int32, :int64, :uint32, :uint64, :bool,
  184. * :string, :bytes.
  185. *
  186. * The supported value types are: :int32, :int64, :uint32, :uint64, :bool,
  187. * :string, :bytes, :enum, :message.
  188. *
  189. * The third argument, value_typeclass, must be present if value_type is :enum
  190. * or :message. As in RepeatedField#new, this argument must be a message class
  191. * (for :message) or enum module (for :enum).
  192. *
  193. * The last argument, if present, provides initial content for map. Note that
  194. * this may be an ordinary Ruby hashmap or another Map instance with identical
  195. * key and value types. Also note that this argument may be present whether or
  196. * not value_typeclass is present (and it is unambiguously separate from
  197. * value_typeclass because value_typeclass's presence is strictly determined by
  198. * value_type). The contents of this initial hashmap or Map instance are
  199. * shallow-copied into the new Map: the original map is unmodified, but
  200. * references to underlying objects will be shared if the value type is a
  201. * message type.
  202. */
  203. VALUE Map_init(int argc, VALUE* argv, VALUE _self) {
  204. Map* self = ruby_to_Map(_self);
  205. int init_value_arg;
  206. // We take either two args (:key_type, :value_type), three args (:key_type,
  207. // :value_type, "ValueMessageType"), or four args (the above plus an initial
  208. // hashmap).
  209. if (argc < 2 || argc > 4) {
  210. rb_raise(rb_eArgError, "Map constructor expects 2, 3 or 4 arguments.");
  211. }
  212. self->key_type = ruby_to_fieldtype(argv[0]);
  213. self->value_type = ruby_to_fieldtype(argv[1]);
  214. self->parse_frame = Qnil;
  215. // Check that the key type is an allowed type.
  216. switch (self->key_type) {
  217. case UPB_TYPE_INT32:
  218. case UPB_TYPE_INT64:
  219. case UPB_TYPE_UINT32:
  220. case UPB_TYPE_UINT64:
  221. case UPB_TYPE_BOOL:
  222. case UPB_TYPE_STRING:
  223. case UPB_TYPE_BYTES:
  224. // These are OK.
  225. break;
  226. default:
  227. rb_raise(rb_eArgError, "Invalid key type for map.");
  228. }
  229. init_value_arg = 2;
  230. if (needs_typeclass(self->value_type) && argc > 2) {
  231. self->value_type_class = argv[2];
  232. validate_type_class(self->value_type, self->value_type_class);
  233. init_value_arg = 3;
  234. }
  235. // Table value type is always UINT64: this ensures enough space to store the
  236. // native_slot value.
  237. if (!upb_strtable_init(&self->table, UPB_CTYPE_UINT64)) {
  238. rb_raise(rb_eRuntimeError, "Could not allocate table.");
  239. }
  240. if (argc > init_value_arg) {
  241. Map_merge_into_self(_self, argv[init_value_arg]);
  242. }
  243. return Qnil;
  244. }
  245. /*
  246. * call-seq:
  247. * Map.each(&block)
  248. *
  249. * Invokes &block on each |key, value| pair in the map, in unspecified order.
  250. * Note that Map also includes Enumerable; map thus acts like a normal Ruby
  251. * sequence.
  252. */
  253. VALUE Map_each(VALUE _self) {
  254. Map* self = ruby_to_Map(_self);
  255. upb_strtable_iter it;
  256. for (upb_strtable_begin(&it, &self->table);
  257. !upb_strtable_done(&it);
  258. upb_strtable_next(&it)) {
  259. VALUE key = table_key_to_ruby(
  260. self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
  261. upb_value v = upb_strtable_iter_value(&it);
  262. void* mem = value_memory(&v);
  263. VALUE value = native_slot_get(self->value_type,
  264. self->value_type_class,
  265. mem);
  266. rb_yield_values(2, key, value);
  267. }
  268. return Qnil;
  269. }
  270. /*
  271. * call-seq:
  272. * Map.keys => [list_of_keys]
  273. *
  274. * Returns the list of keys contained in the map, in unspecified order.
  275. */
  276. VALUE Map_keys(VALUE _self) {
  277. Map* self = ruby_to_Map(_self);
  278. VALUE ret = rb_ary_new();
  279. upb_strtable_iter it;
  280. for (upb_strtable_begin(&it, &self->table);
  281. !upb_strtable_done(&it);
  282. upb_strtable_next(&it)) {
  283. VALUE key = table_key_to_ruby(
  284. self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
  285. rb_ary_push(ret, key);
  286. }
  287. return ret;
  288. }
  289. /*
  290. * call-seq:
  291. * Map.values => [list_of_values]
  292. *
  293. * Returns the list of values contained in the map, in unspecified order.
  294. */
  295. VALUE Map_values(VALUE _self) {
  296. Map* self = ruby_to_Map(_self);
  297. VALUE ret = rb_ary_new();
  298. upb_strtable_iter it;
  299. for (upb_strtable_begin(&it, &self->table);
  300. !upb_strtable_done(&it);
  301. upb_strtable_next(&it)) {
  302. upb_value v = upb_strtable_iter_value(&it);
  303. void* mem = value_memory(&v);
  304. VALUE value = native_slot_get(self->value_type,
  305. self->value_type_class,
  306. mem);
  307. rb_ary_push(ret, value);
  308. }
  309. return ret;
  310. }
  311. /*
  312. * call-seq:
  313. * Map.[](key) => value
  314. *
  315. * Accesses the element at the given key. Throws an exception if the key type is
  316. * incorrect. Returns nil when the key is not present in the map.
  317. */
  318. VALUE Map_index(VALUE _self, VALUE key) {
  319. Map* self = ruby_to_Map(_self);
  320. char keybuf[TABLE_KEY_BUF_LENGTH];
  321. const char* keyval = NULL;
  322. size_t length = 0;
  323. upb_value v;
  324. key = table_key(self, key, keybuf, &keyval, &length);
  325. if (upb_strtable_lookup2(&self->table, keyval, length, &v)) {
  326. void* mem = value_memory(&v);
  327. return native_slot_get(self->value_type, self->value_type_class, mem);
  328. } else {
  329. return Qnil;
  330. }
  331. }
  332. /*
  333. * call-seq:
  334. * Map.[]=(key, value) => value
  335. *
  336. * Inserts or overwrites the value at the given key with the given new value.
  337. * Throws an exception if the key type is incorrect. Returns the new value that
  338. * was just inserted.
  339. */
  340. VALUE Map_index_set(VALUE _self, VALUE key, VALUE value) {
  341. rb_check_frozen(_self);
  342. Map* self = ruby_to_Map(_self);
  343. char keybuf[TABLE_KEY_BUF_LENGTH];
  344. const char* keyval = NULL;
  345. size_t length = 0;
  346. upb_value v;
  347. void* mem;
  348. key = table_key(self, key, keybuf, &keyval, &length);
  349. if (TYPE(value) == T_HASH) {
  350. VALUE args[1] = { value };
  351. value = rb_class_new_instance(1, args, self->value_type_class);
  352. }
  353. mem = value_memory(&v);
  354. native_slot_set("", self->value_type, self->value_type_class, mem, value);
  355. // Replace any existing value by issuing a 'remove' operation first.
  356. upb_strtable_remove2(&self->table, keyval, length, NULL);
  357. if (!upb_strtable_insert2(&self->table, keyval, length, v)) {
  358. rb_raise(rb_eRuntimeError, "Could not insert into table");
  359. }
  360. // Ruby hashmap's :[]= method also returns the inserted value.
  361. return value;
  362. }
  363. /*
  364. * call-seq:
  365. * Map.has_key?(key) => bool
  366. *
  367. * Returns true if the given key is present in the map. Throws an exception if
  368. * the key has the wrong type.
  369. */
  370. VALUE Map_has_key(VALUE _self, VALUE key) {
  371. Map* self = ruby_to_Map(_self);
  372. char keybuf[TABLE_KEY_BUF_LENGTH];
  373. const char* keyval = NULL;
  374. size_t length = 0;
  375. key = table_key(self, key, keybuf, &keyval, &length);
  376. if (upb_strtable_lookup2(&self->table, keyval, length, NULL)) {
  377. return Qtrue;
  378. } else {
  379. return Qfalse;
  380. }
  381. }
  382. /*
  383. * call-seq:
  384. * Map.delete(key) => old_value
  385. *
  386. * Deletes the value at the given key, if any, returning either the old value or
  387. * nil if none was present. Throws an exception if the key is of the wrong type.
  388. */
  389. VALUE Map_delete(VALUE _self, VALUE key) {
  390. rb_check_frozen(_self);
  391. Map* self = ruby_to_Map(_self);
  392. char keybuf[TABLE_KEY_BUF_LENGTH];
  393. const char* keyval = NULL;
  394. size_t length = 0;
  395. upb_value v;
  396. key = table_key(self, key, keybuf, &keyval, &length);
  397. if (upb_strtable_remove2(&self->table, keyval, length, &v)) {
  398. void* mem = value_memory(&v);
  399. return native_slot_get(self->value_type, self->value_type_class, mem);
  400. } else {
  401. return Qnil;
  402. }
  403. }
  404. /*
  405. * call-seq:
  406. * Map.clear
  407. *
  408. * Removes all entries from the map.
  409. */
  410. VALUE Map_clear(VALUE _self) {
  411. rb_check_frozen(_self);
  412. Map* self = ruby_to_Map(_self);
  413. // Uninit and reinit the table -- this is faster than iterating and doing a
  414. // delete-lookup on each key.
  415. upb_strtable_uninit(&self->table);
  416. if (!upb_strtable_init(&self->table, UPB_CTYPE_INT64)) {
  417. rb_raise(rb_eRuntimeError, "Unable to re-initialize table");
  418. }
  419. return Qnil;
  420. }
  421. /*
  422. * call-seq:
  423. * Map.length
  424. *
  425. * Returns the number of entries (key-value pairs) in the map.
  426. */
  427. VALUE Map_length(VALUE _self) {
  428. Map* self = ruby_to_Map(_self);
  429. return ULL2NUM(upb_strtable_count(&self->table));
  430. }
  431. static VALUE Map_new_this_type(VALUE _self) {
  432. Map* self = ruby_to_Map(_self);
  433. VALUE new_map = Qnil;
  434. VALUE key_type = fieldtype_to_ruby(self->key_type);
  435. VALUE value_type = fieldtype_to_ruby(self->value_type);
  436. if (self->value_type_class != Qnil) {
  437. new_map = rb_funcall(CLASS_OF(_self), rb_intern("new"), 3,
  438. key_type, value_type, self->value_type_class);
  439. } else {
  440. new_map = rb_funcall(CLASS_OF(_self), rb_intern("new"), 2,
  441. key_type, value_type);
  442. }
  443. return new_map;
  444. }
  445. /*
  446. * call-seq:
  447. * Map.dup => new_map
  448. *
  449. * Duplicates this map with a shallow copy. References to all non-primitive
  450. * element objects (e.g., submessages) are shared.
  451. */
  452. VALUE Map_dup(VALUE _self) {
  453. Map* self = ruby_to_Map(_self);
  454. VALUE new_map = Map_new_this_type(_self);
  455. Map* new_self = ruby_to_Map(new_map);
  456. upb_strtable_iter it;
  457. for (upb_strtable_begin(&it, &self->table);
  458. !upb_strtable_done(&it);
  459. upb_strtable_next(&it)) {
  460. upb_value v = upb_strtable_iter_value(&it);
  461. void* mem = value_memory(&v);
  462. upb_value dup;
  463. void* dup_mem = value_memory(&dup);
  464. native_slot_dup(self->value_type, dup_mem, mem);
  465. if (!upb_strtable_insert2(&new_self->table,
  466. upb_strtable_iter_key(&it),
  467. upb_strtable_iter_keylength(&it),
  468. dup)) {
  469. rb_raise(rb_eRuntimeError, "Error inserting value into new table");
  470. }
  471. }
  472. return new_map;
  473. }
  474. // Used by Google::Protobuf.deep_copy but not exposed directly.
  475. VALUE Map_deep_copy(VALUE _self) {
  476. Map* self = ruby_to_Map(_self);
  477. VALUE new_map = Map_new_this_type(_self);
  478. Map* new_self = ruby_to_Map(new_map);
  479. upb_strtable_iter it;
  480. for (upb_strtable_begin(&it, &self->table);
  481. !upb_strtable_done(&it);
  482. upb_strtable_next(&it)) {
  483. upb_value v = upb_strtable_iter_value(&it);
  484. void* mem = value_memory(&v);
  485. upb_value dup;
  486. void* dup_mem = value_memory(&dup);
  487. native_slot_deep_copy(self->value_type, dup_mem, mem);
  488. if (!upb_strtable_insert2(&new_self->table,
  489. upb_strtable_iter_key(&it),
  490. upb_strtable_iter_keylength(&it),
  491. dup)) {
  492. rb_raise(rb_eRuntimeError, "Error inserting value into new table");
  493. }
  494. }
  495. return new_map;
  496. }
  497. /*
  498. * call-seq:
  499. * Map.==(other) => boolean
  500. *
  501. * Compares this map to another. Maps are equal if they have identical key sets,
  502. * and for each key, the values in both maps compare equal. Elements are
  503. * compared as per normal Ruby semantics, by calling their :== methods (or
  504. * performing a more efficient comparison for primitive types).
  505. *
  506. * Maps with dissimilar key types or value types/typeclasses are never equal,
  507. * even if value comparison (for example, between integers and floats) would
  508. * have otherwise indicated that every element has equal value.
  509. */
  510. VALUE Map_eq(VALUE _self, VALUE _other) {
  511. Map* self = ruby_to_Map(_self);
  512. Map* other;
  513. upb_strtable_iter it;
  514. // Allow comparisons to Ruby hashmaps by converting to a temporary Map
  515. // instance. Slow, but workable.
  516. if (TYPE(_other) == T_HASH) {
  517. VALUE other_map = Map_new_this_type(_self);
  518. Map_merge_into_self(other_map, _other);
  519. _other = other_map;
  520. }
  521. other = ruby_to_Map(_other);
  522. if (self == other) {
  523. return Qtrue;
  524. }
  525. if (self->key_type != other->key_type ||
  526. self->value_type != other->value_type ||
  527. self->value_type_class != other->value_type_class) {
  528. return Qfalse;
  529. }
  530. if (upb_strtable_count(&self->table) != upb_strtable_count(&other->table)) {
  531. return Qfalse;
  532. }
  533. // For each member of self, check that an equal member exists at the same key
  534. // in other.
  535. for (upb_strtable_begin(&it, &self->table);
  536. !upb_strtable_done(&it);
  537. upb_strtable_next(&it)) {
  538. upb_value v = upb_strtable_iter_value(&it);
  539. void* mem = value_memory(&v);
  540. upb_value other_v;
  541. void* other_mem = value_memory(&other_v);
  542. if (!upb_strtable_lookup2(&other->table,
  543. upb_strtable_iter_key(&it),
  544. upb_strtable_iter_keylength(&it),
  545. &other_v)) {
  546. // Not present in other map.
  547. return Qfalse;
  548. }
  549. if (!native_slot_eq(self->value_type, mem, other_mem)) {
  550. // Present, but value not equal.
  551. return Qfalse;
  552. }
  553. }
  554. return Qtrue;
  555. }
  556. /*
  557. * call-seq:
  558. * Map.hash => hash_value
  559. *
  560. * Returns a hash value based on this map's contents.
  561. */
  562. VALUE Map_hash(VALUE _self) {
  563. Map* self = ruby_to_Map(_self);
  564. st_index_t h = rb_hash_start(0);
  565. VALUE hash_sym = rb_intern("hash");
  566. upb_strtable_iter it;
  567. for (upb_strtable_begin(&it, &self->table);
  568. !upb_strtable_done(&it);
  569. upb_strtable_next(&it)) {
  570. VALUE key = table_key_to_ruby(
  571. self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
  572. upb_value v = upb_strtable_iter_value(&it);
  573. void* mem = value_memory(&v);
  574. VALUE value = native_slot_get(self->value_type,
  575. self->value_type_class,
  576. mem);
  577. h = rb_hash_uint(h, NUM2LONG(rb_funcall(key, hash_sym, 0)));
  578. h = rb_hash_uint(h, NUM2LONG(rb_funcall(value, hash_sym, 0)));
  579. }
  580. return INT2FIX(h);
  581. }
  582. /*
  583. * call-seq:
  584. * Map.to_h => {}
  585. *
  586. * Returns a Ruby Hash object containing all the values within the map
  587. */
  588. VALUE Map_to_h(VALUE _self) {
  589. Map* self = ruby_to_Map(_self);
  590. VALUE hash = rb_hash_new();
  591. upb_strtable_iter it;
  592. for (upb_strtable_begin(&it, &self->table);
  593. !upb_strtable_done(&it);
  594. upb_strtable_next(&it)) {
  595. VALUE key = table_key_to_ruby(
  596. self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
  597. upb_value v = upb_strtable_iter_value(&it);
  598. void* mem = value_memory(&v);
  599. VALUE value = native_slot_get(self->value_type,
  600. self->value_type_class,
  601. mem);
  602. if (self->value_type == UPB_TYPE_MESSAGE) {
  603. value = Message_to_h(value);
  604. }
  605. rb_hash_aset(hash, key, value);
  606. }
  607. return hash;
  608. }
  609. /*
  610. * call-seq:
  611. * Map.inspect => string
  612. *
  613. * Returns a string representing this map's elements. It will be formatted as
  614. * "{key => value, key => value, ...}", with each key and value string
  615. * representation computed by its own #inspect method.
  616. */
  617. VALUE Map_inspect(VALUE _self) {
  618. Map* self = ruby_to_Map(_self);
  619. VALUE str = rb_str_new2("{");
  620. bool first = true;
  621. VALUE inspect_sym = rb_intern("inspect");
  622. upb_strtable_iter it;
  623. for (upb_strtable_begin(&it, &self->table);
  624. !upb_strtable_done(&it);
  625. upb_strtable_next(&it)) {
  626. VALUE key = table_key_to_ruby(
  627. self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
  628. upb_value v = upb_strtable_iter_value(&it);
  629. void* mem = value_memory(&v);
  630. VALUE value = native_slot_get(self->value_type,
  631. self->value_type_class,
  632. mem);
  633. if (!first) {
  634. str = rb_str_cat2(str, ", ");
  635. } else {
  636. first = false;
  637. }
  638. str = rb_str_append(str, rb_funcall(key, inspect_sym, 0));
  639. str = rb_str_cat2(str, "=>");
  640. str = rb_str_append(str, rb_funcall(value, inspect_sym, 0));
  641. }
  642. str = rb_str_cat2(str, "}");
  643. return str;
  644. }
  645. /*
  646. * call-seq:
  647. * Map.merge(other_map) => map
  648. *
  649. * Copies key/value pairs from other_map into a copy of this map. If a key is
  650. * set in other_map and this map, the value from other_map overwrites the value
  651. * in the new copy of this map. Returns the new copy of this map with merged
  652. * contents.
  653. */
  654. VALUE Map_merge(VALUE _self, VALUE hashmap) {
  655. VALUE dupped = Map_dup(_self);
  656. return Map_merge_into_self(dupped, hashmap);
  657. }
  658. static int merge_into_self_callback(VALUE key, VALUE value, VALUE self) {
  659. Map_index_set(self, key, value);
  660. return ST_CONTINUE;
  661. }
  662. // Used only internally -- shared by #merge and #initialize.
  663. VALUE Map_merge_into_self(VALUE _self, VALUE hashmap) {
  664. if (TYPE(hashmap) == T_HASH) {
  665. rb_hash_foreach(hashmap, merge_into_self_callback, _self);
  666. } else if (RB_TYPE_P(hashmap, T_DATA) && RTYPEDDATA_P(hashmap) &&
  667. RTYPEDDATA_TYPE(hashmap) == &Map_type) {
  668. Map* self = ruby_to_Map(_self);
  669. Map* other = ruby_to_Map(hashmap);
  670. upb_strtable_iter it;
  671. if (self->key_type != other->key_type ||
  672. self->value_type != other->value_type ||
  673. self->value_type_class != other->value_type_class) {
  674. rb_raise(rb_eArgError, "Attempt to merge Map with mismatching types");
  675. }
  676. for (upb_strtable_begin(&it, &other->table);
  677. !upb_strtable_done(&it);
  678. upb_strtable_next(&it)) {
  679. // Replace any existing value by issuing a 'remove' operation first.
  680. upb_value v;
  681. upb_value oldv;
  682. upb_strtable_remove2(&self->table,
  683. upb_strtable_iter_key(&it),
  684. upb_strtable_iter_keylength(&it),
  685. &oldv);
  686. v = upb_strtable_iter_value(&it);
  687. upb_strtable_insert2(&self->table,
  688. upb_strtable_iter_key(&it),
  689. upb_strtable_iter_keylength(&it),
  690. v);
  691. }
  692. } else {
  693. rb_raise(rb_eArgError, "Unknown type merging into Map");
  694. }
  695. return _self;
  696. }
  697. // Internal method: map iterator initialization (used for serialization).
  698. void Map_begin(VALUE _self, Map_iter* iter) {
  699. Map* self = ruby_to_Map(_self);
  700. iter->self = self;
  701. upb_strtable_begin(&iter->it, &self->table);
  702. }
  703. void Map_next(Map_iter* iter) {
  704. upb_strtable_next(&iter->it);
  705. }
  706. bool Map_done(Map_iter* iter) {
  707. return upb_strtable_done(&iter->it);
  708. }
  709. VALUE Map_iter_key(Map_iter* iter) {
  710. return table_key_to_ruby(
  711. iter->self,
  712. upb_strtable_iter_key(&iter->it),
  713. upb_strtable_iter_keylength(&iter->it));
  714. }
  715. VALUE Map_iter_value(Map_iter* iter) {
  716. upb_value v = upb_strtable_iter_value(&iter->it);
  717. void* mem = value_memory(&v);
  718. return native_slot_get(iter->self->value_type,
  719. iter->self->value_type_class,
  720. mem);
  721. }
  722. void Map_register(VALUE module) {
  723. VALUE klass = rb_define_class_under(module, "Map", rb_cObject);
  724. rb_define_alloc_func(klass, Map_alloc);
  725. rb_gc_register_address(&cMap);
  726. cMap = klass;
  727. rb_define_method(klass, "initialize", Map_init, -1);
  728. rb_define_method(klass, "each", Map_each, 0);
  729. rb_define_method(klass, "keys", Map_keys, 0);
  730. rb_define_method(klass, "values", Map_values, 0);
  731. rb_define_method(klass, "[]", Map_index, 1);
  732. rb_define_method(klass, "[]=", Map_index_set, 2);
  733. rb_define_method(klass, "has_key?", Map_has_key, 1);
  734. rb_define_method(klass, "delete", Map_delete, 1);
  735. rb_define_method(klass, "clear", Map_clear, 0);
  736. rb_define_method(klass, "length", Map_length, 0);
  737. rb_define_method(klass, "dup", Map_dup, 0);
  738. rb_define_method(klass, "==", Map_eq, 1);
  739. rb_define_method(klass, "hash", Map_hash, 0);
  740. rb_define_method(klass, "to_h", Map_to_h, 0);
  741. rb_define_method(klass, "inspect", Map_inspect, 0);
  742. rb_define_method(klass, "merge", Map_merge, 1);
  743. rb_include_module(klass, rb_mEnumerable);
  744. }