map.c 27 KB

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