Merge pull request #1039 from crimsonwoods/fix_the_type_of_opcode
[mruby.git] / src / hash.c
blob6976530e143330cf672febc717dfd435eea115d8
1 /*
2 ** hash.c - Hash class
3 **
4 ** See Copyright Notice in mruby.h
5 */
7 #include "mruby.h"
8 #include "mruby/hash.h"
9 #include "mruby/khash.h"
10 #include "mruby/class.h"
11 #include "mruby/array.h"
12 #include "mruby/string.h"
13 #include "mruby/variable.h"
15 static inline khint_t
16 mrb_hash_ht_hash_func(mrb_state *mrb, mrb_value key)
18 khint_t h = (khint_t)mrb_type(key) << 24;
19 mrb_value h2;
21 h2 = mrb_funcall(mrb, key, "hash", 0, 0);
22 h ^= h2.value.i;
23 return h;
26 static inline khint_t
27 mrb_hash_ht_hash_equal(mrb_state *mrb, mrb_value a, mrb_value b)
29 return mrb_eql(mrb, a, b);
32 KHASH_DECLARE(ht, mrb_value, mrb_value, 1)
33 KHASH_DEFINE (ht, mrb_value, mrb_value, 1, mrb_hash_ht_hash_func, mrb_hash_ht_hash_equal)
35 static void mrb_hash_modify(mrb_state *mrb, mrb_value hash);
37 static inline mrb_value
38 mrb_hash_ht_key(mrb_state *mrb, mrb_value key)
40 if (mrb_string_p(key))
41 return mrb_str_dup(mrb, key);
42 else
43 return key;
46 #define KEY(key) mrb_hash_ht_key(mrb, key)
48 void
49 mrb_gc_mark_ht(mrb_state *mrb, struct RHash *hash)
51 khiter_t k;
52 khash_t(ht) *h = hash->ht;
54 if (!h) return;
55 for (k = kh_begin(h); k != kh_end(h); k++) {
56 if (kh_exist(h, k)) {
57 mrb_value key = kh_key(h, k);
58 mrb_value val = kh_value(h, k);
60 mrb_gc_mark_value(mrb, key);
61 mrb_gc_mark_value(mrb, val);
66 size_t
67 mrb_gc_mark_ht_size(mrb_state *mrb, struct RHash *hash)
69 if (!hash->ht) return 0;
70 return kh_size(hash->ht)*2;
73 void
74 mrb_gc_free_ht(mrb_state *mrb, struct RHash *hash)
76 if (hash->ht) kh_destroy(ht, hash->ht);
80 mrb_value
81 mrb_hash_new_capa(mrb_state *mrb, int capa)
83 struct RHash *h;
85 h = (struct RHash*)mrb_obj_alloc(mrb, MRB_TT_HASH, mrb->hash_class);
86 h->ht = kh_init(ht, mrb);
87 if (capa > 0) {
88 kh_resize(ht, h->ht, capa);
90 h->iv = 0;
91 return mrb_obj_value(h);
94 mrb_value
95 mrb_hash_new(mrb_state *mrb)
97 return mrb_hash_new_capa(mrb, 0);
100 mrb_value
101 mrb_hash_get(mrb_state *mrb, mrb_value hash, mrb_value key)
103 khash_t(ht) *h = RHASH_TBL(hash);
104 khiter_t k;
106 if (h) {
107 k = kh_get(ht, h, key);
108 if (k != kh_end(h))
109 return kh_value(h, k);
112 /* not found */
113 if (MRB_RHASH_PROCDEFAULT_P(hash)) {
114 return mrb_funcall(mrb, RHASH_PROCDEFAULT(hash), "call", 2, hash, key);
116 return RHASH_IFNONE(hash);
119 mrb_value
120 mrb_hash_fetch(mrb_state *mrb, mrb_value hash, mrb_value key, mrb_value def)
122 khash_t(ht) *h = RHASH_TBL(hash);
123 khiter_t k;
125 if (h) {
126 k = kh_get(ht, h, key);
127 if (k != kh_end(h))
128 return kh_value(h, k);
131 /* not found */
132 return def;
135 void
136 mrb_hash_set(mrb_state *mrb, mrb_value hash, mrb_value key, mrb_value val) /* mrb_hash_aset */
138 khash_t(ht) *h;
139 khiter_t k;
141 mrb_hash_modify(mrb, hash);
142 h = RHASH_TBL(hash);
144 if (!h) h = RHASH_TBL(hash) = kh_init(ht, mrb);
145 k = kh_get(ht, h, key);
146 if (k == kh_end(h)) {
147 /* expand */
148 k = kh_put(ht, h, KEY(key));
151 kh_value(h, k) = val;
152 mrb_write_barrier(mrb, (struct RBasic*)RHASH(hash));
153 return;
156 mrb_value
157 mrb_hash_dup(mrb_state *mrb, mrb_value hash)
159 struct RHash* ret;
160 khash_t(ht) *h, *ret_h;
161 khiter_t k, ret_k;
163 h = RHASH_TBL(hash);
164 ret = (struct RHash*)mrb_obj_alloc(mrb, MRB_TT_HASH, mrb->hash_class);
165 ret->ht = kh_init(ht, mrb);
167 if (kh_size(h) > 0) {
168 ret_h = ret->ht;
170 for (k = kh_begin(h); k != kh_end(h); k++) {
171 if (kh_exist(h,k)) {
172 ret_k = kh_put(ht, ret_h, KEY(kh_key(h,k)));
173 kh_val(ret_h, ret_k) = kh_val(h,k);
178 return mrb_obj_value(ret);
181 mrb_value
182 mrb_check_hash_type(mrb_state *mrb, mrb_value hash)
184 return mrb_check_convert_type(mrb, hash, MRB_TT_HASH, "Hash", "to_hash");
187 khash_t(ht) *
188 mrb_hash_tbl(mrb_state *mrb, mrb_value hash)
190 khash_t(ht) *h = RHASH_TBL(hash);
192 if (!h) {
193 RHASH_TBL(hash) = kh_init(ht, mrb);
195 return h;
198 static void
199 mrb_hash_modify(mrb_state *mrb, mrb_value hash)
201 mrb_hash_tbl(mrb, hash);
204 /* 15.2.13.4.16 */
206 * call-seq:
207 * Hash.new -> new_hash
208 * Hash.new(obj) -> new_hash
209 * Hash.new {|hash, key| block } -> new_hash
211 * Returns a new, empty hash. If this hash is subsequently accessed by
212 * a key that doesn't correspond to a hash entry, the value returned
213 * depends on the style of <code>new</code> used to create the hash. In
214 * the first form, the access returns <code>nil</code>. If
215 * <i>obj</i> is specified, this single object will be used for
216 * all <em>default values</em>. If a block is specified, it will be
217 * called with the hash object and the key, and should return the
218 * default value. It is the block's responsibility to store the value
219 * in the hash if required.
221 * h = Hash.new("Go Fish")
222 * h["a"] = 100
223 * h["b"] = 200
224 * h["a"] #=> 100
225 * h["c"] #=> "Go Fish"
226 * # The following alters the single default object
227 * h["c"].upcase! #=> "GO FISH"
228 * h["d"] #=> "GO FISH"
229 * h.keys #=> ["a", "b"]
231 * # While this creates a new default object each time
232 * h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
233 * h["c"] #=> "Go Fish: c"
234 * h["c"].upcase! #=> "GO FISH: C"
235 * h["d"] #=> "Go Fish: d"
236 * h.keys #=> ["c", "d"]
240 static mrb_value
241 mrb_hash_init_core(mrb_state *mrb, mrb_value hash)
243 mrb_value block, ifnone;
244 mrb_value *argv;
245 int argc;
247 mrb_get_args(mrb, "o*", &block, &argv, &argc);
248 mrb_hash_modify(mrb, hash);
249 if (mrb_nil_p(block)) {
250 if (argc > 0) {
251 if (argc != 1) mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments");
252 ifnone = argv[0];
254 else {
255 ifnone = mrb_nil_value();
258 else {
259 if (argc > 0) {
260 mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments");
262 RHASH(hash)->flags |= MRB_HASH_PROC_DEFAULT;
263 ifnone = block;
265 mrb_iv_set(mrb, hash, mrb_intern2(mrb, "ifnone", 6), ifnone);
266 return hash;
270 * call-seq:
271 * Hash[ key, value, ... ] -> new_hash
272 * Hash[ [ [key, value], ... ] ] -> new_hash
273 * Hash[ object ] -> new_hash
275 * Creates a new hash populated with the given objects. Equivalent to
276 * the literal <code>{ <i>key</i> => <i>value</i>, ... }</code>. In the first
277 * form, keys and values occur in pairs, so there must be an even number of arguments.
278 * The second and third form take a single argument which is either
279 * an array of key-value pairs or an object convertible to a hash.
281 * Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
282 * Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200}
283 * Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}
286 static mrb_value
287 to_hash(mrb_state *mrb, mrb_value hash)
289 return mrb_convert_type(mrb, hash, MRB_TT_HASH, "Hash", "to_hash");
293 * call-seq:
294 * Hash.try_convert(obj) -> hash or nil
296 * Try to convert <i>obj</i> into a hash, using to_hash method.
297 * Returns converted hash or nil if <i>obj</i> cannot be converted
298 * for any reason.
300 * Hash.try_convert({1=>2}) # => {1=>2}
301 * Hash.try_convert("1=>2") # => nil
304 /* 15.2.13.4.2 */
306 * call-seq:
307 * hsh[key] -> value
309 * Element Reference---Retrieves the <i>value</i> object corresponding
310 * to the <i>key</i> object. If not found, returns the default value (see
311 * <code>Hash::new</code> for details).
313 * h = { "a" => 100, "b" => 200 }
314 * h["a"] #=> 100
315 * h["c"] #=> nil
318 mrb_value
319 mrb_hash_aget(mrb_state *mrb, mrb_value self)
321 mrb_value key;
323 mrb_get_args(mrb, "o", &key);
324 return mrb_hash_get(mrb, self, key);
327 mrb_value
328 mrb_hash_lookup(mrb_state *mrb, mrb_value hash, mrb_value key)
330 return mrb_hash_get(mrb, hash, key);
334 * call-seq:
335 * hsh.fetch(key [, default] ) -> obj
336 * hsh.fetch(key) {| key | block } -> obj
338 * Returns a value from the hash for the given key. If the key can't be
339 * found, there are several options: With no other arguments, it will
340 * raise an <code>KeyError</code> exception; if <i>default</i> is
341 * given, then that will be returned; if the optional code block is
342 * specified, then that will be run and its result returned.
344 * h = { "a" => 100, "b" => 200 }
345 * h.fetch("a") #=> 100
346 * h.fetch("z", "go fish") #=> "go fish"
347 * h.fetch("z") { |el| "go fish, #{el}"} #=> "go fish, z"
349 * The following example shows that an exception is raised if the key
350 * is not found and a default value is not supplied.
352 * h = { "a" => 100, "b" => 200 }
353 * h.fetch("z")
355 * <em>produces:</em>
357 * prog.rb:2:in `fetch': key not found (KeyError)
358 * from prog.rb:2
362 /* 15.2.13.4.5 */
364 * call-seq:
365 * hsh.default(key=nil) -> obj
367 * Returns the default value, the value that would be returned by
368 * <i>hsh</i>[<i>key</i>] if <i>key</i> did not exist in <i>hsh</i>.
369 * See also <code>Hash::new</code> and <code>Hash#default=</code>.
371 * h = Hash.new #=> {}
372 * h.default #=> nil
373 * h.default(2) #=> nil
375 * h = Hash.new("cat") #=> {}
376 * h.default #=> "cat"
377 * h.default(2) #=> "cat"
379 * h = Hash.new {|h,k| h[k] = k.to_i*10} #=> {}
380 * h.default #=> nil
381 * h.default(2) #=> 20
384 static mrb_value
385 mrb_hash_default(mrb_state *mrb, mrb_value hash)
387 mrb_value *argv;
388 int argc;
389 mrb_value key;
391 mrb_get_args(mrb, "*", &argv, &argc);
392 if (MRB_RHASH_PROCDEFAULT_P(hash)) {
393 if (argc == 0) return mrb_nil_value();
394 key = argv[0];
395 return mrb_funcall(mrb, RHASH_PROCDEFAULT(hash), "call", 2, hash, key);
397 else {
398 return RHASH_IFNONE(hash);
402 /* 15.2.13.4.6 */
404 * call-seq:
405 * hsh.default = obj -> obj
407 * Sets the default value, the value returned for a key that does not
408 * exist in the hash. It is not possible to set the default to a
409 * <code>Proc</code> that will be executed on each key lookup.
411 * h = { "a" => 100, "b" => 200 }
412 * h.default = "Go fish"
413 * h["a"] #=> 100
414 * h["z"] #=> "Go fish"
415 * # This doesn't do what you might hope...
416 * h.default = proc do |hash, key|
417 * hash[key] = key + key
418 * end
419 * h[2] #=> #<Proc:0x401b3948@-:6>
420 * h["cat"] #=> #<Proc:0x401b3948@-:6>
423 static mrb_value
424 mrb_hash_set_default(mrb_state *mrb, mrb_value hash)
426 mrb_value ifnone;
428 mrb_get_args(mrb, "o", &ifnone);
429 mrb_hash_modify(mrb, hash);
430 mrb_iv_set(mrb, hash, mrb_intern2(mrb, "ifnone", 6), ifnone);
431 RHASH(hash)->flags &= ~(MRB_HASH_PROC_DEFAULT);
433 return ifnone;
436 /* 15.2.13.4.7 */
438 * call-seq:
439 * hsh.default_proc -> anObject
441 * If <code>Hash::new</code> was invoked with a block, return that
442 * block, otherwise return <code>nil</code>.
444 * h = Hash.new {|h,k| h[k] = k*k } #=> {}
445 * p = h.default_proc #=> #<Proc:0x401b3d08@-:1>
446 * a = [] #=> []
447 * p.call(a, 2)
448 * a #=> [nil, nil, 4]
452 static mrb_value
453 mrb_hash_default_proc(mrb_state *mrb, mrb_value hash)
455 if (MRB_RHASH_PROCDEFAULT_P(hash)) {
456 return RHASH_PROCDEFAULT(hash);
458 return mrb_nil_value();
462 * call-seq:
463 * hsh.default_proc = proc_obj -> proc_obj
465 * Sets the default proc to be executed on each key lookup.
467 * h.default_proc = proc do |hash, key|
468 * hash[key] = key + key
469 * end
470 * h[2] #=> 4
471 * h["cat"] #=> "catcat"
474 static mrb_value
475 mrb_hash_set_default_proc(mrb_state *mrb, mrb_value hash)
477 mrb_value ifnone;
479 mrb_get_args(mrb, "o", &ifnone);
480 mrb_hash_modify(mrb, hash);
481 mrb_iv_set(mrb, hash, mrb_intern2(mrb, "ifnone", 6), ifnone);
482 RHASH(hash)->flags |= MRB_HASH_PROC_DEFAULT;
484 return ifnone;
487 mrb_value
488 mrb_hash_delete_key(mrb_state *mrb, mrb_value hash, mrb_value key)
490 khash_t(ht) *h = RHASH_TBL(hash);
491 khiter_t k;
492 mrb_value delVal;
494 if (h) {
495 k = kh_get(ht, h, key);
496 if (k != kh_end(h)) {
497 delVal = kh_value(h, k);
498 kh_del(ht, h, k);
499 return delVal;
503 /* not found */
504 return mrb_nil_value();
507 /* 15.2.13.4.8 */
509 * call-seq:
510 * hsh.delete(key) -> value
511 * hsh.delete(key) {| key | block } -> value
513 * Deletes and returns a key-value pair from <i>hsh</i> whose key is
514 * equal to <i>key</i>. If the key is not found, returns the
515 * <em>default value</em>. If the optional code block is given and the
516 * key is not found, pass in the key and return the result of
517 * <i>block</i>.
519 * h = { "a" => 100, "b" => 200 }
520 * h.delete("a") #=> 100
521 * h.delete("z") #=> nil
522 * h.delete("z") { |el| "#{el} not found" } #=> "z not found"
525 mrb_value
526 mrb_hash_delete(mrb_state *mrb, mrb_value self)
528 mrb_value key;
530 mrb_get_args(mrb, "o", &key);
531 return mrb_hash_delete_key(mrb, self, key);
534 /* 15.2.13.4.24 */
536 * call-seq:
537 * hsh.shift -> anArray or obj
539 * Removes a key-value pair from <i>hsh</i> and returns it as the
540 * two-item array <code>[</code> <i>key, value</i> <code>]</code>, or
541 * the hash's default value if the hash is empty.
543 * h = { 1 => "a", 2 => "b", 3 => "c" }
544 * h.shift #=> [1, "a"]
545 * h #=> {2=>"b", 3=>"c"}
548 static mrb_value
549 mrb_hash_shift(mrb_state *mrb, mrb_value hash)
551 khash_t(ht) *h = RHASH_TBL(hash);
552 khiter_t k;
553 mrb_value delKey, delVal;
555 mrb_hash_modify(mrb, hash);
556 if (h) {
557 if (kh_size(h) > 0) {
558 for (k = kh_begin(h); k != kh_end(h); k++) {
559 if (!kh_exist(h,k)) continue;
561 delKey = kh_key(h,k);
562 mrb_gc_protect(mrb, delKey);
563 delVal = mrb_hash_delete_key(mrb, hash, delKey);
564 mrb_gc_protect(mrb, delVal);
566 return mrb_assoc_new(mrb, delKey, delVal);
571 if (MRB_RHASH_PROCDEFAULT_P(hash)) {
572 return mrb_funcall(mrb, RHASH_PROCDEFAULT(hash), "call", 2, hash, mrb_nil_value());
574 else {
575 return RHASH_IFNONE(hash);
580 * call-seq:
581 * hsh.delete_if {| key, value | block } -> hsh
582 * hsh.delete_if -> an_enumerator
584 * Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
585 * evaluates to <code>true</code>.
587 * If no block is given, an enumerator is returned instead.
589 * h = { "a" => 100, "b" => 200, "c" => 300 }
590 * h.delete_if {|key, value| key >= "b" } #=> {"a"=>100}
595 * call-seq:
596 * hsh.reject! {| key, value | block } -> hsh or nil
597 * hsh.reject! -> an_enumerator
599 * Equivalent to <code>Hash#delete_if</code>, but returns
600 * <code>nil</code> if no changes were made.
604 * call-seq:
605 * hsh.reject {| key, value | block } -> a_hash
607 * Same as <code>Hash#delete_if</code>, but works on (and returns) a
608 * copy of the <i>hsh</i>. Equivalent to
609 * <code><i>hsh</i>.dup.delete_if</code>.
614 * call-seq:
615 * hsh.values_at(key, ...) -> array
617 * Return an array containing the values associated with the given keys.
618 * Also see <code>Hash.select</code>.
620 * h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
621 * h.values_at("cow", "cat") #=> ["bovine", "feline"]
624 mrb_value
625 mrb_hash_values_at(mrb_state *mrb, int argc, mrb_value *argv, mrb_value hash)
627 mrb_value result = mrb_ary_new_capa(mrb, argc);
628 long i;
630 for (i=0; i<argc; i++) {
631 mrb_ary_push(mrb, result, mrb_hash_get(mrb, hash, argv[i]));
633 return result;
637 * call-seq:
638 * hsh.select {|key, value| block} -> a_hash
639 * hsh.select -> an_enumerator
641 * Returns a new hash consisting of entries for which the block returns true.
643 * If no block is given, an enumerator is returned instead.
645 * h = { "a" => 100, "b" => 200, "c" => 300 }
646 * h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300}
647 * h.select {|k,v| v < 200} #=> {"a" => 100}
651 * call-seq:
652 * hsh.select! {| key, value | block } -> hsh or nil
653 * hsh.select! -> an_enumerator
655 * Equivalent to <code>Hash#keep_if</code>, but returns
656 * <code>nil</code> if no changes were made.
660 * call-seq:
661 * hsh.keep_if {| key, value | block } -> hsh
662 * hsh.keep_if -> an_enumerator
664 * Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
665 * evaluates to false.
667 * If no block is given, an enumerator is returned instead.
671 /* 15.2.13.4.4 */
673 * call-seq:
674 * hsh.clear -> hsh
676 * Removes all key-value pairs from <i>hsh</i>.
678 * h = { "a" => 100, "b" => 200 } #=> {"a"=>100, "b"=>200}
679 * h.clear #=> {}
683 static mrb_value
684 mrb_hash_clear(mrb_state *mrb, mrb_value hash)
686 khash_t(ht) *h = RHASH_TBL(hash);
688 if (h) kh_clear(ht, h);
689 return hash;
692 /* 15.2.13.4.3 */
693 /* 15.2.13.4.26 */
695 * call-seq:
696 * hsh[key] = value -> value
697 * hsh.store(key, value) -> value
699 * Element Assignment---Associates the value given by
700 * <i>value</i> with the key given by <i>key</i>.
701 * <i>key</i> should not have its value changed while it is in
702 * use as a key (a <code>String</code> passed as a key will be
703 * duplicated and frozen).
705 * h = { "a" => 100, "b" => 200 }
706 * h["a"] = 9
707 * h["c"] = 4
708 * h #=> {"a"=>9, "b"=>200, "c"=>4}
711 mrb_value
712 mrb_hash_aset(mrb_state *mrb, mrb_value self)
714 mrb_value key, val;
716 mrb_get_args(mrb, "oo", &key, &val);
717 mrb_hash_set(mrb, self, key, val);
718 return val;
721 /* 15.2.13.4.17 */
722 /* 15.2.13.4.23 */
724 * call-seq:
725 * hsh.replace(other_hash) -> hsh
727 * Replaces the contents of <i>hsh</i> with the contents of
728 * <i>other_hash</i>.
730 * h = { "a" => 100, "b" => 200 }
731 * h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400}
735 static mrb_value
736 mrb_hash_replace(mrb_state *mrb, mrb_value hash)
738 mrb_value hash2, ifnone;
739 khash_t(ht) *h2;
740 khiter_t k;
742 mrb_get_args(mrb, "o", &hash2);
743 hash2 = to_hash(mrb, hash2);
744 if (mrb_obj_equal(mrb, hash, hash2)) return hash;
745 mrb_hash_clear(mrb, hash);
747 h2 = RHASH_TBL(hash2);
748 if (h2) {
749 for (k = kh_begin(h2); k != kh_end(h2); k++) {
750 if (kh_exist(h2, k))
751 mrb_hash_set(mrb, hash, kh_key(h2, k), kh_value(h2, k));
755 if (MRB_RHASH_PROCDEFAULT_P(hash2)) {
756 RHASH(hash)->flags |= MRB_HASH_PROC_DEFAULT;
757 ifnone = RHASH_PROCDEFAULT(hash2);
759 else {
760 ifnone = RHASH_IFNONE(hash2);
762 mrb_iv_set(mrb, hash, mrb_intern2(mrb, "ifnone", 6), ifnone);
764 return hash;
767 /* 15.2.13.4.20 */
768 /* 15.2.13.4.25 */
770 * call-seq:
771 * hsh.length -> fixnum
772 * hsh.size -> fixnum
774 * Returns the number of key-value pairs in the hash.
776 * h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
777 * h.length #=> 4
778 * h.delete("a") #=> 200
779 * h.length #=> 3
781 static mrb_value
782 mrb_hash_size_m(mrb_state *mrb, mrb_value self)
784 khash_t(ht) *h = RHASH_TBL(self);
786 if (!h) return mrb_fixnum_value(0);
787 return mrb_fixnum_value(kh_size(h));
790 /* 15.2.13.4.12 */
792 * call-seq:
793 * hsh.empty? -> true or false
795 * Returns <code>true</code> if <i>hsh</i> contains no key-value pairs.
797 * {}.empty? #=> true
800 static mrb_value
801 mrb_hash_empty_p(mrb_state *mrb, mrb_value self)
803 khash_t(ht) *h = RHASH_TBL(self);
804 mrb_bool empty_p;
806 if (h) {
807 empty_p = (kh_size(h) == 0);
809 else {
810 empty_p = 1;
813 return mrb_bool_value(empty_p);
816 /* 15.2.13.4.11 */
818 * call-seq:
819 * hsh.each_value {| value | block } -> hsh
820 * hsh.each_value -> an_enumerator
822 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the
823 * value as a parameter.
825 * If no block is given, an enumerator is returned instead.
827 * h = { "a" => 100, "b" => 200 }
828 * h.each_value {|value| puts value }
830 * <em>produces:</em>
832 * 100
833 * 200
836 /* 15.2.13.4.10 */
838 * call-seq:
839 * hsh.each_key {| key | block } -> hsh
840 * hsh.each_key -> an_enumerator
842 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
843 * as a parameter.
845 * If no block is given, an enumerator is returned instead.
847 * h = { "a" => 100, "b" => 200 }
848 * h.each_key {|key| puts key }
850 * <em>produces:</em>
856 /* 15.2.13.4.9 */
858 * call-seq:
859 * hsh.each {| key, value | block } -> hsh
860 * hsh.each_pair {| key, value | block } -> hsh
861 * hsh.each -> an_enumerator
862 * hsh.each_pair -> an_enumerator
864 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the key-value
865 * pair as parameters.
867 * If no block is given, an enumerator is returned instead.
869 * h = { "a" => 100, "b" => 200 }
870 * h.each {|key, value| puts "#{key} is #{value}" }
872 * <em>produces:</em>
874 * a is 100
875 * b is 200
879 static mrb_value
880 inspect_hash(mrb_state *mrb, mrb_value hash, int recur)
882 mrb_value str, str2;
883 khash_t(ht) *h = RHASH_TBL(hash);
884 khiter_t k;
886 if (recur) return mrb_str_new(mrb, "{...}", 5);
888 str = mrb_str_new(mrb, "{", 1);
889 if (h && kh_size(h) > 0) {
890 for (k = kh_begin(h); k != kh_end(h); k++) {
891 int ai;
893 if (!kh_exist(h,k)) continue;
895 ai = mrb_gc_arena_save(mrb);
897 if (RSTRING_LEN(str) > 1) mrb_str_cat2(mrb, str, ", ");
899 str2 = mrb_inspect(mrb, kh_key(h,k));
900 mrb_str_append(mrb, str, str2);
901 mrb_str_buf_cat(mrb, str, "=>", 2);
902 str2 = mrb_inspect(mrb, kh_value(h,k));
903 mrb_str_append(mrb, str, str2);
905 mrb_gc_arena_restore(mrb, ai);
908 mrb_str_buf_cat(mrb, str, "}", 1);
910 return str;
913 /* 15.2.13.4.30 (x)*/
915 * call-seq:
916 * hsh.to_s -> string
917 * hsh.inspect -> string
919 * Return the contents of this hash as a string.
921 * h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
922 * h.to_s #=> "{\"c\"=>300, \"a\"=>100, \"d\"=>400}"
925 static mrb_value
926 mrb_hash_inspect(mrb_state *mrb, mrb_value hash)
928 khash_t(ht) *h = RHASH_TBL(hash);
930 if (!h || kh_size(h) == 0)
931 return mrb_str_new(mrb, "{}", 2);
932 return inspect_hash(mrb, hash, 0);
935 /* 15.2.13.4.29 (x)*/
937 * call-seq:
938 * hsh.to_hash => hsh
940 * Returns +self+.
943 static mrb_value
944 mrb_hash_to_hash(mrb_state *mrb, mrb_value hash)
946 return hash;
949 /* 15.2.13.4.19 */
951 * call-seq:
952 * hsh.keys -> array
954 * Returns a new array populated with the keys from this hash. See also
955 * <code>Hash#values</code>.
957 * h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }
958 * h.keys #=> ["a", "b", "c", "d"]
962 mrb_value
963 mrb_hash_keys(mrb_state *mrb, mrb_value hash)
965 khash_t(ht) *h = RHASH_TBL(hash);
966 khiter_t k;
967 mrb_value ary;
969 if (!h) return mrb_ary_new(mrb);
970 ary = mrb_ary_new_capa(mrb, kh_size(h));
971 for (k = kh_begin(h); k != kh_end(h); k++) {
972 if (kh_exist(h, k)) {
973 mrb_value v = kh_key(h,k);
974 mrb_ary_push(mrb, ary, v);
977 return ary;
980 /* 15.2.13.4.28 */
982 * call-seq:
983 * hsh.values -> array
985 * Returns a new array populated with the values from <i>hsh</i>. See
986 * also <code>Hash#keys</code>.
988 * h = { "a" => 100, "b" => 200, "c" => 300 }
989 * h.values #=> [100, 200, 300]
993 static mrb_value
994 mrb_hash_values(mrb_state *mrb, mrb_value hash)
996 khash_t(ht) *h = RHASH_TBL(hash);
997 khiter_t k;
998 mrb_value ary;
1000 if (!h) return mrb_ary_new(mrb);
1001 ary = mrb_ary_new_capa(mrb, kh_size(h));
1002 for (k = kh_begin(h); k != kh_end(h); k++) {
1003 if (kh_exist(h, k)){
1004 mrb_value v = kh_value(h,k);
1005 mrb_ary_push(mrb, ary, v);
1008 return ary;
1011 static mrb_value
1012 mrb_hash_has_keyWithKey(mrb_state *mrb, mrb_value hash, mrb_value key)
1014 khash_t(ht) *h = RHASH_TBL(hash);
1015 khiter_t k;
1016 mrb_bool result;
1018 if (h) {
1019 k = kh_get(ht, h, key);
1020 result = (k != kh_end(h));
1022 else {
1023 result = 0;
1026 return mrb_bool_value(result);
1029 /* 15.2.13.4.13 */
1030 /* 15.2.13.4.15 */
1031 /* 15.2.13.4.18 */
1032 /* 15.2.13.4.21 */
1034 * call-seq:
1035 * hsh.has_key?(key) -> true or false
1036 * hsh.include?(key) -> true or false
1037 * hsh.key?(key) -> true or false
1038 * hsh.member?(key) -> true or false
1040 * Returns <code>true</code> if the given key is present in <i>hsh</i>.
1042 * h = { "a" => 100, "b" => 200 }
1043 * h.has_key?("a") #=> true
1044 * h.has_key?("z") #=> false
1048 static mrb_value
1049 mrb_hash_has_key(mrb_state *mrb, mrb_value hash)
1051 mrb_value key;
1053 mrb_get_args(mrb, "o", &key);
1054 return mrb_hash_has_keyWithKey(mrb, hash, key);
1057 static mrb_value
1058 mrb_hash_has_valueWithvalue(mrb_state *mrb, mrb_value hash, mrb_value value)
1060 khash_t(ht) *h = RHASH_TBL(hash);
1061 khiter_t k;
1063 if (h) {
1064 for (k = kh_begin(h); k != kh_end(h); k++) {
1065 if (!kh_exist(h, k)) continue;
1067 if (mrb_equal(mrb, kh_value(h,k), value)) {
1068 return mrb_true_value();
1073 return mrb_false_value();
1076 /* 15.2.13.4.14 */
1077 /* 15.2.13.4.27 */
1079 * call-seq:
1080 * hsh.has_value?(value) -> true or false
1081 * hsh.value?(value) -> true or false
1083 * Returns <code>true</code> if the given value is present for some key
1084 * in <i>hsh</i>.
1086 * h = { "a" => 100, "b" => 200 }
1087 * h.has_value?(100) #=> true
1088 * h.has_value?(999) #=> false
1091 static mrb_value
1092 mrb_hash_has_value(mrb_state *mrb, mrb_value hash)
1094 mrb_value val;
1096 mrb_get_args(mrb, "o", &val);
1097 return mrb_hash_has_valueWithvalue(mrb, hash, val);
1100 static mrb_value
1101 hash_equal(mrb_state *mrb, mrb_value hash1, mrb_value hash2, int eql)
1103 khash_t(ht) *h1, *h2;
1105 if (mrb_obj_equal(mrb, hash1, hash2)) return mrb_true_value();
1106 if (!mrb_hash_p(hash2)) {
1107 if (!mrb_respond_to(mrb, hash2, mrb_intern2(mrb, "to_hash", 7))) {
1108 return mrb_false_value();
1110 if (eql)
1111 return mrb_fixnum_value(mrb_eql(mrb, hash2, hash1));
1112 else
1113 return mrb_fixnum_value(mrb_equal(mrb, hash2, hash1));
1115 h1 = RHASH_TBL(hash1);
1116 h2 = RHASH_TBL(hash2);
1117 if (!h1) {
1118 return mrb_bool_value(!h2);
1120 if (!h2) return mrb_false_value();
1121 if (kh_size(h1) != kh_size(h2)) return mrb_false_value();
1122 else {
1123 khiter_t k1, k2;
1124 mrb_value key;
1126 for (k1 = kh_begin(h1); k1 != kh_end(h1); k1++) {
1127 if (!kh_exist(h1, k1)) continue;
1128 key = kh_key(h1,k1);
1129 k2 = kh_get(ht, h2, key);
1130 if (k2 != kh_end(h2)) {
1131 if (mrb_equal(mrb, kh_value(h1,k1), kh_value(h2,k2))) {
1132 continue; /* next key */
1135 return mrb_false_value();
1138 return mrb_true_value();
1141 /* 15.2.13.4.1 */
1143 * call-seq:
1144 * hsh == other_hash -> true or false
1146 * Equality---Two hashes are equal if they each contain the same number
1147 * of keys and if each key-value pair is equal to (according to
1148 * <code>Object#==</code>) the corresponding elements in the other
1149 * hash.
1151 * h1 = { "a" => 1, "c" => 2 }
1152 * h2 = { 7 => 35, "c" => 2, "a" => 1 }
1153 * h3 = { "a" => 1, "c" => 2, 7 => 35 }
1154 * h4 = { "a" => 1, "d" => 2, "f" => 35 }
1155 * h1 == h2 #=> false
1156 * h2 == h3 #=> true
1157 * h3 == h4 #=> false
1161 static mrb_value
1162 mrb_hash_equal(mrb_state *mrb, mrb_value hash1)
1164 mrb_value hash2;
1166 mrb_get_args(mrb, "o", &hash2);
1167 return hash_equal(mrb, hash1, hash2, FALSE);
1170 /* 15.2.13.4.32 (x)*/
1172 * call-seq:
1173 * hash.eql?(other) -> true or false
1175 * Returns <code>true</code> if <i>hash</i> and <i>other</i> are
1176 * both hashes with the same content.
1179 static mrb_value
1180 mrb_hash_eql(mrb_state *mrb, mrb_value hash1)
1182 mrb_value hash2;
1184 mrb_get_args(mrb, "o", &hash2);
1185 return hash_equal(mrb, hash1, hash2, TRUE);
1189 * call-seq:
1190 * hsh.merge!(other_hash) -> hsh
1191 * hsh.update(other_hash) -> hsh
1192 * hsh.merge!(other_hash){|key, oldval, newval| block} -> hsh
1193 * hsh.update(other_hash){|key, oldval, newval| block} -> hsh
1195 * Adds the contents of <i>other_hash</i> to <i>hsh</i>. If no
1196 * block is specified, entries with duplicate keys are overwritten
1197 * with the values from <i>other_hash</i>, otherwise the value
1198 * of each duplicate key is determined by calling the block with
1199 * the key, its value in <i>hsh</i> and its value in <i>other_hash</i>.
1201 * h1 = { "a" => 100, "b" => 200 }
1202 * h2 = { "b" => 254, "c" => 300 }
1203 * h1.merge!(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
1205 * h1 = { "a" => 100, "b" => 200 }
1206 * h2 = { "b" => 254, "c" => 300 }
1207 * h1.merge!(h2) { |key, v1, v2| v1 }
1208 * #=> {"a"=>100, "b"=>200, "c"=>300}
1211 /* 15.2.13.4.22 */
1213 * call-seq:
1214 * hsh.merge(other_hash) -> new_hash
1215 * hsh.merge(other_hash){|key, oldval, newval| block} -> new_hash
1217 * Returns a new hash containing the contents of <i>other_hash</i> and
1218 * the contents of <i>hsh</i>. If no block is specified, the value for
1219 * entries with duplicate keys will be that of <i>other_hash</i>. Otherwise
1220 * the value for each duplicate key is determined by calling the block
1221 * with the key, its value in <i>hsh</i> and its value in <i>other_hash</i>.
1223 * h1 = { "a" => 100, "b" => 200 }
1224 * h2 = { "b" => 254, "c" => 300 }
1225 * h1.merge(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
1226 * h1.merge(h2){|key, oldval, newval| newval - oldval}
1227 * #=> {"a"=>100, "b"=>54, "c"=>300}
1228 * h1 #=> {"a"=>100, "b"=>200}
1233 * call-seq:
1234 * hash.assoc(obj) -> an_array or nil
1236 * Searches through the hash comparing _obj_ with the key using <code>==</code>.
1237 * Returns the key-value pair (two elements array) or +nil+
1238 * if no match is found. See <code>Array#assoc</code>.
1240 * h = {"colors" => ["red", "blue", "green"],
1241 * "letters" => ["a", "b", "c" ]}
1242 * h.assoc("letters") #=> ["letters", ["a", "b", "c"]]
1243 * h.assoc("foo") #=> nil
1246 mrb_value
1247 mrb_hash_assoc(mrb_state *mrb, mrb_value hash)
1249 mrb_value key, value, has_key;
1251 mrb_get_args(mrb, "o", &key);
1252 if (mrb_nil_p(key))
1253 mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments");
1255 has_key = mrb_hash_has_keyWithKey(mrb, hash, key);
1256 if (mrb_test(has_key)) {
1257 value = mrb_hash_get(mrb, hash, key);
1258 return mrb_assoc_new(mrb, key, value);
1260 else {
1261 return mrb_nil_value();
1266 * call-seq:
1267 * hash.rassoc(key) -> an_array or nil
1269 * Searches through the hash comparing _obj_ with the value using <code>==</code>.
1270 * Returns the first key-value pair (two-element array) that matches. See
1271 * also <code>Array#rassoc</code>.
1273 * a = {1=> "one", 2 => "two", 3 => "three", "ii" => "two"}
1274 * a.rassoc("two") #=> [2, "two"]
1275 * a.rassoc("four") #=> nil
1278 mrb_value
1279 mrb_hash_rassoc(mrb_state *mrb, mrb_value hash)
1281 mrb_value key, value, has_key;
1283 mrb_get_args(mrb, "o", &key);
1284 has_key = mrb_hash_has_keyWithKey(mrb, hash, key);
1285 if (mrb_test(has_key)) {
1286 value = mrb_hash_get(mrb, hash, key);
1287 return mrb_assoc_new(mrb, value, key);
1289 else {
1290 return mrb_nil_value();
1295 * call-seq:
1296 * hash.flatten -> an_array
1297 * hash.flatten(level) -> an_array
1299 * Returns a new array that is a one-dimensional flattening of this
1300 * hash. That is, for every key or value that is an array, extract
1301 * its elements into the new array. Unlike Array#flatten, this
1302 * method does not flatten recursively by default. The optional
1303 * <i>level</i> argument determines the level of recursion to flatten.
1305 * a = {1=> "one", 2 => [2,"two"], 3 => "three"}
1306 * a.flatten # => [1, "one", 2, [2, "two"], 3, "three"]
1307 * a.flatten(2) # => [1, "one", 2, 2, "two", 3, "three"]
1311 * A <code>Hash</code> is a collection of key-value pairs. It is
1312 * similar to an <code>Array</code>, except that indexing is done via
1313 * arbitrary keys of any object type, not an integer index. Hashes enumerate
1314 * their values in the order that the corresponding keys were inserted.
1316 * Hashes have a <em>default value</em> that is returned when accessing
1317 * keys that do not exist in the hash. By default, that value is
1318 * <code>nil</code>.
1322 void
1323 mrb_init_hash(mrb_state *mrb)
1325 struct RClass *h;
1327 h = mrb->hash_class = mrb_define_class(mrb, "Hash", mrb->object_class);
1328 MRB_SET_INSTANCE_TT(h, MRB_TT_HASH);
1330 mrb_include_module(mrb, h, mrb_class_get(mrb, "Enumerable"));
1331 mrb_define_method(mrb, h, "==", mrb_hash_equal, ARGS_REQ(1)); /* 15.2.13.4.1 */
1332 mrb_define_method(mrb, h, "[]", mrb_hash_aget, ARGS_REQ(1)); /* 15.2.13.4.2 */
1333 mrb_define_method(mrb, h, "[]=", mrb_hash_aset, ARGS_REQ(2)); /* 15.2.13.4.3 */
1334 mrb_define_method(mrb, h, "clear", mrb_hash_clear, ARGS_NONE()); /* 15.2.13.4.4 */
1335 mrb_define_method(mrb, h, "default", mrb_hash_default, ARGS_ANY()); /* 15.2.13.4.5 */
1336 mrb_define_method(mrb, h, "default=", mrb_hash_set_default, ARGS_REQ(1)); /* 15.2.13.4.6 */
1337 mrb_define_method(mrb, h, "default_proc", mrb_hash_default_proc,ARGS_NONE()); /* 15.2.13.4.7 */
1338 mrb_define_method(mrb, h, "default_proc=", mrb_hash_set_default_proc,ARGS_REQ(1)); /* 15.2.13.4.7 */
1339 mrb_define_method(mrb, h, "__delete", mrb_hash_delete, ARGS_REQ(1)); /* core of 15.2.13.4.8 */
1340 // "each" 15.2.13.4.9 move to mrblib/hash.rb
1341 // "each_key" 15.2.13.4.10 move to mrblib/hash.rb
1342 // "each_value" 15.2.13.4.11 move to mrblib/hash.rb
1343 mrb_define_method(mrb, h, "empty?", mrb_hash_empty_p, ARGS_NONE()); /* 15.2.13.4.12 */
1344 mrb_define_method(mrb, h, "has_key?", mrb_hash_has_key, ARGS_REQ(1)); /* 15.2.13.4.13 */
1345 mrb_define_method(mrb, h, "has_value?", mrb_hash_has_value, ARGS_REQ(1)); /* 15.2.13.4.14 */
1346 mrb_define_method(mrb, h, "include?", mrb_hash_has_key, ARGS_REQ(1)); /* 15.2.13.4.15 */
1347 mrb_define_method(mrb, h, "__init_core", mrb_hash_init_core, ARGS_ANY()); /* core of 15.2.13.4.16 */
1348 mrb_define_method(mrb, h, "initialize_copy", mrb_hash_replace, ARGS_REQ(1)); /* 15.2.13.4.17 */
1349 mrb_define_method(mrb, h, "key?", mrb_hash_has_key, ARGS_REQ(1)); /* 15.2.13.4.18 */
1350 mrb_define_method(mrb, h, "keys", mrb_hash_keys, ARGS_NONE()); /* 15.2.13.4.19 */
1351 mrb_define_method(mrb, h, "length", mrb_hash_size_m, ARGS_NONE()); /* 15.2.13.4.20 */
1352 mrb_define_method(mrb, h, "member?", mrb_hash_has_key, ARGS_REQ(1)); /* 15.2.13.4.21 */
1353 // "merge" 15.2.13.4.22 move to mrblib/hash.rb
1354 mrb_define_method(mrb, h, "replace", mrb_hash_replace, ARGS_REQ(1)); /* 15.2.13.4.23 */
1355 mrb_define_method(mrb, h, "shift", mrb_hash_shift, ARGS_NONE()); /* 15.2.13.4.24 */
1356 mrb_define_method(mrb, h, "size", mrb_hash_size_m, ARGS_NONE()); /* 15.2.13.4.25 */
1357 mrb_define_method(mrb, h, "store", mrb_hash_aset, ARGS_REQ(2)); /* 15.2.13.4.26 */
1358 mrb_define_method(mrb, h, "value?", mrb_hash_has_value, ARGS_REQ(1)); /* 15.2.13.4.27 */
1359 mrb_define_method(mrb, h, "values", mrb_hash_values, ARGS_NONE()); /* 15.2.13.4.28 */
1361 mrb_define_method(mrb, h, "to_hash", mrb_hash_to_hash, ARGS_NONE()); /* 15.2.13.4.29 (x)*/
1362 mrb_define_method(mrb, h, "inspect", mrb_hash_inspect, ARGS_NONE()); /* 15.2.13.4.30 (x)*/
1363 mrb_define_alias(mrb, h, "to_s", "inspect"); /* 15.2.13.4.31 (x)*/
1364 mrb_define_method(mrb, h, "eql?", mrb_hash_eql, ARGS_REQ(1)); /* 15.2.13.4.32 (x)*/