map.c 26 KB

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