* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / hash.c
blobf032ef642a153293bc6c77083db4e6f14128e07f
1 /**********************************************************************
3 hash.c -
5 $Author$
6 created at: Mon Nov 22 18:51:18 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/internal/config.h"
16 #include <errno.h>
18 #ifdef __APPLE__
19 # ifdef HAVE_CRT_EXTERNS_H
20 # include <crt_externs.h>
21 # else
22 # include "missing/crt_externs.h"
23 # endif
24 #endif
26 #include "debug_counter.h"
27 #include "id.h"
28 #include "internal.h"
29 #include "internal/array.h"
30 #include "internal/bignum.h"
31 #include "internal/class.h"
32 #include "internal/cont.h"
33 #include "internal/error.h"
34 #include "internal/hash.h"
35 #include "internal/object.h"
36 #include "internal/proc.h"
37 #include "internal/symbol.h"
38 #include "internal/time.h"
39 #include "internal/vm.h"
40 #include "probes.h"
41 #include "ruby/st.h"
42 #include "ruby/util.h"
43 #include "ruby_assert.h"
44 #include "symbol.h"
45 #include "transient_heap.h"
46 #include "ruby/thread_native.h"
47 #include "ruby/ractor.h"
48 #include "vm_sync.h"
50 #ifndef HASH_DEBUG
51 #define HASH_DEBUG 0
52 #endif
54 #if HASH_DEBUG
55 #include "gc.h"
56 #endif
58 #define SET_DEFAULT(hash, ifnone) ( \
59 FL_UNSET_RAW(hash, RHASH_PROC_DEFAULT), \
60 RHASH_SET_IFNONE(hash, ifnone))
62 #define SET_PROC_DEFAULT(hash, proc) set_proc_default(hash, proc)
64 #define COPY_DEFAULT(hash, hash2) copy_default(RHASH(hash), RHASH(hash2))
66 static inline void
67 copy_default(struct RHash *hash, const struct RHash *hash2)
69 hash->basic.flags &= ~RHASH_PROC_DEFAULT;
70 hash->basic.flags |= hash2->basic.flags & RHASH_PROC_DEFAULT;
71 RHASH_SET_IFNONE(hash, RHASH_IFNONE((VALUE)hash2));
74 static VALUE rb_hash_s_try_convert(VALUE, VALUE);
77 * Hash WB strategy:
78 * 1. Check mutate st_* functions
79 * * st_insert()
80 * * st_insert2()
81 * * st_update()
82 * * st_add_direct()
83 * 2. Insert WBs
86 VALUE
87 rb_hash_freeze(VALUE hash)
89 return rb_obj_freeze(hash);
92 VALUE rb_cHash;
94 static VALUE envtbl;
95 static ID id_hash, id_default, id_flatten_bang;
96 static ID id_hash_iter_lev;
98 VALUE
99 rb_hash_set_ifnone(VALUE hash, VALUE ifnone)
101 RB_OBJ_WRITE(hash, (&RHASH(hash)->ifnone), ifnone);
102 return hash;
105 static int
106 rb_any_cmp(VALUE a, VALUE b)
108 if (a == b) return 0;
109 if (RB_TYPE_P(a, T_STRING) && RBASIC(a)->klass == rb_cString &&
110 RB_TYPE_P(b, T_STRING) && RBASIC(b)->klass == rb_cString) {
111 return rb_str_hash_cmp(a, b);
113 if (a == Qundef || b == Qundef) return -1;
114 if (SYMBOL_P(a) && SYMBOL_P(b)) {
115 return a != b;
118 return !rb_eql(a, b);
121 static VALUE
122 hash_recursive(VALUE obj, VALUE arg, int recurse)
124 if (recurse) return INT2FIX(0);
125 return rb_funcallv(obj, id_hash, 0, 0);
128 static long rb_objid_hash(st_index_t index);
130 static st_index_t
131 dbl_to_index(double d)
133 union {double d; st_index_t i;} u;
134 u.d = d;
135 return u.i;
138 long
139 rb_dbl_long_hash(double d)
141 /* normalize -0.0 to 0.0 */
142 if (d == 0.0) d = 0.0;
143 #if SIZEOF_INT == SIZEOF_VOIDP
144 return rb_memhash(&d, sizeof(d));
145 #else
146 return rb_objid_hash(dbl_to_index(d));
147 #endif
150 static inline long
151 any_hash(VALUE a, st_index_t (*other_func)(VALUE))
153 VALUE hval;
154 st_index_t hnum;
156 switch (TYPE(a)) {
157 case T_SYMBOL:
158 if (STATIC_SYM_P(a)) {
159 hnum = a >> (RUBY_SPECIAL_SHIFT + ID_SCOPE_SHIFT);
160 hnum = rb_hash_start(hnum);
162 else {
163 hnum = RSYMBOL(a)->hashval;
165 break;
166 case T_FIXNUM:
167 case T_TRUE:
168 case T_FALSE:
169 case T_NIL:
170 hnum = rb_objid_hash((st_index_t)a);
171 break;
172 case T_STRING:
173 hnum = rb_str_hash(a);
174 break;
175 case T_BIGNUM:
176 hval = rb_big_hash(a);
177 hnum = FIX2LONG(hval);
178 break;
179 case T_FLOAT: /* prevent pathological behavior: [Bug #10761] */
180 hnum = rb_dbl_long_hash(rb_float_value(a));
181 break;
182 default:
183 hnum = other_func(a);
185 if ((SIGNED_VALUE)hnum > 0)
186 hnum &= FIXNUM_MAX;
187 else
188 hnum |= FIXNUM_MIN;
189 return (long)hnum;
192 static st_index_t
193 obj_any_hash(VALUE obj)
195 VALUE hval = rb_check_funcall_basic_kw(obj, id_hash, rb_mKernel, 0, 0, 0);
197 if (hval == Qundef) {
198 hval = rb_exec_recursive_outer(hash_recursive, obj, 0);
201 while (!FIXNUM_P(hval)) {
202 if (RB_TYPE_P(hval, T_BIGNUM)) {
203 int sign;
204 unsigned long ul;
205 sign = rb_integer_pack(hval, &ul, 1, sizeof(ul), 0,
206 INTEGER_PACK_NATIVE_BYTE_ORDER);
207 if (sign < 0) {
208 hval = LONG2FIX(ul | FIXNUM_MIN);
210 else {
211 hval = LONG2FIX(ul & FIXNUM_MAX);
214 hval = rb_to_int(hval);
217 return FIX2LONG(hval);
220 static st_index_t
221 rb_any_hash(VALUE a)
223 return any_hash(a, obj_any_hash);
226 VALUE
227 rb_hash(VALUE obj)
229 return LONG2FIX(any_hash(obj, obj_any_hash));
233 /* Here is a hash function for 64-bit key. It is about 5 times faster
234 (2 times faster when uint128 type is absent) on Haswell than
235 tailored Spooky or City hash function can be. */
237 /* Here we two primes with random bit generation. */
238 static const uint64_t prime1 = ((uint64_t)0x2e0bb864 << 32) | 0xe9ea7df5;
239 static const uint32_t prime2 = 0x830fcab9;
242 static inline uint64_t
243 mult_and_mix(uint64_t m1, uint64_t m2)
245 #if defined HAVE_UINT128_T
246 uint128_t r = (uint128_t) m1 * (uint128_t) m2;
247 return (uint64_t) (r >> 64) ^ (uint64_t) r;
248 #else
249 uint64_t hm1 = m1 >> 32, hm2 = m2 >> 32;
250 uint64_t lm1 = m1, lm2 = m2;
251 uint64_t v64_128 = hm1 * hm2;
252 uint64_t v32_96 = hm1 * lm2 + lm1 * hm2;
253 uint64_t v1_32 = lm1 * lm2;
255 return (v64_128 + (v32_96 >> 32)) ^ ((v32_96 << 32) + v1_32);
256 #endif
259 static inline uint64_t
260 key64_hash(uint64_t key, uint32_t seed)
262 return mult_and_mix(key + seed, prime1);
265 /* Should cast down the result for each purpose */
266 #define st_index_hash(index) key64_hash(rb_hash_start(index), prime2)
268 static long
269 rb_objid_hash(st_index_t index)
271 return (long)st_index_hash(index);
274 static st_index_t
275 objid_hash(VALUE obj)
277 VALUE object_id = rb_obj_id(obj);
278 if (!FIXNUM_P(object_id))
279 object_id = rb_big_hash(object_id);
281 #if SIZEOF_LONG == SIZEOF_VOIDP
282 return (st_index_t)st_index_hash((st_index_t)NUM2LONG(object_id));
283 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
284 return (st_index_t)st_index_hash((st_index_t)NUM2LL(object_id));
285 #endif
289 * call-seq:
290 * obj.hash -> integer
292 * Generates an Integer hash value for this object. This function must have the
293 * property that <code>a.eql?(b)</code> implies <code>a.hash == b.hash</code>.
295 * The hash value is used along with #eql? by the Hash class to determine if
296 * two objects reference the same hash key. Any hash value that exceeds the
297 * capacity of an Integer will be truncated before being used.
299 * The hash value for an object may not be identical across invocations or
300 * implementations of Ruby. If you need a stable identifier across Ruby
301 * invocations and implementations you will need to generate one with a custom
302 * method.
304 * Certain core classes such as Integer use built-in hash calculations and
305 * do not call the #hash method when used as a hash key.
307 * \private
310 VALUE
311 rb_obj_hash(VALUE obj)
313 long hnum = any_hash(obj, objid_hash);
314 return ST2FIX(hnum);
317 static const struct st_hash_type objhash = {
318 rb_any_cmp,
319 rb_any_hash,
322 #define rb_ident_cmp st_numcmp
324 static st_index_t
325 rb_ident_hash(st_data_t n)
327 #ifdef USE_FLONUM /* RUBY */
329 * - flonum (on 64-bit) is pathologically bad, mix the actual
330 * float value in, but do not use the float value as-is since
331 * many integers get interpreted as 2.0 or -2.0 [Bug #10761]
333 if (FLONUM_P(n)) {
334 n ^= dbl_to_index(rb_float_value(n));
336 #endif
338 return (st_index_t)st_index_hash((st_index_t)n);
341 #define identhash rb_hashtype_ident
342 const struct st_hash_type rb_hashtype_ident = {
343 rb_ident_cmp,
344 rb_ident_hash,
347 typedef st_index_t st_hash_t;
350 * RHASH_AR_TABLE_P(h):
351 * * as.ar == NULL or
352 * as.ar points ar_table.
353 * * as.ar is allocated by transient heap or xmalloc.
355 * !RHASH_AR_TABLE_P(h):
356 * * as.st points st_table.
359 #define RHASH_AR_TABLE_MAX_BOUND RHASH_AR_TABLE_MAX_SIZE
361 #define RHASH_AR_TABLE_REF(hash, n) (&RHASH_AR_TABLE(hash)->pairs[n])
362 #define RHASH_AR_CLEARED_HINT 0xff
364 typedef struct ar_table_pair_struct {
365 VALUE key;
366 VALUE val;
367 } ar_table_pair;
369 typedef struct ar_table_struct {
370 /* 64bit CPU: 8B * 2 * 8 = 128B */
371 ar_table_pair pairs[RHASH_AR_TABLE_MAX_SIZE];
372 } ar_table;
374 size_t
375 rb_hash_ar_table_size(void)
377 return sizeof(ar_table);
380 static inline st_hash_t
381 ar_do_hash(st_data_t key)
383 return (st_hash_t)rb_any_hash(key);
386 static inline ar_hint_t
387 ar_do_hash_hint(st_hash_t hash_value)
389 return (ar_hint_t)hash_value;
392 static inline ar_hint_t
393 ar_hint(VALUE hash, unsigned int index)
395 return RHASH(hash)->ar_hint.ary[index];
398 static inline void
399 ar_hint_set_hint(VALUE hash, unsigned int index, ar_hint_t hint)
401 RHASH(hash)->ar_hint.ary[index] = hint;
404 static inline void
405 ar_hint_set(VALUE hash, unsigned int index, st_hash_t hash_value)
407 ar_hint_set_hint(hash, index, ar_do_hash_hint(hash_value));
410 static inline void
411 ar_clear_entry(VALUE hash, unsigned int index)
413 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
414 pair->key = Qundef;
415 ar_hint_set_hint(hash, index, RHASH_AR_CLEARED_HINT);
418 static inline int
419 ar_cleared_entry(VALUE hash, unsigned int index)
421 if (ar_hint(hash, index) == RHASH_AR_CLEARED_HINT) {
422 /* RHASH_AR_CLEARED_HINT is only a hint, not mean cleared entry,
423 * so you need to check key == Qundef
425 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
426 return pair->key == Qundef;
428 else {
429 return FALSE;
433 static inline void
434 ar_set_entry(VALUE hash, unsigned int index, st_data_t key, st_data_t val, st_hash_t hash_value)
436 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
437 pair->key = key;
438 pair->val = val;
439 ar_hint_set(hash, index, hash_value);
442 #define RHASH_AR_TABLE_SIZE(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
443 RHASH_AR_TABLE_SIZE_RAW(h))
445 #define RHASH_AR_TABLE_BOUND_RAW(h) \
446 ((unsigned int)((RBASIC(h)->flags >> RHASH_AR_TABLE_BOUND_SHIFT) & \
447 (RHASH_AR_TABLE_BOUND_MASK >> RHASH_AR_TABLE_BOUND_SHIFT)))
449 #define RHASH_AR_TABLE_BOUND(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
450 RHASH_AR_TABLE_BOUND_RAW(h))
452 #define RHASH_ST_TABLE_SET(h, s) rb_hash_st_table_set(h, s)
453 #define RHASH_TYPE(hash) (RHASH_AR_TABLE_P(hash) ? &objhash : RHASH_ST_TABLE(hash)->type)
455 #define HASH_ASSERT(expr) RUBY_ASSERT_MESG_WHEN(HASH_DEBUG, expr, #expr)
457 #if HASH_DEBUG
458 #define hash_verify(hash) hash_verify_(hash, __FILE__, __LINE__)
460 void
461 rb_hash_dump(VALUE hash)
463 rb_obj_info_dump(hash);
465 if (RHASH_AR_TABLE_P(hash)) {
466 unsigned i, n = 0, bound = RHASH_AR_TABLE_BOUND(hash);
468 fprintf(stderr, " size:%u bound:%u\n",
469 RHASH_AR_TABLE_SIZE(hash), RHASH_AR_TABLE_BOUND(hash));
471 for (i=0; i<bound; i++) {
472 st_data_t k, v;
474 if (!ar_cleared_entry(hash, i)) {
475 char b1[0x100], b2[0x100];
476 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
477 k = pair->key;
478 v = pair->val;
479 fprintf(stderr, " %d key:%s val:%s hint:%02x\n", i,
480 rb_raw_obj_info(b1, 0x100, k),
481 rb_raw_obj_info(b2, 0x100, v),
482 ar_hint(hash, i));
483 n++;
485 else {
486 fprintf(stderr, " %d empty\n", i);
492 static VALUE
493 hash_verify_(VALUE hash, const char *file, int line)
495 HASH_ASSERT(RB_TYPE_P(hash, T_HASH));
497 if (RHASH_AR_TABLE_P(hash)) {
498 unsigned i, n = 0, bound = RHASH_AR_TABLE_BOUND(hash);
500 for (i=0; i<bound; i++) {
501 st_data_t k, v;
502 if (!ar_cleared_entry(hash, i)) {
503 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
504 k = pair->key;
505 v = pair->val;
506 HASH_ASSERT(k != Qundef);
507 HASH_ASSERT(v != Qundef);
508 n++;
511 if (n != RHASH_AR_TABLE_SIZE(hash)) {
512 rb_bug("n:%u, RHASH_AR_TABLE_SIZE:%u", n, RHASH_AR_TABLE_SIZE(hash));
515 else {
516 HASH_ASSERT(RHASH_ST_TABLE(hash) != NULL);
517 HASH_ASSERT(RHASH_AR_TABLE_SIZE_RAW(hash) == 0);
518 HASH_ASSERT(RHASH_AR_TABLE_BOUND_RAW(hash) == 0);
521 #if USE_TRANSIENT_HEAP
522 if (RHASH_TRANSIENT_P(hash)) {
523 volatile st_data_t MAYBE_UNUSED(key) = RHASH_AR_TABLE_REF(hash, 0)->key; /* read */
524 HASH_ASSERT(RHASH_AR_TABLE(hash) != NULL);
525 HASH_ASSERT(rb_transient_heap_managed_ptr_p(RHASH_AR_TABLE(hash)));
527 #endif
528 return hash;
531 #else
532 #define hash_verify(h) ((void)0)
533 #endif
535 static inline int
536 RHASH_TABLE_NULL_P(VALUE hash)
538 if (RHASH(hash)->as.ar == NULL) {
539 HASH_ASSERT(RHASH_AR_TABLE_P(hash));
540 return TRUE;
542 else {
543 return FALSE;
547 static inline int
548 RHASH_TABLE_EMPTY_P(VALUE hash)
550 return RHASH_SIZE(hash) == 0;
554 rb_hash_ar_table_p(VALUE hash)
556 if (FL_TEST_RAW((hash), RHASH_ST_TABLE_FLAG)) {
557 HASH_ASSERT(RHASH(hash)->as.st != NULL);
558 return FALSE;
560 else {
561 return TRUE;
565 ar_table *
566 rb_hash_ar_table(VALUE hash)
568 HASH_ASSERT(RHASH_AR_TABLE_P(hash));
569 return RHASH(hash)->as.ar;
572 st_table *
573 rb_hash_st_table(VALUE hash)
575 HASH_ASSERT(!RHASH_AR_TABLE_P(hash));
576 return RHASH(hash)->as.st;
579 void
580 rb_hash_st_table_set(VALUE hash, st_table *st)
582 HASH_ASSERT(st != NULL);
583 FL_SET_RAW((hash), RHASH_ST_TABLE_FLAG);
584 RHASH(hash)->as.st = st;
587 static void
588 hash_ar_table_set(VALUE hash, ar_table *ar)
590 HASH_ASSERT(RHASH_AR_TABLE_P(hash));
591 HASH_ASSERT((RHASH_TRANSIENT_P(hash) && ar == NULL) ? FALSE : TRUE);
592 RHASH(hash)->as.ar = ar;
593 hash_verify(hash);
596 #define RHASH_SET_ST_FLAG(h) FL_SET_RAW(h, RHASH_ST_TABLE_FLAG)
597 #define RHASH_UNSET_ST_FLAG(h) FL_UNSET_RAW(h, RHASH_ST_TABLE_FLAG)
599 static inline void
600 RHASH_AR_TABLE_BOUND_SET(VALUE h, st_index_t n)
602 HASH_ASSERT(RHASH_AR_TABLE_P(h));
603 HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_BOUND);
605 RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
606 RBASIC(h)->flags |= n << RHASH_AR_TABLE_BOUND_SHIFT;
609 static inline void
610 RHASH_AR_TABLE_SIZE_SET(VALUE h, st_index_t n)
612 HASH_ASSERT(RHASH_AR_TABLE_P(h));
613 HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_SIZE);
615 RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
616 RBASIC(h)->flags |= n << RHASH_AR_TABLE_SIZE_SHIFT;
619 static inline void
620 HASH_AR_TABLE_SIZE_ADD(VALUE h, st_index_t n)
622 HASH_ASSERT(RHASH_AR_TABLE_P(h));
624 RHASH_AR_TABLE_SIZE_SET(h, RHASH_AR_TABLE_SIZE(h) + n);
626 hash_verify(h);
629 #define RHASH_AR_TABLE_SIZE_INC(h) HASH_AR_TABLE_SIZE_ADD(h, 1)
631 static inline void
632 RHASH_AR_TABLE_SIZE_DEC(VALUE h)
634 HASH_ASSERT(RHASH_AR_TABLE_P(h));
635 int new_size = RHASH_AR_TABLE_SIZE(h) - 1;
637 if (new_size != 0) {
638 RHASH_AR_TABLE_SIZE_SET(h, new_size);
640 else {
641 RHASH_AR_TABLE_SIZE_SET(h, 0);
642 RHASH_AR_TABLE_BOUND_SET(h, 0);
644 hash_verify(h);
647 static inline void
648 RHASH_AR_TABLE_CLEAR(VALUE h)
650 RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
651 RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
653 hash_ar_table_set(h, NULL);
656 static ar_table*
657 ar_alloc_table(VALUE hash)
659 ar_table *tab = (ar_table*)rb_transient_heap_alloc(hash, sizeof(ar_table));
661 if (tab != NULL) {
662 RHASH_SET_TRANSIENT_FLAG(hash);
664 else {
665 RHASH_UNSET_TRANSIENT_FLAG(hash);
666 tab = (ar_table*)ruby_xmalloc(sizeof(ar_table));
669 RHASH_AR_TABLE_SIZE_SET(hash, 0);
670 RHASH_AR_TABLE_BOUND_SET(hash, 0);
671 hash_ar_table_set(hash, tab);
673 return tab;
676 NOINLINE(static int ar_equal(VALUE x, VALUE y));
678 static int
679 ar_equal(VALUE x, VALUE y)
681 return rb_any_cmp(x, y) == 0;
684 static unsigned
685 ar_find_entry_hint(VALUE hash, ar_hint_t hint, st_data_t key)
687 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
688 const ar_hint_t *hints = RHASH(hash)->ar_hint.ary;
690 /* if table is NULL, then bound also should be 0 */
692 for (i = 0; i < bound; i++) {
693 if (hints[i] == hint) {
694 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
695 if (ar_equal(key, pair->key)) {
696 RB_DEBUG_COUNTER_INC(artable_hint_hit);
697 return i;
699 else {
700 #if 0
701 static int pid;
702 static char fname[256];
703 static FILE *fp;
705 if (pid != getpid()) {
706 snprintf(fname, sizeof(fname), "/tmp/ruby-armiss.%d", pid = getpid());
707 if ((fp = fopen(fname, "w")) == NULL) rb_bug("fopen");
710 st_hash_t h1 = ar_do_hash(key);
711 st_hash_t h2 = ar_do_hash(pair->key);
713 fprintf(fp, "miss: hash_eq:%d hints[%d]:%02x hint:%02x\n"
714 " key :%016lx %s\n"
715 " pair->key:%016lx %s\n",
716 h1 == h2, i, hints[i], hint,
717 h1, rb_obj_info(key), h2, rb_obj_info(pair->key));
718 #endif
719 RB_DEBUG_COUNTER_INC(artable_hint_miss);
723 RB_DEBUG_COUNTER_INC(artable_hint_notfound);
724 return RHASH_AR_TABLE_MAX_BOUND;
727 static unsigned
728 ar_find_entry(VALUE hash, st_hash_t hash_value, st_data_t key)
730 ar_hint_t hint = ar_do_hash_hint(hash_value);
731 return ar_find_entry_hint(hash, hint, key);
734 static inline void
735 ar_free_and_clear_table(VALUE hash)
737 ar_table *tab = RHASH_AR_TABLE(hash);
739 if (tab) {
740 if (RHASH_TRANSIENT_P(hash)) {
741 RHASH_UNSET_TRANSIENT_FLAG(hash);
743 else {
744 ruby_xfree(RHASH_AR_TABLE(hash));
746 RHASH_AR_TABLE_CLEAR(hash);
748 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
749 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
750 HASH_ASSERT(RHASH_TRANSIENT_P(hash) == 0);
753 static void
754 ar_try_convert_table(VALUE hash)
756 if (!RHASH_AR_TABLE_P(hash)) return;
758 const unsigned size = RHASH_AR_TABLE_SIZE(hash);
760 st_table *new_tab;
761 st_index_t i;
763 if (size < RHASH_AR_TABLE_MAX_SIZE) {
764 return;
767 new_tab = st_init_table_with_size(&objhash, size * 2);
769 for (i = 0; i < RHASH_AR_TABLE_MAX_BOUND; i++) {
770 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
771 st_add_direct(new_tab, pair->key, pair->val);
773 ar_free_and_clear_table(hash);
774 RHASH_ST_TABLE_SET(hash, new_tab);
775 return;
778 static st_table *
779 ar_force_convert_table(VALUE hash, const char *file, int line)
781 st_table *new_tab;
783 if (RHASH_ST_TABLE_P(hash)) {
784 return RHASH_ST_TABLE(hash);
787 if (RHASH_AR_TABLE(hash)) {
788 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
790 #if defined(RHASH_CONVERT_TABLE_DEBUG) && RHASH_CONVERT_TABLE_DEBUG
791 rb_obj_info_dump(hash);
792 fprintf(stderr, "force_convert: %s:%d\n", file, line);
793 RB_DEBUG_COUNTER_INC(obj_hash_force_convert);
794 #endif
796 new_tab = st_init_table_with_size(&objhash, RHASH_AR_TABLE_SIZE(hash));
798 for (i = 0; i < bound; i++) {
799 if (ar_cleared_entry(hash, i)) continue;
801 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
802 st_add_direct(new_tab, pair->key, pair->val);
804 ar_free_and_clear_table(hash);
806 else {
807 new_tab = st_init_table(&objhash);
809 RHASH_ST_TABLE_SET(hash, new_tab);
811 return new_tab;
814 static ar_table *
815 hash_ar_table(VALUE hash)
817 if (RHASH_TABLE_NULL_P(hash)) {
818 ar_alloc_table(hash);
820 return RHASH_AR_TABLE(hash);
823 static int
824 ar_compact_table(VALUE hash)
826 const unsigned bound = RHASH_AR_TABLE_BOUND(hash);
827 const unsigned size = RHASH_AR_TABLE_SIZE(hash);
829 if (size == bound) {
830 return size;
832 else {
833 unsigned i, j=0;
834 ar_table_pair *pairs = RHASH_AR_TABLE(hash)->pairs;
836 for (i=0; i<bound; i++) {
837 if (ar_cleared_entry(hash, i)) {
838 if (j <= i) j = i+1;
839 for (; j<bound; j++) {
840 if (!ar_cleared_entry(hash, j)) {
841 pairs[i] = pairs[j];
842 ar_hint_set_hint(hash, i, (st_hash_t)ar_hint(hash, j));
843 ar_clear_entry(hash, j);
844 j++;
845 goto found;
848 /* non-empty is not found */
849 goto done;
850 found:;
853 done:
854 HASH_ASSERT(i<=bound);
856 RHASH_AR_TABLE_BOUND_SET(hash, size);
857 hash_verify(hash);
858 return size;
862 static int
863 ar_add_direct_with_hash(VALUE hash, st_data_t key, st_data_t val, st_hash_t hash_value)
865 unsigned bin = RHASH_AR_TABLE_BOUND(hash);
867 if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
868 return 1;
870 else {
871 if (UNLIKELY(bin >= RHASH_AR_TABLE_MAX_BOUND)) {
872 bin = ar_compact_table(hash);
873 hash_ar_table(hash);
875 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
877 ar_set_entry(hash, bin, key, val, hash_value);
878 RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
879 RHASH_AR_TABLE_SIZE_INC(hash);
880 return 0;
884 static int
885 ar_general_foreach(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
887 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
888 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
890 for (i = 0; i < bound; i++) {
891 if (ar_cleared_entry(hash, i)) continue;
893 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
894 enum st_retval retval = (*func)(pair->key, pair->val, arg, 0);
895 /* pair may be not valid here because of theap */
897 switch (retval) {
898 case ST_CONTINUE:
899 break;
900 case ST_CHECK:
901 case ST_STOP:
902 return 0;
903 case ST_REPLACE:
904 if (replace) {
905 VALUE key = pair->key;
906 VALUE val = pair->val;
907 retval = (*replace)(&key, &val, arg, TRUE);
909 // TODO: pair should be same as pair before.
910 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
911 pair->key = key;
912 pair->val = val;
914 break;
915 case ST_DELETE:
916 ar_clear_entry(hash, i);
917 RHASH_AR_TABLE_SIZE_DEC(hash);
918 break;
922 return 0;
925 static int
926 ar_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
928 return ar_general_foreach(hash, func, replace, arg);
931 struct functor {
932 st_foreach_callback_func *func;
933 st_data_t arg;
936 static int
937 apply_functor(st_data_t k, st_data_t v, st_data_t d, int _)
939 const struct functor *f = (void *)d;
940 return f->func(k, v, f->arg);
943 static int
944 ar_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
946 const struct functor f = { func, arg };
947 return ar_general_foreach(hash, apply_functor, NULL, (st_data_t)&f);
950 static int
951 ar_foreach_check(VALUE hash, st_foreach_check_callback_func *func, st_data_t arg,
952 st_data_t never)
954 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
955 unsigned i, ret = 0, bound = RHASH_AR_TABLE_BOUND(hash);
956 enum st_retval retval;
957 st_data_t key;
958 ar_table_pair *pair;
959 ar_hint_t hint;
961 for (i = 0; i < bound; i++) {
962 if (ar_cleared_entry(hash, i)) continue;
964 pair = RHASH_AR_TABLE_REF(hash, i);
965 key = pair->key;
966 hint = ar_hint(hash, i);
968 retval = (*func)(key, pair->val, arg, 0);
969 hash_verify(hash);
971 switch (retval) {
972 case ST_CHECK: {
973 pair = RHASH_AR_TABLE_REF(hash, i);
974 if (pair->key == never) break;
975 ret = ar_find_entry_hint(hash, hint, key);
976 if (ret == RHASH_AR_TABLE_MAX_BOUND) {
977 retval = (*func)(0, 0, arg, 1);
978 return 2;
981 case ST_CONTINUE:
982 break;
983 case ST_STOP:
984 case ST_REPLACE:
985 return 0;
986 case ST_DELETE: {
987 if (!ar_cleared_entry(hash, i)) {
988 ar_clear_entry(hash, i);
989 RHASH_AR_TABLE_SIZE_DEC(hash);
991 break;
996 return 0;
999 static int
1000 ar_update(VALUE hash, st_data_t key,
1001 st_update_callback_func *func, st_data_t arg)
1003 int retval, existing;
1004 unsigned bin = RHASH_AR_TABLE_MAX_BOUND;
1005 st_data_t value = 0, old_key;
1006 st_hash_t hash_value = ar_do_hash(key);
1008 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1009 // `#hash` changes ar_table -> st_table
1010 return -1;
1013 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
1014 bin = ar_find_entry(hash, hash_value, key);
1015 existing = (bin != RHASH_AR_TABLE_MAX_BOUND) ? TRUE : FALSE;
1017 else {
1018 hash_ar_table(hash); /* allocate ltbl if needed */
1019 existing = FALSE;
1022 if (existing) {
1023 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1024 key = pair->key;
1025 value = pair->val;
1027 old_key = key;
1028 retval = (*func)(&key, &value, arg, existing);
1029 /* pair can be invalid here because of theap */
1031 switch (retval) {
1032 case ST_CONTINUE:
1033 if (!existing) {
1034 if (ar_add_direct_with_hash(hash, key, value, hash_value)) {
1035 return -1;
1038 else {
1039 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1040 if (old_key != key) {
1041 pair->key = key;
1043 pair->val = value;
1045 break;
1046 case ST_DELETE:
1047 if (existing) {
1048 ar_clear_entry(hash, bin);
1049 RHASH_AR_TABLE_SIZE_DEC(hash);
1051 break;
1053 return existing;
1056 static int
1057 ar_insert(VALUE hash, st_data_t key, st_data_t value)
1059 unsigned bin = RHASH_AR_TABLE_BOUND(hash);
1060 st_hash_t hash_value = ar_do_hash(key);
1062 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1063 // `#hash` changes ar_table -> st_table
1064 return -1;
1067 hash_ar_table(hash); /* prepare ltbl */
1069 bin = ar_find_entry(hash, hash_value, key);
1070 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1071 if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
1072 return -1;
1074 else if (bin >= RHASH_AR_TABLE_MAX_BOUND) {
1075 bin = ar_compact_table(hash);
1076 hash_ar_table(hash);
1078 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1080 ar_set_entry(hash, bin, key, value, hash_value);
1081 RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
1082 RHASH_AR_TABLE_SIZE_INC(hash);
1083 return 0;
1085 else {
1086 RHASH_AR_TABLE_REF(hash, bin)->val = value;
1087 return 1;
1091 static int
1092 ar_lookup(VALUE hash, st_data_t key, st_data_t *value)
1094 if (RHASH_AR_TABLE_SIZE(hash) == 0) {
1095 return 0;
1097 else {
1098 st_hash_t hash_value = ar_do_hash(key);
1099 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1100 // `#hash` changes ar_table -> st_table
1101 return st_lookup(RHASH_ST_TABLE(hash), key, value);
1103 unsigned bin = ar_find_entry(hash, hash_value, key);
1105 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1106 return 0;
1108 else {
1109 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1110 if (value != NULL) {
1111 *value = RHASH_AR_TABLE_REF(hash, bin)->val;
1113 return 1;
1118 static int
1119 ar_delete(VALUE hash, st_data_t *key, st_data_t *value)
1121 unsigned bin;
1122 st_hash_t hash_value = ar_do_hash(*key);
1124 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1125 // `#hash` changes ar_table -> st_table
1126 return st_delete(RHASH_ST_TABLE(hash), key, value);
1129 bin = ar_find_entry(hash, hash_value, *key);
1131 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1132 if (value != 0) *value = 0;
1133 return 0;
1135 else {
1136 if (value != 0) {
1137 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1138 *value = pair->val;
1140 ar_clear_entry(hash, bin);
1141 RHASH_AR_TABLE_SIZE_DEC(hash);
1142 return 1;
1146 static int
1147 ar_shift(VALUE hash, st_data_t *key, st_data_t *value)
1149 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
1150 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1152 for (i = 0; i < bound; i++) {
1153 if (!ar_cleared_entry(hash, i)) {
1154 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
1155 if (value != 0) *value = pair->val;
1156 *key = pair->key;
1157 ar_clear_entry(hash, i);
1158 RHASH_AR_TABLE_SIZE_DEC(hash);
1159 return 1;
1163 if (value != NULL) *value = 0;
1164 return 0;
1167 static long
1168 ar_keys(VALUE hash, st_data_t *keys, st_index_t size)
1170 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1171 st_data_t *keys_start = keys, *keys_end = keys + size;
1173 for (i = 0; i < bound; i++) {
1174 if (keys == keys_end) {
1175 break;
1177 else {
1178 if (!ar_cleared_entry(hash, i)) {
1179 *keys++ = RHASH_AR_TABLE_REF(hash, i)->key;
1184 return keys - keys_start;
1187 static long
1188 ar_values(VALUE hash, st_data_t *values, st_index_t size)
1190 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1191 st_data_t *values_start = values, *values_end = values + size;
1193 for (i = 0; i < bound; i++) {
1194 if (values == values_end) {
1195 break;
1197 else {
1198 if (!ar_cleared_entry(hash, i)) {
1199 *values++ = RHASH_AR_TABLE_REF(hash, i)->val;
1204 return values - values_start;
1207 static ar_table*
1208 ar_copy(VALUE hash1, VALUE hash2)
1210 ar_table *old_tab = RHASH_AR_TABLE(hash2);
1212 if (old_tab != NULL) {
1213 ar_table *new_tab = RHASH_AR_TABLE(hash1);
1214 if (new_tab == NULL) {
1215 new_tab = (ar_table*) rb_transient_heap_alloc(hash1, sizeof(ar_table));
1216 if (new_tab != NULL) {
1217 RHASH_SET_TRANSIENT_FLAG(hash1);
1219 else {
1220 RHASH_UNSET_TRANSIENT_FLAG(hash1);
1221 new_tab = (ar_table*)ruby_xmalloc(sizeof(ar_table));
1224 *new_tab = *old_tab;
1225 RHASH(hash1)->ar_hint.word = RHASH(hash2)->ar_hint.word;
1226 RHASH_AR_TABLE_BOUND_SET(hash1, RHASH_AR_TABLE_BOUND(hash2));
1227 RHASH_AR_TABLE_SIZE_SET(hash1, RHASH_AR_TABLE_SIZE(hash2));
1228 hash_ar_table_set(hash1, new_tab);
1230 rb_gc_writebarrier_remember(hash1);
1231 return new_tab;
1233 else {
1234 RHASH_AR_TABLE_BOUND_SET(hash1, RHASH_AR_TABLE_BOUND(hash2));
1235 RHASH_AR_TABLE_SIZE_SET(hash1, RHASH_AR_TABLE_SIZE(hash2));
1237 if (RHASH_TRANSIENT_P(hash1)) {
1238 RHASH_UNSET_TRANSIENT_FLAG(hash1);
1240 else if (RHASH_AR_TABLE(hash1)) {
1241 ruby_xfree(RHASH_AR_TABLE(hash1));
1244 hash_ar_table_set(hash1, NULL);
1246 rb_gc_writebarrier_remember(hash1);
1247 return old_tab;
1251 static void
1252 ar_clear(VALUE hash)
1254 if (RHASH_AR_TABLE(hash) != NULL) {
1255 RHASH_AR_TABLE_SIZE_SET(hash, 0);
1256 RHASH_AR_TABLE_BOUND_SET(hash, 0);
1258 else {
1259 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
1260 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
1264 #if USE_TRANSIENT_HEAP
1265 void
1266 rb_hash_transient_heap_evacuate(VALUE hash, int promote)
1268 if (RHASH_TRANSIENT_P(hash)) {
1269 ar_table *new_tab;
1270 ar_table *old_tab = RHASH_AR_TABLE(hash);
1272 if (UNLIKELY(old_tab == NULL)) {
1273 return;
1275 HASH_ASSERT(old_tab != NULL);
1276 if (! promote) {
1277 new_tab = rb_transient_heap_alloc(hash, sizeof(ar_table));
1278 if (new_tab == NULL) promote = true;
1280 if (promote) {
1281 new_tab = ruby_xmalloc(sizeof(ar_table));
1282 RHASH_UNSET_TRANSIENT_FLAG(hash);
1284 *new_tab = *old_tab;
1285 hash_ar_table_set(hash, new_tab);
1287 hash_verify(hash);
1289 #endif
1291 typedef int st_foreach_func(st_data_t, st_data_t, st_data_t);
1293 struct foreach_safe_arg {
1294 st_table *tbl;
1295 st_foreach_func *func;
1296 st_data_t arg;
1299 static int
1300 foreach_safe_i(st_data_t key, st_data_t value, st_data_t args, int error)
1302 int status;
1303 struct foreach_safe_arg *arg = (void *)args;
1305 if (error) return ST_STOP;
1306 status = (*arg->func)(key, value, arg->arg);
1307 if (status == ST_CONTINUE) {
1308 return ST_CHECK;
1310 return status;
1313 void
1314 st_foreach_safe(st_table *table, st_foreach_func *func, st_data_t a)
1316 struct foreach_safe_arg arg;
1318 arg.tbl = table;
1319 arg.func = (st_foreach_func *)func;
1320 arg.arg = a;
1321 if (st_foreach_check(table, foreach_safe_i, (st_data_t)&arg, 0)) {
1322 rb_raise(rb_eRuntimeError, "hash modified during iteration");
1326 typedef int rb_foreach_func(VALUE, VALUE, VALUE);
1328 struct hash_foreach_arg {
1329 VALUE hash;
1330 rb_foreach_func *func;
1331 VALUE arg;
1334 static int
1335 hash_ar_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1337 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1338 int status;
1340 if (error) return ST_STOP;
1341 status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1342 /* TODO: rehash check? rb_raise(rb_eRuntimeError, "rehash occurred during iteration"); */
1344 switch (status) {
1345 case ST_DELETE:
1346 return ST_DELETE;
1347 case ST_CONTINUE:
1348 break;
1349 case ST_STOP:
1350 return ST_STOP;
1352 return ST_CHECK;
1355 static int
1356 hash_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1358 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1359 int status;
1360 st_table *tbl;
1362 if (error) return ST_STOP;
1363 tbl = RHASH_ST_TABLE(arg->hash);
1364 status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1365 if (RHASH_ST_TABLE(arg->hash) != tbl) {
1366 rb_raise(rb_eRuntimeError, "rehash occurred during iteration");
1368 switch (status) {
1369 case ST_DELETE:
1370 return ST_DELETE;
1371 case ST_CONTINUE:
1372 break;
1373 case ST_STOP:
1374 return ST_STOP;
1376 return ST_CHECK;
1379 static int
1380 iter_lev_in_ivar(VALUE hash)
1382 VALUE levval = rb_ivar_get(hash, id_hash_iter_lev);
1383 HASH_ASSERT(FIXNUM_P(levval));
1384 return FIX2INT(levval);
1387 void rb_ivar_set_internal(VALUE obj, ID id, VALUE val);
1389 static void
1390 iter_lev_in_ivar_set(VALUE hash, int lev)
1392 rb_ivar_set_internal(hash, id_hash_iter_lev, INT2FIX(lev));
1395 static int
1396 iter_lev_in_flags(VALUE hash)
1398 unsigned int u = (unsigned int)((RBASIC(hash)->flags >> RHASH_LEV_SHIFT) & RHASH_LEV_MAX);
1399 return (int)u;
1402 static int
1403 RHASH_ITER_LEV(VALUE hash)
1405 int lev = iter_lev_in_flags(hash);
1407 if (lev == RHASH_LEV_MAX) {
1408 return iter_lev_in_ivar(hash);
1410 else {
1411 return lev;
1415 static void
1416 hash_iter_lev_inc(VALUE hash)
1418 int lev = iter_lev_in_flags(hash);
1419 if (lev == RHASH_LEV_MAX) {
1420 lev = iter_lev_in_ivar(hash);
1421 iter_lev_in_ivar_set(hash, lev+1);
1423 else {
1424 lev += 1;
1425 RBASIC(hash)->flags = ((RBASIC(hash)->flags & ~RHASH_LEV_MASK) | ((VALUE)lev << RHASH_LEV_SHIFT));
1426 if (lev == RHASH_LEV_MAX) {
1427 iter_lev_in_ivar_set(hash, lev);
1432 static void
1433 hash_iter_lev_dec(VALUE hash)
1435 int lev = iter_lev_in_flags(hash);
1436 if (lev == RHASH_LEV_MAX) {
1437 lev = iter_lev_in_ivar(hash);
1438 HASH_ASSERT(lev > 0);
1439 iter_lev_in_ivar_set(hash, lev-1);
1441 else {
1442 HASH_ASSERT(lev > 0);
1443 RBASIC(hash)->flags = ((RBASIC(hash)->flags & ~RHASH_LEV_MASK) | ((lev-1) << RHASH_LEV_SHIFT));
1447 static VALUE
1448 hash_foreach_ensure_rollback(VALUE hash)
1450 hash_iter_lev_inc(hash);
1451 return 0;
1454 static VALUE
1455 hash_foreach_ensure(VALUE hash)
1457 hash_iter_lev_dec(hash);
1458 return 0;
1462 rb_hash_stlike_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
1464 if (RHASH_AR_TABLE_P(hash)) {
1465 return ar_foreach(hash, func, arg);
1467 else {
1468 return st_foreach(RHASH_ST_TABLE(hash), func, arg);
1473 rb_hash_stlike_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
1475 if (RHASH_AR_TABLE_P(hash)) {
1476 return ar_foreach_with_replace(hash, func, replace, arg);
1478 else {
1479 return st_foreach_with_replace(RHASH_ST_TABLE(hash), func, replace, arg);
1483 static VALUE
1484 hash_foreach_call(VALUE arg)
1486 VALUE hash = ((struct hash_foreach_arg *)arg)->hash;
1487 int ret = 0;
1488 if (RHASH_AR_TABLE_P(hash)) {
1489 ret = ar_foreach_check(hash, hash_ar_foreach_iter,
1490 (st_data_t)arg, (st_data_t)Qundef);
1492 else if (RHASH_ST_TABLE_P(hash)) {
1493 ret = st_foreach_check(RHASH_ST_TABLE(hash), hash_foreach_iter,
1494 (st_data_t)arg, (st_data_t)Qundef);
1496 if (ret) {
1497 rb_raise(rb_eRuntimeError, "ret: %d, hash modified during iteration", ret);
1499 return Qnil;
1502 void
1503 rb_hash_foreach(VALUE hash, rb_foreach_func *func, VALUE farg)
1505 struct hash_foreach_arg arg;
1507 if (RHASH_TABLE_EMPTY_P(hash))
1508 return;
1509 arg.hash = hash;
1510 arg.func = (rb_foreach_func *)func;
1511 arg.arg = farg;
1512 if (RB_OBJ_FROZEN(hash)) {
1513 hash_foreach_call((VALUE)&arg);
1515 else {
1516 hash_iter_lev_inc(hash);
1517 rb_ensure(hash_foreach_call, (VALUE)&arg, hash_foreach_ensure, hash);
1519 hash_verify(hash);
1522 static VALUE
1523 hash_alloc_flags(VALUE klass, VALUE flags, VALUE ifnone)
1525 const VALUE wb = (RGENGC_WB_PROTECTED_HASH ? FL_WB_PROTECTED : 0);
1526 NEWOBJ_OF(hash, struct RHash, klass, T_HASH | wb | flags);
1528 RHASH_SET_IFNONE((VALUE)hash, ifnone);
1530 return (VALUE)hash;
1533 static VALUE
1534 hash_alloc(VALUE klass)
1536 return hash_alloc_flags(klass, 0, Qnil);
1539 static VALUE
1540 empty_hash_alloc(VALUE klass)
1542 RUBY_DTRACE_CREATE_HOOK(HASH, 0);
1544 return hash_alloc(klass);
1547 VALUE
1548 rb_hash_new(void)
1550 return hash_alloc(rb_cHash);
1553 static VALUE
1554 copy_compare_by_id(VALUE hash, VALUE basis)
1556 if (rb_hash_compare_by_id_p(basis)) {
1557 return rb_hash_compare_by_id(hash);
1559 return hash;
1562 MJIT_FUNC_EXPORTED VALUE
1563 rb_hash_new_with_size(st_index_t size)
1565 VALUE ret = rb_hash_new();
1566 if (size == 0) {
1567 /* do nothing */
1569 else if (size <= RHASH_AR_TABLE_MAX_SIZE) {
1570 ar_alloc_table(ret);
1572 else {
1573 RHASH_ST_TABLE_SET(ret, st_init_table_with_size(&objhash, size));
1575 return ret;
1578 static VALUE
1579 hash_copy(VALUE ret, VALUE hash)
1581 if (!RHASH_EMPTY_P(hash)) {
1582 if (RHASH_AR_TABLE_P(hash))
1583 ar_copy(ret, hash);
1584 else if (RHASH_ST_TABLE_P(hash))
1585 RHASH_ST_TABLE_SET(ret, st_copy(RHASH_ST_TABLE(hash)));
1587 return ret;
1590 static VALUE
1591 hash_dup_with_compare_by_id(VALUE hash)
1593 return hash_copy(copy_compare_by_id(rb_hash_new(), hash), hash);
1596 static VALUE
1597 hash_dup(VALUE hash, VALUE klass, VALUE flags)
1599 return hash_copy(hash_alloc_flags(klass, flags, RHASH_IFNONE(hash)),
1600 hash);
1603 VALUE
1604 rb_hash_dup(VALUE hash)
1606 const VALUE flags = RBASIC(hash)->flags;
1607 VALUE ret = hash_dup(hash, rb_obj_class(hash),
1608 flags & (FL_EXIVAR|RHASH_PROC_DEFAULT));
1609 if (flags & FL_EXIVAR)
1610 rb_copy_generic_ivar(ret, hash);
1611 return ret;
1614 MJIT_FUNC_EXPORTED VALUE
1615 rb_hash_resurrect(VALUE hash)
1617 VALUE ret = hash_dup(hash, rb_cHash, 0);
1618 return ret;
1621 static void
1622 rb_hash_modify_check(VALUE hash)
1624 rb_check_frozen(hash);
1627 MJIT_FUNC_EXPORTED struct st_table *
1628 rb_hash_tbl_raw(VALUE hash, const char *file, int line)
1630 return ar_force_convert_table(hash, file, line);
1633 struct st_table *
1634 rb_hash_tbl(VALUE hash, const char *file, int line)
1636 OBJ_WB_UNPROTECT(hash);
1637 return rb_hash_tbl_raw(hash, file, line);
1640 static void
1641 rb_hash_modify(VALUE hash)
1643 rb_hash_modify_check(hash);
1646 NORETURN(static void no_new_key(void));
1647 static void
1648 no_new_key(void)
1650 rb_raise(rb_eRuntimeError, "can't add a new key into hash during iteration");
1653 struct update_callback_arg {
1654 VALUE hash;
1655 st_data_t arg;
1658 #define NOINSERT_UPDATE_CALLBACK(func) \
1659 static int \
1660 func##_noinsert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1662 if (!existing) no_new_key(); \
1663 return func(key, val, (struct update_arg *)arg, existing); \
1666 static int \
1667 func##_insert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1669 return func(key, val, (struct update_arg *)arg, existing); \
1672 struct update_arg {
1673 st_data_t arg;
1674 st_update_callback_func *func;
1675 VALUE hash;
1678 typedef int (*tbl_update_func)(st_data_t *, st_data_t *, st_data_t, int);
1681 rb_hash_stlike_update(VALUE hash, st_data_t key, st_update_callback_func *func, st_data_t arg)
1683 if (RHASH_AR_TABLE_P(hash)) {
1684 int result = ar_update(hash, key, func, arg);
1685 if (result == -1) {
1686 ar_try_convert_table(hash);
1688 else {
1689 return result;
1693 return st_update(RHASH_ST_TABLE(hash), key, func, arg);
1696 static int
1697 tbl_update_modify(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
1699 struct update_arg *p = (struct update_arg *)arg;
1700 st_data_t old_key = *key;
1701 st_data_t old_value = *val;
1702 VALUE hash = p->hash;
1703 int ret = (p->func)(key, val, arg, existing);
1704 switch (ret) {
1705 default:
1706 break;
1707 case ST_CONTINUE:
1708 if (!existing || *key != old_key || *val != old_value)
1709 rb_hash_modify(hash);
1710 /* write barrier */
1711 RB_OBJ_WRITTEN(hash, Qundef, *key);
1712 RB_OBJ_WRITTEN(hash, Qundef, *val);
1713 break;
1714 case ST_DELETE:
1715 if (existing)
1716 rb_hash_modify(hash);
1717 break;
1720 return ret;
1723 static int
1724 tbl_update(VALUE hash, VALUE key, tbl_update_func func, st_data_t optional_arg)
1726 struct update_arg arg = {
1727 .arg = optional_arg,
1728 .func = func,
1729 .hash = hash,
1732 return rb_hash_stlike_update(hash, key, tbl_update_modify, (st_data_t)&arg);
1735 #define UPDATE_CALLBACK(iter_lev, func) ((iter_lev) > 0 ? func##_noinsert : func##_insert)
1737 #define RHASH_UPDATE_ITER(h, iter_lev, key, func, a) do { \
1738 tbl_update((h), (key), UPDATE_CALLBACK((iter_lev), func), (st_data_t)(a)); \
1739 } while (0)
1741 #define RHASH_UPDATE(hash, key, func, arg) \
1742 RHASH_UPDATE_ITER(hash, RHASH_ITER_LEV(hash), key, func, arg)
1744 static void
1745 set_proc_default(VALUE hash, VALUE proc)
1747 if (rb_proc_lambda_p(proc)) {
1748 int n = rb_proc_arity(proc);
1750 if (n != 2 && (n >= 0 || n < -3)) {
1751 if (n < 0) n = -n-1;
1752 rb_raise(rb_eTypeError, "default_proc takes two arguments (2 for %d)", n);
1756 FL_SET_RAW(hash, RHASH_PROC_DEFAULT);
1757 RHASH_SET_IFNONE(hash, proc);
1761 * call-seq:
1762 * Hash.new(default_value = nil) -> new_hash
1763 * Hash.new {|hash, key| ... } -> new_hash
1765 * Returns a new empty \Hash object.
1767 * The initial default value and initial default proc for the new hash
1768 * depend on which form above was used. See {Default Values}[#class-Hash-label-Default+Values].
1770 * If neither an argument nor a block given,
1771 * initializes both the default value and the default proc to <tt>nil</tt>:
1772 * h = Hash.new
1773 * h.default # => nil
1774 * h.default_proc # => nil
1776 * If argument <tt>default_value</tt> given but no block given,
1777 * initializes the default value to the given <tt>default_value</tt>
1778 * and the default proc to <tt>nil</tt>:
1779 * h = Hash.new(false)
1780 * h.default # => false
1781 * h.default_proc # => nil
1783 * If a block given but no argument, stores the block as the default proc
1784 * and sets the default value to <tt>nil</tt>:
1785 * h = Hash.new {|hash, key| "Default value for #{key}" }
1786 * h.default # => nil
1787 * h.default_proc.class # => Proc
1788 * h[:nosuch] # => "Default value for nosuch"
1791 static VALUE
1792 rb_hash_initialize(int argc, VALUE *argv, VALUE hash)
1794 VALUE ifnone;
1796 rb_hash_modify(hash);
1797 if (rb_block_given_p()) {
1798 rb_check_arity(argc, 0, 0);
1799 ifnone = rb_block_proc();
1800 SET_PROC_DEFAULT(hash, ifnone);
1802 else {
1803 rb_check_arity(argc, 0, 1);
1804 ifnone = argc == 0 ? Qnil : argv[0];
1805 RHASH_SET_IFNONE(hash, ifnone);
1808 return hash;
1812 * call-seq:
1813 * Hash[] -> new_empty_hash
1814 * Hash[hash] -> new_hash
1815 * Hash[ [*2_element_arrays] ] -> new_hash
1816 * Hash[*objects] -> new_hash
1818 * Returns a new \Hash object populated with the given objects, if any.
1819 * See Hash::new.
1821 * With no argument, returns a new empty \Hash.
1823 * When the single given argument is a \Hash, returns a new \Hash
1824 * populated with the entries from the given \Hash, excluding the
1825 * default value or proc.
1827 * h = {foo: 0, bar: 1, baz: 2}
1828 * Hash[h] # => {:foo=>0, :bar=>1, :baz=>2}
1830 * When the single given argument is an \Array of 2-element Arrays,
1831 * returns a new \Hash object wherein each 2-element array forms a
1832 * key-value entry:
1834 * Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {:foo=>0, :bar=>1}
1836 * When the argument count is an even number;
1837 * returns a new \Hash object wherein each successive pair of arguments
1838 * has become a key-value entry:
1840 * Hash[:foo, 0, :bar, 1] # => {:foo=>0, :bar=>1}
1842 * Raises an exception if the argument list does not conform to any
1843 * of the above.
1846 static VALUE
1847 rb_hash_s_create(int argc, VALUE *argv, VALUE klass)
1849 VALUE hash, tmp;
1851 if (argc == 1) {
1852 tmp = rb_hash_s_try_convert(Qnil, argv[0]);
1853 if (!NIL_P(tmp)) {
1854 hash = hash_alloc(klass);
1855 hash_copy(hash, tmp);
1856 return hash;
1859 tmp = rb_check_array_type(argv[0]);
1860 if (!NIL_P(tmp)) {
1861 long i;
1863 hash = hash_alloc(klass);
1864 for (i = 0; i < RARRAY_LEN(tmp); ++i) {
1865 VALUE e = RARRAY_AREF(tmp, i);
1866 VALUE v = rb_check_array_type(e);
1867 VALUE key, val = Qnil;
1869 if (NIL_P(v)) {
1870 rb_raise(rb_eArgError, "wrong element type %s at %ld (expected array)",
1871 rb_builtin_class_name(e), i);
1873 switch (RARRAY_LEN(v)) {
1874 default:
1875 rb_raise(rb_eArgError, "invalid number of elements (%ld for 1..2)",
1876 RARRAY_LEN(v));
1877 case 2:
1878 val = RARRAY_AREF(v, 1);
1879 case 1:
1880 key = RARRAY_AREF(v, 0);
1881 rb_hash_aset(hash, key, val);
1884 return hash;
1887 if (argc % 2 != 0) {
1888 rb_raise(rb_eArgError, "odd number of arguments for Hash");
1891 hash = hash_alloc(klass);
1892 rb_hash_bulk_insert(argc, argv, hash);
1893 hash_verify(hash);
1894 return hash;
1897 MJIT_FUNC_EXPORTED VALUE
1898 rb_to_hash_type(VALUE hash)
1900 return rb_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1902 #define to_hash rb_to_hash_type
1904 VALUE
1905 rb_check_hash_type(VALUE hash)
1907 return rb_check_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1911 * call-seq:
1912 * Hash.try_convert(obj) -> obj, new_hash, or nil
1914 * If +obj+ is a \Hash object, returns +obj+.
1916 * Otherwise if +obj+ responds to <tt>:to_hash</tt>,
1917 * calls <tt>obj.to_hash</tt> and returns the result.
1919 * Returns +nil+ if +obj+ does not respond to <tt>:to_hash</tt>
1921 * Raises an exception unless <tt>obj.to_hash</tt> returns a \Hash object.
1923 static VALUE
1924 rb_hash_s_try_convert(VALUE dummy, VALUE hash)
1926 return rb_check_hash_type(hash);
1930 * call-seq:
1931 * Hash.ruby2_keywords_hash?(hash) -> true or false
1933 * Checks if a given hash is flagged by Module#ruby2_keywords (or
1934 * Proc#ruby2_keywords).
1935 * This method is not for casual use; debugging, researching, and
1936 * some truly necessary cases like serialization of arguments.
1938 * ruby2_keywords def foo(*args)
1939 * Hash.ruby2_keywords_hash?(args.last)
1940 * end
1941 * foo(k: 1) #=> true
1942 * foo({k: 1}) #=> false
1944 static VALUE
1945 rb_hash_s_ruby2_keywords_hash_p(VALUE dummy, VALUE hash)
1947 Check_Type(hash, T_HASH);
1948 return RBOOL(RHASH(hash)->basic.flags & RHASH_PASS_AS_KEYWORDS);
1952 * call-seq:
1953 * Hash.ruby2_keywords_hash(hash) -> hash
1955 * Duplicates a given hash and adds a ruby2_keywords flag.
1956 * This method is not for casual use; debugging, researching, and
1957 * some truly necessary cases like deserialization of arguments.
1959 * h = {k: 1}
1960 * h = Hash.ruby2_keywords_hash(h)
1961 * def foo(k: 42)
1963 * end
1964 * foo(*[h]) #=> 1 with neither a warning or an error
1966 static VALUE
1967 rb_hash_s_ruby2_keywords_hash(VALUE dummy, VALUE hash)
1969 Check_Type(hash, T_HASH);
1970 hash = rb_hash_dup(hash);
1971 RHASH(hash)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
1972 return hash;
1975 struct rehash_arg {
1976 VALUE hash;
1977 st_table *tbl;
1980 static int
1981 rb_hash_rehash_i(VALUE key, VALUE value, VALUE arg)
1983 if (RHASH_AR_TABLE_P(arg)) {
1984 ar_insert(arg, (st_data_t)key, (st_data_t)value);
1986 else {
1987 st_insert(RHASH_ST_TABLE(arg), (st_data_t)key, (st_data_t)value);
1989 return ST_CONTINUE;
1993 * call-seq:
1994 * hash.rehash -> self
1996 * Rebuilds the hash table by recomputing the hash index for each key;
1997 * returns <tt>self</tt>.
1999 * The hash table becomes invalid if the hash value of a key
2000 * has changed after the entry was created.
2001 * See {Modifying an Active Hash Key}[#class-Hash-label-Modifying+an+Active+Hash+Key].
2004 VALUE
2005 rb_hash_rehash(VALUE hash)
2007 VALUE tmp;
2008 st_table *tbl;
2010 if (RHASH_ITER_LEV(hash) > 0) {
2011 rb_raise(rb_eRuntimeError, "rehash during iteration");
2013 rb_hash_modify_check(hash);
2014 if (RHASH_AR_TABLE_P(hash)) {
2015 tmp = hash_alloc(0);
2016 ar_alloc_table(tmp);
2017 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
2018 ar_free_and_clear_table(hash);
2019 ar_copy(hash, tmp);
2020 ar_free_and_clear_table(tmp);
2022 else if (RHASH_ST_TABLE_P(hash)) {
2023 st_table *old_tab = RHASH_ST_TABLE(hash);
2024 tmp = hash_alloc(0);
2025 tbl = st_init_table_with_size(old_tab->type, old_tab->num_entries);
2026 RHASH_ST_TABLE_SET(tmp, tbl);
2027 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
2028 st_free_table(old_tab);
2029 RHASH_ST_TABLE_SET(hash, tbl);
2030 RHASH_ST_CLEAR(tmp);
2032 hash_verify(hash);
2033 return hash;
2036 static VALUE
2037 call_default_proc(VALUE proc, VALUE hash, VALUE key)
2039 VALUE args[2] = {hash, key};
2040 return rb_proc_call_with_block(proc, 2, args, Qnil);
2043 VALUE
2044 rb_hash_default_value(VALUE hash, VALUE key)
2046 if (LIKELY(rb_method_basic_definition_p(CLASS_OF(hash), id_default))) {
2047 VALUE ifnone = RHASH_IFNONE(hash);
2048 if (!FL_TEST(hash, RHASH_PROC_DEFAULT)) return ifnone;
2049 if (key == Qundef) return Qnil;
2050 return call_default_proc(ifnone, hash, key);
2052 else {
2053 return rb_funcall(hash, id_default, 1, key);
2057 static inline int
2058 hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2060 hash_verify(hash);
2062 if (RHASH_AR_TABLE_P(hash)) {
2063 return ar_lookup(hash, key, pval);
2065 else {
2066 return st_lookup(RHASH_ST_TABLE(hash), key, pval);
2070 MJIT_FUNC_EXPORTED int
2071 rb_hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2073 return hash_stlike_lookup(hash, key, pval);
2077 * call-seq:
2078 * hash[key] -> value
2080 * Returns the value associated with the given +key+, if found:
2081 * h = {foo: 0, bar: 1, baz: 2}
2082 * h[:foo] # => 0
2084 * If +key+ is not found, returns a default value
2085 * (see {Default Values}[#class-Hash-label-Default+Values]):
2086 * h = {foo: 0, bar: 1, baz: 2}
2087 * h[:nosuch] # => nil
2090 VALUE
2091 rb_hash_aref(VALUE hash, VALUE key)
2093 st_data_t val;
2095 if (hash_stlike_lookup(hash, key, &val)) {
2096 return (VALUE)val;
2098 else {
2099 return rb_hash_default_value(hash, key);
2103 VALUE
2104 rb_hash_lookup2(VALUE hash, VALUE key, VALUE def)
2106 st_data_t val;
2108 if (hash_stlike_lookup(hash, key, &val)) {
2109 return (VALUE)val;
2111 else {
2112 return def; /* without Hash#default */
2116 VALUE
2117 rb_hash_lookup(VALUE hash, VALUE key)
2119 return rb_hash_lookup2(hash, key, Qnil);
2123 * call-seq:
2124 * hash.fetch(key) -> object
2125 * hash.fetch(key, default_value) -> object
2126 * hash.fetch(key) {|key| ... } -> object
2128 * Returns the value for the given +key+, if found.
2129 * h = {foo: 0, bar: 1, baz: 2}
2130 * h.fetch(:bar) # => 1
2132 * If +key+ is not found and no block was given,
2133 * returns +default_value+:
2134 * {}.fetch(:nosuch, :default) # => :default
2136 * If +key+ is not found and a block was given,
2137 * yields +key+ to the block and returns the block's return value:
2138 * {}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
2140 * Raises KeyError if neither +default_value+ nor a block was given.
2142 * Note that this method does not use the values of either #default or #default_proc.
2145 static VALUE
2146 rb_hash_fetch_m(int argc, VALUE *argv, VALUE hash)
2148 VALUE key;
2149 st_data_t val;
2150 long block_given;
2152 rb_check_arity(argc, 1, 2);
2153 key = argv[0];
2155 block_given = rb_block_given_p();
2156 if (block_given && argc == 2) {
2157 rb_warn("block supersedes default value argument");
2160 if (hash_stlike_lookup(hash, key, &val)) {
2161 return (VALUE)val;
2163 else {
2164 if (block_given) {
2165 return rb_yield(key);
2167 else if (argc == 1) {
2168 VALUE desc = rb_protect(rb_inspect, key, 0);
2169 if (NIL_P(desc)) {
2170 desc = rb_any_to_s(key);
2172 desc = rb_str_ellipsize(desc, 65);
2173 rb_key_err_raise(rb_sprintf("key not found: %"PRIsVALUE, desc), hash, key);
2175 else {
2176 return argv[1];
2181 VALUE
2182 rb_hash_fetch(VALUE hash, VALUE key)
2184 return rb_hash_fetch_m(1, &key, hash);
2188 * call-seq:
2189 * hash.default -> object
2190 * hash.default(key) -> object
2192 * Returns the default value for the given +key+.
2193 * The returned value will be determined either by the default proc or by the default value.
2194 * See {Default Values}[#class-Hash-label-Default+Values].
2196 * With no argument, returns the current default value:
2197 * h = {}
2198 * h.default # => nil
2200 * If +key+ is given, returns the default value for +key+,
2201 * regardless of whether that key exists:
2202 * h = Hash.new { |hash, key| hash[key] = "No key #{key}"}
2203 * h[:foo] = "Hello"
2204 * h.default(:foo) # => "No key foo"
2207 static VALUE
2208 rb_hash_default(int argc, VALUE *argv, VALUE hash)
2210 VALUE ifnone;
2212 rb_check_arity(argc, 0, 1);
2213 ifnone = RHASH_IFNONE(hash);
2214 if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2215 if (argc == 0) return Qnil;
2216 return call_default_proc(ifnone, hash, argv[0]);
2218 return ifnone;
2222 * call-seq:
2223 * hash.default = value -> object
2225 * Sets the default value to +value+; returns +value+:
2226 * h = {}
2227 * h.default # => nil
2228 * h.default = false # => false
2229 * h.default # => false
2231 * See {Default Values}[#class-Hash-label-Default+Values].
2234 static VALUE
2235 rb_hash_set_default(VALUE hash, VALUE ifnone)
2237 rb_hash_modify_check(hash);
2238 SET_DEFAULT(hash, ifnone);
2239 return ifnone;
2243 * call-seq:
2244 * hash.default_proc -> proc or nil
2246 * Returns the default proc for +self+
2247 * (see {Default Values}[#class-Hash-label-Default+Values]):
2248 * h = {}
2249 * h.default_proc # => nil
2250 * h.default_proc = proc {|hash, key| "Default value for #{key}" }
2251 * h.default_proc.class # => Proc
2254 static VALUE
2255 rb_hash_default_proc(VALUE hash)
2257 if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2258 return RHASH_IFNONE(hash);
2260 return Qnil;
2264 * call-seq:
2265 * hash.default_proc = proc -> proc
2267 * Sets the default proc for +self+ to +proc+:
2268 * (see {Default Values}[#class-Hash-label-Default+Values]):
2269 * h = {}
2270 * h.default_proc # => nil
2271 * h.default_proc = proc { |hash, key| "Default value for #{key}" }
2272 * h.default_proc.class # => Proc
2273 * h.default_proc = nil
2274 * h.default_proc # => nil
2277 VALUE
2278 rb_hash_set_default_proc(VALUE hash, VALUE proc)
2280 VALUE b;
2282 rb_hash_modify_check(hash);
2283 if (NIL_P(proc)) {
2284 SET_DEFAULT(hash, proc);
2285 return proc;
2287 b = rb_check_convert_type_with_id(proc, T_DATA, "Proc", idTo_proc);
2288 if (NIL_P(b) || !rb_obj_is_proc(b)) {
2289 rb_raise(rb_eTypeError,
2290 "wrong default_proc type %s (expected Proc)",
2291 rb_obj_classname(proc));
2293 proc = b;
2294 SET_PROC_DEFAULT(hash, proc);
2295 return proc;
2298 static int
2299 key_i(VALUE key, VALUE value, VALUE arg)
2301 VALUE *args = (VALUE *)arg;
2303 if (rb_equal(value, args[0])) {
2304 args[1] = key;
2305 return ST_STOP;
2307 return ST_CONTINUE;
2311 * call-seq:
2312 * hash.key(value) -> key or nil
2314 * Returns the key for the first-found entry with the given +value+
2315 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
2316 * h = {foo: 0, bar: 2, baz: 2}
2317 * h.key(0) # => :foo
2318 * h.key(2) # => :bar
2320 * Returns +nil+ if so such value is found.
2323 static VALUE
2324 rb_hash_key(VALUE hash, VALUE value)
2326 VALUE args[2];
2328 args[0] = value;
2329 args[1] = Qnil;
2331 rb_hash_foreach(hash, key_i, (VALUE)args);
2333 return args[1];
2337 rb_hash_stlike_delete(VALUE hash, st_data_t *pkey, st_data_t *pval)
2339 if (RHASH_AR_TABLE_P(hash)) {
2340 return ar_delete(hash, pkey, pval);
2342 else {
2343 return st_delete(RHASH_ST_TABLE(hash), pkey, pval);
2348 * delete a specified entry by a given key.
2349 * if there is the corresponding entry, return a value of the entry.
2350 * if there is no corresponding entry, return Qundef.
2352 VALUE
2353 rb_hash_delete_entry(VALUE hash, VALUE key)
2355 st_data_t ktmp = (st_data_t)key, val;
2357 if (rb_hash_stlike_delete(hash, &ktmp, &val)) {
2358 return (VALUE)val;
2360 else {
2361 return Qundef;
2366 * delete a specified entry by a given key.
2367 * if there is the corresponding entry, return a value of the entry.
2368 * if there is no corresponding entry, return Qnil.
2370 VALUE
2371 rb_hash_delete(VALUE hash, VALUE key)
2373 VALUE deleted_value = rb_hash_delete_entry(hash, key);
2375 if (deleted_value != Qundef) { /* likely pass */
2376 return deleted_value;
2378 else {
2379 return Qnil;
2384 * call-seq:
2385 * hash.delete(key) -> value or nil
2386 * hash.delete(key) {|key| ... } -> object
2388 * Deletes the entry for the given +key+ and returns its associated value.
2390 * If no block is given and +key+ is found, deletes the entry and returns the associated value:
2391 * h = {foo: 0, bar: 1, baz: 2}
2392 * h.delete(:bar) # => 1
2393 * h # => {:foo=>0, :baz=>2}
2395 * If no block given and +key+ is not found, returns +nil+.
2397 * If a block is given and +key+ is found, ignores the block,
2398 * deletes the entry, and returns the associated value:
2399 * h = {foo: 0, bar: 1, baz: 2}
2400 * h.delete(:baz) { |key| raise 'Will never happen'} # => 2
2401 * h # => {:foo=>0, :bar=>1}
2403 * If a block is given and +key+ is not found,
2404 * calls the block and returns the block's return value:
2405 * h = {foo: 0, bar: 1, baz: 2}
2406 * h.delete(:nosuch) { |key| "Key #{key} not found" } # => "Key nosuch not found"
2407 * h # => {:foo=>0, :bar=>1, :baz=>2}
2410 static VALUE
2411 rb_hash_delete_m(VALUE hash, VALUE key)
2413 VALUE val;
2415 rb_hash_modify_check(hash);
2416 val = rb_hash_delete_entry(hash, key);
2418 if (val != Qundef) {
2419 return val;
2421 else {
2422 if (rb_block_given_p()) {
2423 return rb_yield(key);
2425 else {
2426 return Qnil;
2431 struct shift_var {
2432 VALUE key;
2433 VALUE val;
2436 static int
2437 shift_i_safe(VALUE key, VALUE value, VALUE arg)
2439 struct shift_var *var = (struct shift_var *)arg;
2441 var->key = key;
2442 var->val = value;
2443 return ST_STOP;
2447 * call-seq:
2448 * hash.shift -> [key, value] or nil
2450 * Removes the first hash entry
2451 * (see {Entry Order}[#class-Hash-label-Entry+Order]);
2452 * returns a 2-element \Array containing the removed key and value:
2453 * h = {foo: 0, bar: 1, baz: 2}
2454 * h.shift # => [:foo, 0]
2455 * h # => {:bar=>1, :baz=>2}
2457 * Returns nil if the hash is empty.
2460 static VALUE
2461 rb_hash_shift(VALUE hash)
2463 struct shift_var var;
2465 rb_hash_modify_check(hash);
2466 if (RHASH_AR_TABLE_P(hash)) {
2467 var.key = Qundef;
2468 if (RHASH_ITER_LEV(hash) == 0) {
2469 if (ar_shift(hash, &var.key, &var.val)) {
2470 return rb_assoc_new(var.key, var.val);
2473 else {
2474 rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2475 if (var.key != Qundef) {
2476 rb_hash_delete_entry(hash, var.key);
2477 return rb_assoc_new(var.key, var.val);
2481 if (RHASH_ST_TABLE_P(hash)) {
2482 var.key = Qundef;
2483 if (RHASH_ITER_LEV(hash) == 0) {
2484 if (st_shift(RHASH_ST_TABLE(hash), &var.key, &var.val)) {
2485 return rb_assoc_new(var.key, var.val);
2488 else {
2489 rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2490 if (var.key != Qundef) {
2491 rb_hash_delete_entry(hash, var.key);
2492 return rb_assoc_new(var.key, var.val);
2496 return Qnil;
2499 static int
2500 delete_if_i(VALUE key, VALUE value, VALUE hash)
2502 if (RTEST(rb_yield_values(2, key, value))) {
2503 rb_hash_modify(hash);
2504 return ST_DELETE;
2506 return ST_CONTINUE;
2509 static VALUE
2510 hash_enum_size(VALUE hash, VALUE args, VALUE eobj)
2512 return rb_hash_size(hash);
2516 * call-seq:
2517 * hash.delete_if {|key, value| ... } -> self
2518 * hash.delete_if -> new_enumerator
2520 * If a block given, calls the block with each key-value pair;
2521 * deletes each entry for which the block returns a truthy value;
2522 * returns +self+:
2523 * h = {foo: 0, bar: 1, baz: 2}
2524 * h.delete_if {|key, value| value > 0 } # => {:foo=>0}
2526 * If no block given, returns a new \Enumerator:
2527 * h = {foo: 0, bar: 1, baz: 2}
2528 * e = h.delete_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:delete_if>
2529 * e.each { |key, value| value > 0 } # => {:foo=>0}
2532 VALUE
2533 rb_hash_delete_if(VALUE hash)
2535 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2536 rb_hash_modify_check(hash);
2537 if (!RHASH_TABLE_EMPTY_P(hash)) {
2538 rb_hash_foreach(hash, delete_if_i, hash);
2540 return hash;
2544 * call-seq:
2545 * hash.reject! {|key, value| ... } -> self or nil
2546 * hash.reject! -> new_enumerator
2548 * Returns +self+, whose remaining entries are those
2549 * for which the block returns +false+ or +nil+:
2550 * h = {foo: 0, bar: 1, baz: 2}
2551 * h.reject! {|key, value| value < 2 } # => {:baz=>2}
2553 * Returns +nil+ if no entries are removed.
2555 * Returns a new \Enumerator if no block given:
2556 * h = {foo: 0, bar: 1, baz: 2}
2557 * e = h.reject! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject!>
2558 * e.each {|key, value| key.start_with?('b') } # => {:foo=>0}
2561 static VALUE
2562 rb_hash_reject_bang(VALUE hash)
2564 st_index_t n;
2566 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2567 rb_hash_modify(hash);
2568 n = RHASH_SIZE(hash);
2569 if (!n) return Qnil;
2570 rb_hash_foreach(hash, delete_if_i, hash);
2571 if (n == RHASH_SIZE(hash)) return Qnil;
2572 return hash;
2576 * call-seq:
2577 * hash.reject {|key, value| ... } -> new_hash
2578 * hash.reject -> new_enumerator
2580 * Returns a new \Hash object whose entries are all those
2581 * from +self+ for which the block returns +false+ or +nil+:
2582 * h = {foo: 0, bar: 1, baz: 2}
2583 * h1 = h.reject {|key, value| key.start_with?('b') }
2584 * h1 # => {:foo=>0}
2586 * Returns a new \Enumerator if no block given:
2587 * h = {foo: 0, bar: 1, baz: 2}
2588 * e = h.reject # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject>
2589 * h1 = e.each {|key, value| key.start_with?('b') }
2590 * h1 # => {:foo=>0}
2593 static VALUE
2594 rb_hash_reject(VALUE hash)
2596 VALUE result;
2598 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2599 result = hash_dup_with_compare_by_id(hash);
2600 if (!RHASH_EMPTY_P(hash)) {
2601 rb_hash_foreach(result, delete_if_i, result);
2603 return result;
2607 * call-seq:
2608 * hash.slice(*keys) -> new_hash
2610 * Returns a new \Hash object containing the entries for the given +keys+:
2611 * h = {foo: 0, bar: 1, baz: 2}
2612 * h.slice(:baz, :foo) # => {:baz=>2, :foo=>0}
2614 * Any given +keys+ that are not found are ignored.
2617 static VALUE
2618 rb_hash_slice(int argc, VALUE *argv, VALUE hash)
2620 int i;
2621 VALUE key, value, result;
2623 if (argc == 0 || RHASH_EMPTY_P(hash)) {
2624 return copy_compare_by_id(rb_hash_new(), hash);
2626 result = copy_compare_by_id(rb_hash_new_with_size(argc), hash);
2628 for (i = 0; i < argc; i++) {
2629 key = argv[i];
2630 value = rb_hash_lookup2(hash, key, Qundef);
2631 if (value != Qundef)
2632 rb_hash_aset(result, key, value);
2635 return result;
2639 * call-seq:
2640 * hsh.except(*keys) -> a_hash
2642 * Returns a new \Hash excluding entries for the given +keys+:
2643 * h = { a: 100, b: 200, c: 300 }
2644 * h.except(:a) #=> {:b=>200, :c=>300}
2646 * Any given +keys+ that are not found are ignored.
2649 static VALUE
2650 rb_hash_except(int argc, VALUE *argv, VALUE hash)
2652 int i;
2653 VALUE key, result;
2655 result = hash_dup_with_compare_by_id(hash);
2657 for (i = 0; i < argc; i++) {
2658 key = argv[i];
2659 rb_hash_delete(result, key);
2662 return result;
2666 * call-seq:
2667 * hash.values_at(*keys) -> new_array
2669 * Returns a new \Array containing values for the given +keys+:
2670 * h = {foo: 0, bar: 1, baz: 2}
2671 * h.values_at(:baz, :foo) # => [2, 0]
2673 * The {default values}[#class-Hash-label-Default+Values] are returned
2674 * for any keys that are not found:
2675 * h.values_at(:hello, :foo) # => [nil, 0]
2678 static VALUE
2679 rb_hash_values_at(int argc, VALUE *argv, VALUE hash)
2681 VALUE result = rb_ary_new2(argc);
2682 long i;
2684 for (i=0; i<argc; i++) {
2685 rb_ary_push(result, rb_hash_aref(hash, argv[i]));
2687 return result;
2691 * call-seq:
2692 * hash.fetch_values(*keys) -> new_array
2693 * hash.fetch_values(*keys) {|key| ... } -> new_array
2695 * Returns a new \Array containing the values associated with the given keys *keys:
2696 * h = {foo: 0, bar: 1, baz: 2}
2697 * h.fetch_values(:baz, :foo) # => [2, 0]
2699 * Returns a new empty \Array if no arguments given.
2701 * When a block is given, calls the block with each missing key,
2702 * treating the block's return value as the value for that key:
2703 * h = {foo: 0, bar: 1, baz: 2}
2704 * values = h.fetch_values(:bar, :foo, :bad, :bam) {|key| key.to_s}
2705 * values # => [1, 0, "bad", "bam"]
2707 * When no block is given, raises an exception if any given key is not found.
2710 static VALUE
2711 rb_hash_fetch_values(int argc, VALUE *argv, VALUE hash)
2713 VALUE result = rb_ary_new2(argc);
2714 long i;
2716 for (i=0; i<argc; i++) {
2717 rb_ary_push(result, rb_hash_fetch(hash, argv[i]));
2719 return result;
2722 static int
2723 keep_if_i(VALUE key, VALUE value, VALUE hash)
2725 if (!RTEST(rb_yield_values(2, key, value))) {
2726 rb_hash_modify(hash);
2727 return ST_DELETE;
2729 return ST_CONTINUE;
2733 * call-seq:
2734 * hash.select {|key, value| ... } -> new_hash
2735 * hash.select -> new_enumerator
2737 * Hash#filter is an alias for Hash#select.
2739 * Returns a new \Hash object whose entries are those for which the block returns a truthy value:
2740 * h = {foo: 0, bar: 1, baz: 2}
2741 * h.select {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2743 * Returns a new \Enumerator if no block given:
2744 * h = {foo: 0, bar: 1, baz: 2}
2745 * e = h.select # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select>
2746 * e.each {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2749 static VALUE
2750 rb_hash_select(VALUE hash)
2752 VALUE result;
2754 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2755 result = hash_dup_with_compare_by_id(hash);
2756 if (!RHASH_EMPTY_P(hash)) {
2757 rb_hash_foreach(result, keep_if_i, result);
2759 return result;
2763 * call-seq:
2764 * hash.select! {|key, value| ... } -> self or nil
2765 * hash.select! -> new_enumerator
2767 * Hash#filter! is an alias for Hash#select!.
2769 * Returns +self+, whose entries are those for which the block returns a truthy value:
2770 * h = {foo: 0, bar: 1, baz: 2}
2771 * h.select! {|key, value| value < 2 } => {:foo=>0, :bar=>1}
2773 * Returns +nil+ if no entries were removed.
2775 * Returns a new \Enumerator if no block given:
2776 * h = {foo: 0, bar: 1, baz: 2}
2777 * e = h.select! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select!>
2778 * e.each { |key, value| value < 2 } # => {:foo=>0, :bar=>1}
2781 static VALUE
2782 rb_hash_select_bang(VALUE hash)
2784 st_index_t n;
2786 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2787 rb_hash_modify_check(hash);
2788 n = RHASH_SIZE(hash);
2789 if (!n) return Qnil;
2790 rb_hash_foreach(hash, keep_if_i, hash);
2791 if (n == RHASH_SIZE(hash)) return Qnil;
2792 return hash;
2796 * call-seq:
2797 * hash.keep_if {|key, value| ... } -> self
2798 * hash.keep_if -> new_enumerator
2800 * Calls the block for each key-value pair;
2801 * retains the entry if the block returns a truthy value;
2802 * otherwise deletes the entry; returns +self+.
2803 * h = {foo: 0, bar: 1, baz: 2}
2804 * h.keep_if { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2806 * Returns a new \Enumerator if no block given:
2807 * h = {foo: 0, bar: 1, baz: 2}
2808 * e = h.keep_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:keep_if>
2809 * e.each { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2812 static VALUE
2813 rb_hash_keep_if(VALUE hash)
2815 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2816 rb_hash_modify_check(hash);
2817 if (!RHASH_TABLE_EMPTY_P(hash)) {
2818 rb_hash_foreach(hash, keep_if_i, hash);
2820 return hash;
2823 static int
2824 clear_i(VALUE key, VALUE value, VALUE dummy)
2826 return ST_DELETE;
2830 * call-seq:
2831 * hash.clear -> self
2833 * Removes all hash entries; returns +self+.
2836 VALUE
2837 rb_hash_clear(VALUE hash)
2839 rb_hash_modify_check(hash);
2841 if (RHASH_ITER_LEV(hash) > 0) {
2842 rb_hash_foreach(hash, clear_i, 0);
2844 else if (RHASH_AR_TABLE_P(hash)) {
2845 ar_clear(hash);
2847 else {
2848 st_clear(RHASH_ST_TABLE(hash));
2851 return hash;
2854 static int
2855 hash_aset(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2857 *val = arg->arg;
2858 return ST_CONTINUE;
2861 VALUE
2862 rb_hash_key_str(VALUE key)
2864 if (!RB_FL_ANY_RAW(key, FL_EXIVAR) && RBASIC_CLASS(key) == rb_cString) {
2865 return rb_fstring(key);
2867 else {
2868 return rb_str_new_frozen(key);
2872 static int
2873 hash_aset_str(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2875 if (!existing && !RB_OBJ_FROZEN(*key)) {
2876 *key = rb_hash_key_str(*key);
2878 return hash_aset(key, val, arg, existing);
2881 NOINSERT_UPDATE_CALLBACK(hash_aset)
2882 NOINSERT_UPDATE_CALLBACK(hash_aset_str)
2885 * call-seq:
2886 * hash[key] = value -> value
2887 * hash.store(key, value)
2889 * Hash#store is an alias for Hash#[]=.
2891 * Associates the given +value+ with the given +key+; returns +value+.
2893 * If the given +key+ exists, replaces its value with the given +value+;
2894 * the ordering is not affected
2895 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
2896 * h = {foo: 0, bar: 1}
2897 * h[:foo] = 2 # => 2
2898 * h.store(:bar, 3) # => 3
2899 * h # => {:foo=>2, :bar=>3}
2901 * If +key+ does not exist, adds the +key+ and +value+;
2902 * the new entry is last in the order
2903 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
2904 * h = {foo: 0, bar: 1}
2905 * h[:baz] = 2 # => 2
2906 * h.store(:bat, 3) # => 3
2907 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
2910 VALUE
2911 rb_hash_aset(VALUE hash, VALUE key, VALUE val)
2913 int iter_lev = RHASH_ITER_LEV(hash);
2915 rb_hash_modify(hash);
2917 if (RHASH_TABLE_NULL_P(hash)) {
2918 if (iter_lev > 0) no_new_key();
2919 ar_alloc_table(hash);
2922 if (RHASH_TYPE(hash) == &identhash || rb_obj_class(key) != rb_cString) {
2923 RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset, val);
2925 else {
2926 RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset_str, val);
2928 return val;
2932 * call-seq:
2933 * hash.replace(other_hash) -> self
2935 * Replaces the entire contents of +self+ with the contents of +other_hash+;
2936 * returns +self+:
2937 * h = {foo: 0, bar: 1, baz: 2}
2938 * h.replace({bat: 3, bam: 4}) # => {:bat=>3, :bam=>4}
2941 static VALUE
2942 rb_hash_replace(VALUE hash, VALUE hash2)
2944 rb_hash_modify_check(hash);
2945 if (hash == hash2) return hash;
2946 if (RHASH_ITER_LEV(hash) > 0) {
2947 rb_raise(rb_eRuntimeError, "can't replace hash during iteration");
2949 hash2 = to_hash(hash2);
2951 COPY_DEFAULT(hash, hash2);
2953 if (RHASH_AR_TABLE_P(hash)) {
2954 ar_free_and_clear_table(hash);
2956 else {
2957 st_free_table(RHASH_ST_TABLE(hash));
2958 RHASH_ST_CLEAR(hash);
2960 hash_copy(hash, hash2);
2961 if (RHASH_EMPTY_P(hash2) && RHASH_ST_TABLE_P(hash2)) {
2962 /* ident hash */
2963 RHASH_ST_TABLE_SET(hash, st_init_table_with_size(RHASH_TYPE(hash2), 0));
2966 rb_gc_writebarrier_remember(hash);
2968 return hash;
2972 * call-seq:
2973 * hash.length -> integer
2974 * hash.size -> integer
2976 * Returns the count of entries in +self+:
2977 * {foo: 0, bar: 1, baz: 2}.length # => 3
2979 * Hash#length is an alias for Hash#size.
2982 VALUE
2983 rb_hash_size(VALUE hash)
2985 return INT2FIX(RHASH_SIZE(hash));
2988 size_t
2989 rb_hash_size_num(VALUE hash)
2991 return (long)RHASH_SIZE(hash);
2995 * call-seq:
2996 * hash.empty? -> true or false
2998 * Returns +true+ if there are no hash entries, +false+ otherwise:
2999 * {}.empty? # => true
3000 * {foo: 0, bar: 1, baz: 2}.empty? # => false
3003 static VALUE
3004 rb_hash_empty_p(VALUE hash)
3006 return RBOOL(RHASH_EMPTY_P(hash));
3009 static int
3010 each_value_i(VALUE key, VALUE value, VALUE _)
3012 rb_yield(value);
3013 return ST_CONTINUE;
3017 * call-seq:
3018 * hash.each_value {|value| ... } -> self
3019 * hash.each_value -> new_enumerator
3021 * Calls the given block with each value; returns +self+:
3022 * h = {foo: 0, bar: 1, baz: 2}
3023 * h.each_value {|value| puts value } # => {:foo=>0, :bar=>1, :baz=>2}
3024 * Output:
3029 * Returns a new \Enumerator if no block given:
3030 * h = {foo: 0, bar: 1, baz: 2}
3031 * e = h.each_value # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_value>
3032 * h1 = e.each {|value| puts value }
3033 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3034 * Output:
3040 static VALUE
3041 rb_hash_each_value(VALUE hash)
3043 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3044 rb_hash_foreach(hash, each_value_i, 0);
3045 return hash;
3048 static int
3049 each_key_i(VALUE key, VALUE value, VALUE _)
3051 rb_yield(key);
3052 return ST_CONTINUE;
3056 * call-seq:
3057 * hash.each_key {|key| ... } -> self
3058 * hash.each_key -> new_enumerator
3060 * Calls the given block with each key; returns +self+:
3061 * h = {foo: 0, bar: 1, baz: 2}
3062 * h.each_key {|key| puts key } # => {:foo=>0, :bar=>1, :baz=>2}
3063 * Output:
3064 * foo
3065 * bar
3066 * baz
3068 * Returns a new \Enumerator if no block given:
3069 * h = {foo: 0, bar: 1, baz: 2}
3070 * e = h.each_key # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_key>
3071 * h1 = e.each {|key| puts key }
3072 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3073 * Output:
3074 * foo
3075 * bar
3076 * baz
3078 static VALUE
3079 rb_hash_each_key(VALUE hash)
3081 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3082 rb_hash_foreach(hash, each_key_i, 0);
3083 return hash;
3086 static int
3087 each_pair_i(VALUE key, VALUE value, VALUE _)
3089 rb_yield(rb_assoc_new(key, value));
3090 return ST_CONTINUE;
3093 static int
3094 each_pair_i_fast(VALUE key, VALUE value, VALUE _)
3096 VALUE argv[2];
3097 argv[0] = key;
3098 argv[1] = value;
3099 rb_yield_values2(2, argv);
3100 return ST_CONTINUE;
3104 * call-seq:
3105 * hash.each {|key, value| ... } -> self
3106 * hash.each_pair {|key, value| ... } -> self
3107 * hash.each -> new_enumerator
3108 * hash.each_pair -> new_enumerator
3110 * Hash#each is an alias for Hash#each_pair.
3112 * Calls the given block with each key-value pair; returns +self+:
3113 * h = {foo: 0, bar: 1, baz: 2}
3114 * h.each_pair {|key, value| puts "#{key}: #{value}"} # => {:foo=>0, :bar=>1, :baz=>2}
3115 * Output:
3116 * foo: 0
3117 * bar: 1
3118 * baz: 2
3120 * Returns a new \Enumerator if no block given:
3121 * h = {foo: 0, bar: 1, baz: 2}
3122 * e = h.each_pair # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_pair>
3123 * h1 = e.each {|key, value| puts "#{key}: #{value}"}
3124 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3125 * Output:
3126 * foo: 0
3127 * bar: 1
3128 * baz: 2
3131 static VALUE
3132 rb_hash_each_pair(VALUE hash)
3134 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3135 if (rb_block_pair_yield_optimizable())
3136 rb_hash_foreach(hash, each_pair_i_fast, 0);
3137 else
3138 rb_hash_foreach(hash, each_pair_i, 0);
3139 return hash;
3142 struct transform_keys_args{
3143 VALUE trans;
3144 VALUE result;
3145 int block_given;
3148 static int
3149 transform_keys_hash_i(VALUE key, VALUE value, VALUE transarg)
3151 struct transform_keys_args *p = (void *)transarg;
3152 VALUE trans = p->trans, result = p->result;
3153 VALUE new_key = rb_hash_lookup2(trans, key, Qundef);
3154 if (new_key == Qundef) {
3155 if (p->block_given)
3156 new_key = rb_yield(key);
3157 else
3158 new_key = key;
3160 rb_hash_aset(result, new_key, value);
3161 return ST_CONTINUE;
3164 static int
3165 transform_keys_i(VALUE key, VALUE value, VALUE result)
3167 VALUE new_key = rb_yield(key);
3168 rb_hash_aset(result, new_key, value);
3169 return ST_CONTINUE;
3173 * call-seq:
3174 * hash.transform_keys {|key| ... } -> new_hash
3175 * hash.transform_keys(hash2) -> new_hash
3176 * hash.transform_keys(hash2) {|other_key| ...} -> new_hash
3177 * hash.transform_keys -> new_enumerator
3179 * Returns a new \Hash object; each entry has:
3180 * * A key provided by the block.
3181 * * The value from +self+.
3183 * An optional hash argument can be provided to map keys to new keys.
3184 * Any key not given will be mapped using the provided block,
3185 * or remain the same if no block is given.
3187 * Transform keys:
3188 * h = {foo: 0, bar: 1, baz: 2}
3189 * h1 = h.transform_keys {|key| key.to_s }
3190 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3192 * h.transform_keys(foo: :bar, bar: :foo)
3193 * #=> {bar: 0, foo: 1, baz: 2}
3195 * h.transform_keys(foo: :hello, &:to_s)
3196 * #=> {:hello=>0, "bar"=>1, "baz"=>2}
3198 * Overwrites values for duplicate keys:
3199 * h = {foo: 0, bar: 1, baz: 2}
3200 * h1 = h.transform_keys {|key| :bat }
3201 * h1 # => {:bat=>2}
3203 * Returns a new \Enumerator if no block given:
3204 * h = {foo: 0, bar: 1, baz: 2}
3205 * e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys>
3206 * h1 = e.each { |key| key.to_s }
3207 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3209 static VALUE
3210 rb_hash_transform_keys(int argc, VALUE *argv, VALUE hash)
3212 VALUE result;
3213 struct transform_keys_args transarg = {0};
3215 argc = rb_check_arity(argc, 0, 1);
3216 if (argc > 0) {
3217 transarg.trans = to_hash(argv[0]);
3218 transarg.block_given = rb_block_given_p();
3220 else {
3221 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3223 result = rb_hash_new();
3224 if (!RHASH_EMPTY_P(hash)) {
3225 if (transarg.trans) {
3226 transarg.result = result;
3227 rb_hash_foreach(hash, transform_keys_hash_i, (VALUE)&transarg);
3229 else {
3230 rb_hash_foreach(hash, transform_keys_i, result);
3234 return result;
3237 static int flatten_i(VALUE key, VALUE val, VALUE ary);
3240 * call-seq:
3241 * hash.transform_keys! {|key| ... } -> self
3242 * hash.transform_keys!(hash2) -> self
3243 * hash.transform_keys!(hash2) {|other_key| ...} -> self
3244 * hash.transform_keys! -> new_enumerator
3246 * Same as Hash#transform_keys but modifies the receiver in place
3247 * instead of returning a new hash.
3249 static VALUE
3250 rb_hash_transform_keys_bang(int argc, VALUE *argv, VALUE hash)
3252 VALUE trans = 0;
3253 int block_given = 0;
3255 argc = rb_check_arity(argc, 0, 1);
3256 if (argc > 0) {
3257 trans = to_hash(argv[0]);
3258 block_given = rb_block_given_p();
3260 else {
3261 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3263 rb_hash_modify_check(hash);
3264 if (!RHASH_TABLE_EMPTY_P(hash)) {
3265 long i;
3266 VALUE new_keys = hash_alloc(0);
3267 VALUE pairs = rb_ary_tmp_new(RHASH_SIZE(hash) * 2);
3268 rb_hash_foreach(hash, flatten_i, pairs);
3269 for (i = 0; i < RARRAY_LEN(pairs); i += 2) {
3270 VALUE key = RARRAY_AREF(pairs, i), new_key, val;
3272 if (!trans) {
3273 new_key = rb_yield(key);
3275 else if ((new_key = rb_hash_lookup2(trans, key, Qundef)) != Qundef) {
3276 /* use the transformed key */
3278 else if (block_given) {
3279 new_key = rb_yield(key);
3281 else {
3282 new_key = key;
3284 val = RARRAY_AREF(pairs, i+1);
3285 if (!hash_stlike_lookup(new_keys, key, NULL)) {
3286 rb_hash_stlike_delete(hash, &key, NULL);
3288 rb_hash_aset(hash, new_key, val);
3289 rb_hash_aset(new_keys, new_key, Qnil);
3291 rb_ary_clear(pairs);
3292 rb_hash_clear(new_keys);
3294 return hash;
3297 static int
3298 transform_values_foreach_func(st_data_t key, st_data_t value, st_data_t argp, int error)
3300 return ST_REPLACE;
3303 static int
3304 transform_values_foreach_replace(st_data_t *key, st_data_t *value, st_data_t argp, int existing)
3306 VALUE new_value = rb_yield((VALUE)*value);
3307 VALUE hash = (VALUE)argp;
3308 rb_hash_modify(hash);
3309 RB_OBJ_WRITE(hash, value, new_value);
3310 return ST_CONTINUE;
3314 * call-seq:
3315 * hash.transform_values {|value| ... } -> new_hash
3316 * hash.transform_values -> new_enumerator
3318 * Returns a new \Hash object; each entry has:
3319 * * A key from +self+.
3320 * * A value provided by the block.
3322 * Transform values:
3323 * h = {foo: 0, bar: 1, baz: 2}
3324 * h1 = h.transform_values {|value| value * 100}
3325 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3327 * Returns a new \Enumerator if no block given:
3328 * h = {foo: 0, bar: 1, baz: 2}
3329 * e = h.transform_values # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_values>
3330 * h1 = e.each { |value| value * 100}
3331 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3333 static VALUE
3334 rb_hash_transform_values(VALUE hash)
3336 VALUE result;
3338 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3339 result = hash_dup_with_compare_by_id(hash);
3340 SET_DEFAULT(result, Qnil);
3342 if (!RHASH_EMPTY_P(hash)) {
3343 rb_hash_stlike_foreach_with_replace(result, transform_values_foreach_func, transform_values_foreach_replace, result);
3346 return result;
3350 * call-seq:
3351 * hash.transform_values! {|value| ... } -> self
3352 * hash.transform_values! -> new_enumerator
3354 * Returns +self+, whose keys are unchanged, and whose values are determined by the given block.
3355 * h = {foo: 0, bar: 1, baz: 2}
3356 * h.transform_values! {|value| value * 100} # => {:foo=>0, :bar=>100, :baz=>200}
3358 * Returns a new \Enumerator if no block given:
3359 * h = {foo: 0, bar: 1, baz: 2}
3360 * e = h.transform_values! # => #<Enumerator: {:foo=>0, :bar=>100, :baz=>200}:transform_values!>
3361 * h1 = e.each {|value| value * 100}
3362 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3364 static VALUE
3365 rb_hash_transform_values_bang(VALUE hash)
3367 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3368 rb_hash_modify_check(hash);
3370 if (!RHASH_TABLE_EMPTY_P(hash)) {
3371 rb_hash_stlike_foreach_with_replace(hash, transform_values_foreach_func, transform_values_foreach_replace, hash);
3374 return hash;
3377 static int
3378 to_a_i(VALUE key, VALUE value, VALUE ary)
3380 rb_ary_push(ary, rb_assoc_new(key, value));
3381 return ST_CONTINUE;
3385 * call-seq:
3386 * hash.to_a -> new_array
3388 * Returns a new \Array of 2-element \Array objects;
3389 * each nested \Array contains a key-value pair from +self+:
3390 * h = {foo: 0, bar: 1, baz: 2}
3391 * h.to_a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3394 static VALUE
3395 rb_hash_to_a(VALUE hash)
3397 VALUE ary;
3399 ary = rb_ary_new_capa(RHASH_SIZE(hash));
3400 rb_hash_foreach(hash, to_a_i, ary);
3402 return ary;
3405 static int
3406 inspect_i(VALUE key, VALUE value, VALUE str)
3408 VALUE str2;
3410 str2 = rb_inspect(key);
3411 if (RSTRING_LEN(str) > 1) {
3412 rb_str_buf_cat_ascii(str, ", ");
3414 else {
3415 rb_enc_copy(str, str2);
3417 rb_str_buf_append(str, str2);
3418 rb_str_buf_cat_ascii(str, "=>");
3419 str2 = rb_inspect(value);
3420 rb_str_buf_append(str, str2);
3422 return ST_CONTINUE;
3425 static VALUE
3426 inspect_hash(VALUE hash, VALUE dummy, int recur)
3428 VALUE str;
3430 if (recur) return rb_usascii_str_new2("{...}");
3431 str = rb_str_buf_new2("{");
3432 rb_hash_foreach(hash, inspect_i, str);
3433 rb_str_buf_cat2(str, "}");
3435 return str;
3439 * call-seq:
3440 * hash.inspect -> new_string
3442 * Returns a new \String containing the hash entries:
3443 * h = {foo: 0, bar: 1, baz: 2}
3444 * h.inspect # => "{:foo=>0, :bar=>1, :baz=>2}"
3446 * Hash#to_s is an alias for Hash#inspect.
3449 static VALUE
3450 rb_hash_inspect(VALUE hash)
3452 if (RHASH_EMPTY_P(hash))
3453 return rb_usascii_str_new2("{}");
3454 return rb_exec_recursive(inspect_hash, hash, 0);
3458 * call-seq:
3459 * hash.to_hash -> self
3461 * Returns +self+.
3463 static VALUE
3464 rb_hash_to_hash(VALUE hash)
3466 return hash;
3469 VALUE
3470 rb_hash_set_pair(VALUE hash, VALUE arg)
3472 VALUE pair;
3474 pair = rb_check_array_type(arg);
3475 if (NIL_P(pair)) {
3476 rb_raise(rb_eTypeError, "wrong element type %s (expected array)",
3477 rb_builtin_class_name(arg));
3479 if (RARRAY_LEN(pair) != 2) {
3480 rb_raise(rb_eArgError, "element has wrong array length (expected 2, was %ld)",
3481 RARRAY_LEN(pair));
3483 rb_hash_aset(hash, RARRAY_AREF(pair, 0), RARRAY_AREF(pair, 1));
3484 return hash;
3487 static int
3488 to_h_i(VALUE key, VALUE value, VALUE hash)
3490 rb_hash_set_pair(hash, rb_yield_values(2, key, value));
3491 return ST_CONTINUE;
3494 static VALUE
3495 rb_hash_to_h_block(VALUE hash)
3497 VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
3498 rb_hash_foreach(hash, to_h_i, h);
3499 return h;
3503 * call-seq:
3504 * hash.to_h -> self or new_hash
3505 * hash.to_h {|key, value| ... } -> new_hash
3507 * For an instance of \Hash, returns +self+.
3509 * For a subclass of \Hash, returns a new \Hash
3510 * containing the content of +self+.
3512 * When a block is given, returns a new \Hash object
3513 * whose content is based on the block;
3514 * the block should return a 2-element \Array object
3515 * specifying the key-value pair to be included in the returned \Array:
3516 * h = {foo: 0, bar: 1, baz: 2}
3517 * h1 = h.to_h {|key, value| [value, key] }
3518 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3521 static VALUE
3522 rb_hash_to_h(VALUE hash)
3524 if (rb_block_given_p()) {
3525 return rb_hash_to_h_block(hash);
3527 if (rb_obj_class(hash) != rb_cHash) {
3528 const VALUE flags = RBASIC(hash)->flags;
3529 hash = hash_dup(hash, rb_cHash, flags & RHASH_PROC_DEFAULT);
3531 return hash;
3534 static int
3535 keys_i(VALUE key, VALUE value, VALUE ary)
3537 rb_ary_push(ary, key);
3538 return ST_CONTINUE;
3542 * call-seq:
3543 * hash.keys -> new_array
3545 * Returns a new \Array containing all keys in +self+:
3546 * h = {foo: 0, bar: 1, baz: 2}
3547 * h.keys # => [:foo, :bar, :baz]
3550 MJIT_FUNC_EXPORTED VALUE
3551 rb_hash_keys(VALUE hash)
3553 st_index_t size = RHASH_SIZE(hash);
3554 VALUE keys = rb_ary_new_capa(size);
3556 if (size == 0) return keys;
3558 if (ST_DATA_COMPATIBLE_P(VALUE)) {
3559 RARRAY_PTR_USE_TRANSIENT(keys, ptr, {
3560 if (RHASH_AR_TABLE_P(hash)) {
3561 size = ar_keys(hash, ptr, size);
3563 else {
3564 st_table *table = RHASH_ST_TABLE(hash);
3565 size = st_keys(table, ptr, size);
3568 rb_gc_writebarrier_remember(keys);
3569 rb_ary_set_len(keys, size);
3571 else {
3572 rb_hash_foreach(hash, keys_i, keys);
3575 return keys;
3578 static int
3579 values_i(VALUE key, VALUE value, VALUE ary)
3581 rb_ary_push(ary, value);
3582 return ST_CONTINUE;
3586 * call-seq:
3587 * hash.values -> new_array
3589 * Returns a new \Array containing all values in +self+:
3590 * h = {foo: 0, bar: 1, baz: 2}
3591 * h.values # => [0, 1, 2]
3594 VALUE
3595 rb_hash_values(VALUE hash)
3597 VALUE values;
3598 st_index_t size = RHASH_SIZE(hash);
3600 values = rb_ary_new_capa(size);
3601 if (size == 0) return values;
3603 if (ST_DATA_COMPATIBLE_P(VALUE)) {
3604 if (RHASH_AR_TABLE_P(hash)) {
3605 rb_gc_writebarrier_remember(values);
3606 RARRAY_PTR_USE_TRANSIENT(values, ptr, {
3607 size = ar_values(hash, ptr, size);
3610 else if (RHASH_ST_TABLE_P(hash)) {
3611 st_table *table = RHASH_ST_TABLE(hash);
3612 rb_gc_writebarrier_remember(values);
3613 RARRAY_PTR_USE_TRANSIENT(values, ptr, {
3614 size = st_values(table, ptr, size);
3617 rb_ary_set_len(values, size);
3620 else {
3621 rb_hash_foreach(hash, values_i, values);
3624 return values;
3628 * call-seq:
3629 * hash.include?(key) -> true or false
3630 * hash.has_key?(key) -> true or false
3631 * hash.key?(key) -> true or false
3632 * hash.member?(key) -> true or false
3634 * Methods #has_key?, #key?, and #member? are aliases for \#include?.
3636 * Returns +true+ if +key+ is a key in +self+, otherwise +false+.
3639 MJIT_FUNC_EXPORTED VALUE
3640 rb_hash_has_key(VALUE hash, VALUE key)
3642 return RBOOL(hash_stlike_lookup(hash, key, NULL));
3645 static int
3646 rb_hash_search_value(VALUE key, VALUE value, VALUE arg)
3648 VALUE *data = (VALUE *)arg;
3650 if (rb_equal(value, data[1])) {
3651 data[0] = Qtrue;
3652 return ST_STOP;
3654 return ST_CONTINUE;
3658 * call-seq:
3659 * hash.has_value?(value) -> true or false
3660 * hash.value?(value) -> true or false
3662 * Method #value? is an alias for \#has_value?.
3664 * Returns +true+ if +value+ is a value in +self+, otherwise +false+.
3667 static VALUE
3668 rb_hash_has_value(VALUE hash, VALUE val)
3670 VALUE data[2];
3672 data[0] = Qfalse;
3673 data[1] = val;
3674 rb_hash_foreach(hash, rb_hash_search_value, (VALUE)data);
3675 return data[0];
3678 struct equal_data {
3679 VALUE result;
3680 VALUE hash;
3681 int eql;
3684 static int
3685 eql_i(VALUE key, VALUE val1, VALUE arg)
3687 struct equal_data *data = (struct equal_data *)arg;
3688 st_data_t val2;
3690 if (!hash_stlike_lookup(data->hash, key, &val2)) {
3691 data->result = Qfalse;
3692 return ST_STOP;
3694 else {
3695 if (!(data->eql ? rb_eql(val1, (VALUE)val2) : (int)rb_equal(val1, (VALUE)val2))) {
3696 data->result = Qfalse;
3697 return ST_STOP;
3699 return ST_CONTINUE;
3703 static VALUE
3704 recursive_eql(VALUE hash, VALUE dt, int recur)
3706 struct equal_data *data;
3708 if (recur) return Qtrue; /* Subtle! */
3709 data = (struct equal_data*)dt;
3710 data->result = Qtrue;
3711 rb_hash_foreach(hash, eql_i, dt);
3713 return data->result;
3716 static VALUE
3717 hash_equal(VALUE hash1, VALUE hash2, int eql)
3719 struct equal_data data;
3721 if (hash1 == hash2) return Qtrue;
3722 if (!RB_TYPE_P(hash2, T_HASH)) {
3723 if (!rb_respond_to(hash2, idTo_hash)) {
3724 return Qfalse;
3726 if (eql) {
3727 if (rb_eql(hash2, hash1)) {
3728 return Qtrue;
3730 else {
3731 return Qfalse;
3734 else {
3735 return rb_equal(hash2, hash1);
3738 if (RHASH_SIZE(hash1) != RHASH_SIZE(hash2))
3739 return Qfalse;
3740 if (!RHASH_TABLE_EMPTY_P(hash1) && !RHASH_TABLE_EMPTY_P(hash2)) {
3741 if (RHASH_TYPE(hash1) != RHASH_TYPE(hash2)) {
3742 return Qfalse;
3744 else {
3745 data.hash = hash2;
3746 data.eql = eql;
3747 return rb_exec_recursive_paired(recursive_eql, hash1, hash2, (VALUE)&data);
3751 #if 0
3752 if (!(rb_equal(RHASH_IFNONE(hash1), RHASH_IFNONE(hash2)) &&
3753 FL_TEST(hash1, RHASH_PROC_DEFAULT) == FL_TEST(hash2, RHASH_PROC_DEFAULT)))
3754 return Qfalse;
3755 #endif
3756 return Qtrue;
3760 * call-seq:
3761 * hash == object -> true or false
3763 * Returns +true+ if all of the following are true:
3764 * * +object+ is a \Hash object.
3765 * * +hash+ and +object+ have the same keys (regardless of order).
3766 * * For each key +key+, <tt>hash[key] == object[key]</tt>.
3768 * Otherwise, returns +false+.
3770 * Equal:
3771 * h1 = {foo: 0, bar: 1, baz: 2}
3772 * h2 = {foo: 0, bar: 1, baz: 2}
3773 * h1 == h2 # => true
3774 * h3 = {baz: 2, bar: 1, foo: 0}
3775 * h1 == h3 # => true
3778 static VALUE
3779 rb_hash_equal(VALUE hash1, VALUE hash2)
3781 return hash_equal(hash1, hash2, FALSE);
3785 * call-seq:
3786 * hash.eql? object -> true or false
3788 * Returns +true+ if all of the following are true:
3789 * * +object+ is a \Hash object.
3790 * * +hash+ and +object+ have the same keys (regardless of order).
3791 * * For each key +key+, <tt>h[key] eql? object[key]</tt>.
3793 * Otherwise, returns +false+.
3795 * Equal:
3796 * h1 = {foo: 0, bar: 1, baz: 2}
3797 * h2 = {foo: 0, bar: 1, baz: 2}
3798 * h1.eql? h2 # => true
3799 * h3 = {baz: 2, bar: 1, foo: 0}
3800 * h1.eql? h3 # => true
3803 static VALUE
3804 rb_hash_eql(VALUE hash1, VALUE hash2)
3806 return hash_equal(hash1, hash2, TRUE);
3809 static int
3810 hash_i(VALUE key, VALUE val, VALUE arg)
3812 st_index_t *hval = (st_index_t *)arg;
3813 st_index_t hdata[2];
3815 hdata[0] = rb_hash(key);
3816 hdata[1] = rb_hash(val);
3817 *hval ^= st_hash(hdata, sizeof(hdata), 0);
3818 return ST_CONTINUE;
3822 * call-seq:
3823 * hash.hash -> an_integer
3825 * Returns the \Integer hash-code for the hash.
3827 * Two \Hash objects have the same hash-code if their content is the same
3828 * (regardless or order):
3829 * h1 = {foo: 0, bar: 1, baz: 2}
3830 * h2 = {baz: 2, bar: 1, foo: 0}
3831 * h2.hash == h1.hash # => true
3832 * h2.eql? h1 # => true
3835 static VALUE
3836 rb_hash_hash(VALUE hash)
3838 st_index_t size = RHASH_SIZE(hash);
3839 st_index_t hval = rb_hash_start(size);
3840 hval = rb_hash_uint(hval, (st_index_t)rb_hash_hash);
3841 if (size) {
3842 rb_hash_foreach(hash, hash_i, (VALUE)&hval);
3844 hval = rb_hash_end(hval);
3845 return ST2FIX(hval);
3848 static int
3849 rb_hash_invert_i(VALUE key, VALUE value, VALUE hash)
3851 rb_hash_aset(hash, value, key);
3852 return ST_CONTINUE;
3856 * call-seq:
3857 * hash.invert -> new_hash
3859 * Returns a new \Hash object with the each key-value pair inverted:
3860 * h = {foo: 0, bar: 1, baz: 2}
3861 * h1 = h.invert
3862 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3864 * Overwrites any repeated new keys:
3865 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
3866 * h = {foo: 0, bar: 0, baz: 0}
3867 * h.invert # => {0=>:baz}
3870 static VALUE
3871 rb_hash_invert(VALUE hash)
3873 VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
3875 rb_hash_foreach(hash, rb_hash_invert_i, h);
3876 return h;
3879 static int
3880 rb_hash_update_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
3882 *value = arg->arg;
3883 return ST_CONTINUE;
3886 NOINSERT_UPDATE_CALLBACK(rb_hash_update_callback)
3888 static int
3889 rb_hash_update_i(VALUE key, VALUE value, VALUE hash)
3891 RHASH_UPDATE(hash, key, rb_hash_update_callback, value);
3892 return ST_CONTINUE;
3895 static int
3896 rb_hash_update_block_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
3898 st_data_t newvalue = arg->arg;
3900 if (existing) {
3901 newvalue = (st_data_t)rb_yield_values(3, (VALUE)*key, (VALUE)*value, (VALUE)newvalue);
3903 *value = newvalue;
3904 return ST_CONTINUE;
3907 NOINSERT_UPDATE_CALLBACK(rb_hash_update_block_callback)
3909 static int
3910 rb_hash_update_block_i(VALUE key, VALUE value, VALUE hash)
3912 RHASH_UPDATE(hash, key, rb_hash_update_block_callback, value);
3913 return ST_CONTINUE;
3917 * call-seq:
3918 * hash.merge! -> self
3919 * hash.merge!(*other_hashes) -> self
3920 * hash.merge!(*other_hashes) { |key, old_value, new_value| ... } -> self
3922 * Merges each of +other_hashes+ into +self+; returns +self+.
3924 * Each argument in +other_hashes+ must be a \Hash.
3926 * \Method #update is an alias for \#merge!.
3928 * With arguments and no block:
3929 * * Returns +self+, after the given hashes are merged into it.
3930 * * The given hashes are merged left to right.
3931 * * Each new entry is added at the end.
3932 * * Each duplicate-key entry's value overwrites the previous value.
3934 * Example:
3935 * h = {foo: 0, bar: 1, baz: 2}
3936 * h1 = {bat: 3, bar: 4}
3937 * h2 = {bam: 5, bat:6}
3938 * h.merge!(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
3940 * With arguments and a block:
3941 * * Returns +self+, after the given hashes are merged.
3942 * * The given hashes are merged left to right.
3943 * * Each new-key entry is added at the end.
3944 * * For each duplicate key:
3945 * * Calls the block with the key and the old and new values.
3946 * * The block's return value becomes the new value for the entry.
3948 * Example:
3949 * h = {foo: 0, bar: 1, baz: 2}
3950 * h1 = {bat: 3, bar: 4}
3951 * h2 = {bam: 5, bat:6}
3952 * h3 = h.merge!(h1, h2) { |key, old_value, new_value| old_value + new_value }
3953 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
3955 * With no arguments:
3956 * * Returns +self+, unmodified.
3957 * * The block, if given, is ignored.
3959 * Example:
3960 * h = {foo: 0, bar: 1, baz: 2}
3961 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
3962 * h1 = h.merge! { |key, old_value, new_value| raise 'Cannot happen' }
3963 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3966 static VALUE
3967 rb_hash_update(int argc, VALUE *argv, VALUE self)
3969 int i;
3970 bool block_given = rb_block_given_p();
3972 rb_hash_modify(self);
3973 for (i = 0; i < argc; i++){
3974 VALUE hash = to_hash(argv[i]);
3975 if (block_given) {
3976 rb_hash_foreach(hash, rb_hash_update_block_i, self);
3978 else {
3979 rb_hash_foreach(hash, rb_hash_update_i, self);
3982 return self;
3985 struct update_func_arg {
3986 VALUE hash;
3987 VALUE value;
3988 rb_hash_update_func *func;
3991 static int
3992 rb_hash_update_func_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
3994 struct update_func_arg *uf_arg = (struct update_func_arg *)arg->arg;
3995 VALUE newvalue = uf_arg->value;
3997 if (existing) {
3998 newvalue = (*uf_arg->func)((VALUE)*key, (VALUE)*value, newvalue);
4000 *value = newvalue;
4001 return ST_CONTINUE;
4004 NOINSERT_UPDATE_CALLBACK(rb_hash_update_func_callback)
4006 static int
4007 rb_hash_update_func_i(VALUE key, VALUE value, VALUE arg0)
4009 struct update_func_arg *arg = (struct update_func_arg *)arg0;
4010 VALUE hash = arg->hash;
4012 arg->value = value;
4013 RHASH_UPDATE(hash, key, rb_hash_update_func_callback, (VALUE)arg);
4014 return ST_CONTINUE;
4017 VALUE
4018 rb_hash_update_by(VALUE hash1, VALUE hash2, rb_hash_update_func *func)
4020 rb_hash_modify(hash1);
4021 hash2 = to_hash(hash2);
4022 if (func) {
4023 struct update_func_arg arg;
4024 arg.hash = hash1;
4025 arg.func = func;
4026 rb_hash_foreach(hash2, rb_hash_update_func_i, (VALUE)&arg);
4028 else {
4029 rb_hash_foreach(hash2, rb_hash_update_i, hash1);
4031 return hash1;
4035 * call-seq:
4036 * hash.merge -> copy_of_self
4037 * hash.merge(*other_hashes) -> new_hash
4038 * hash.merge(*other_hashes) { |key, old_value, new_value| ... } -> new_hash
4040 * Returns the new \Hash formed by merging each of +other_hashes+
4041 * into a copy of +self+.
4043 * Each argument in +other_hashes+ must be a \Hash.
4045 * ---
4047 * With arguments and no block:
4048 * * Returns the new \Hash object formed by merging each successive
4049 * \Hash in +other_hashes+ into +self+.
4050 * * Each new-key entry is added at the end.
4051 * * Each duplicate-key entry's value overwrites the previous value.
4053 * Example:
4054 * h = {foo: 0, bar: 1, baz: 2}
4055 * h1 = {bat: 3, bar: 4}
4056 * h2 = {bam: 5, bat:6}
4057 * h.merge(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
4059 * With arguments and a block:
4060 * * Returns a new \Hash object that is the merge of +self+ and each given hash.
4061 * * The given hashes are merged left to right.
4062 * * Each new-key entry is added at the end.
4063 * * For each duplicate key:
4064 * * Calls the block with the key and the old and new values.
4065 * * The block's return value becomes the new value for the entry.
4067 * Example:
4068 * h = {foo: 0, bar: 1, baz: 2}
4069 * h1 = {bat: 3, bar: 4}
4070 * h2 = {bam: 5, bat:6}
4071 * h3 = h.merge(h1, h2) { |key, old_value, new_value| old_value + new_value }
4072 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
4074 * With no arguments:
4075 * * Returns a copy of +self+.
4076 * * The block, if given, is ignored.
4078 * Example:
4079 * h = {foo: 0, bar: 1, baz: 2}
4080 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
4081 * h1 = h.merge { |key, old_value, new_value| raise 'Cannot happen' }
4082 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
4085 static VALUE
4086 rb_hash_merge(int argc, VALUE *argv, VALUE self)
4088 return rb_hash_update(argc, argv, copy_compare_by_id(rb_hash_dup(self), self));
4091 static int
4092 assoc_cmp(VALUE a, VALUE b)
4094 return !RTEST(rb_equal(a, b));
4097 static VALUE
4098 lookup2_call(VALUE arg)
4100 VALUE *args = (VALUE *)arg;
4101 return rb_hash_lookup2(args[0], args[1], Qundef);
4104 struct reset_hash_type_arg {
4105 VALUE hash;
4106 const struct st_hash_type *orighash;
4109 static VALUE
4110 reset_hash_type(VALUE arg)
4112 struct reset_hash_type_arg *p = (struct reset_hash_type_arg *)arg;
4113 HASH_ASSERT(RHASH_ST_TABLE_P(p->hash));
4114 RHASH_ST_TABLE(p->hash)->type = p->orighash;
4115 return Qundef;
4118 static int
4119 assoc_i(VALUE key, VALUE val, VALUE arg)
4121 VALUE *args = (VALUE *)arg;
4123 if (RTEST(rb_equal(args[0], key))) {
4124 args[1] = rb_assoc_new(key, val);
4125 return ST_STOP;
4127 return ST_CONTINUE;
4131 * call-seq:
4132 * hash.assoc(key) -> new_array or nil
4134 * If the given +key+ is found, returns a 2-element \Array containing that key and its value:
4135 * h = {foo: 0, bar: 1, baz: 2}
4136 * h.assoc(:bar) # => [:bar, 1]
4138 * Returns +nil+ if key +key+ is not found.
4141 static VALUE
4142 rb_hash_assoc(VALUE hash, VALUE key)
4144 st_table *table;
4145 const struct st_hash_type *orighash;
4146 VALUE args[2];
4148 if (RHASH_EMPTY_P(hash)) return Qnil;
4150 ar_force_convert_table(hash, __FILE__, __LINE__);
4151 HASH_ASSERT(RHASH_ST_TABLE_P(hash));
4152 table = RHASH_ST_TABLE(hash);
4153 orighash = table->type;
4155 if (orighash != &identhash) {
4156 VALUE value;
4157 struct reset_hash_type_arg ensure_arg;
4158 struct st_hash_type assochash;
4160 assochash.compare = assoc_cmp;
4161 assochash.hash = orighash->hash;
4162 table->type = &assochash;
4163 args[0] = hash;
4164 args[1] = key;
4165 ensure_arg.hash = hash;
4166 ensure_arg.orighash = orighash;
4167 value = rb_ensure(lookup2_call, (VALUE)&args, reset_hash_type, (VALUE)&ensure_arg);
4168 if (value != Qundef) return rb_assoc_new(key, value);
4171 args[0] = key;
4172 args[1] = Qnil;
4173 rb_hash_foreach(hash, assoc_i, (VALUE)args);
4174 return args[1];
4177 static int
4178 rassoc_i(VALUE key, VALUE val, VALUE arg)
4180 VALUE *args = (VALUE *)arg;
4182 if (RTEST(rb_equal(args[0], val))) {
4183 args[1] = rb_assoc_new(key, val);
4184 return ST_STOP;
4186 return ST_CONTINUE;
4190 * call-seq:
4191 * hash.rassoc(value) -> new_array or nil
4193 * Returns a new 2-element \Array consisting of the key and value
4194 * of the first-found entry whose value is <tt>==</tt> to value
4195 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
4196 * h = {foo: 0, bar: 1, baz: 1}
4197 * h.rassoc(1) # => [:bar, 1]
4199 * Returns +nil+ if no such value found.
4202 static VALUE
4203 rb_hash_rassoc(VALUE hash, VALUE obj)
4205 VALUE args[2];
4207 args[0] = obj;
4208 args[1] = Qnil;
4209 rb_hash_foreach(hash, rassoc_i, (VALUE)args);
4210 return args[1];
4213 static int
4214 flatten_i(VALUE key, VALUE val, VALUE ary)
4216 VALUE pair[2];
4218 pair[0] = key;
4219 pair[1] = val;
4220 rb_ary_cat(ary, pair, 2);
4222 return ST_CONTINUE;
4226 * call-seq:
4227 * hash.flatten -> new_array
4228 * hash.flatten(level) -> new_array
4230 * Returns a new \Array object that is a 1-dimensional flattening of +self+.
4232 * ---
4234 * By default, nested Arrays are not flattened:
4235 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4236 * h.flatten # => [:foo, 0, :bar, [:bat, 3], :baz, 2]
4238 * Takes the depth of recursive flattening from \Integer argument +level+:
4239 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4240 * h.flatten(1) # => [:foo, 0, :bar, [:bat, [:baz, [:bat]]]]
4241 * h.flatten(2) # => [:foo, 0, :bar, :bat, [:baz, [:bat]]]
4242 * h.flatten(3) # => [:foo, 0, :bar, :bat, :baz, [:bat]]
4243 * h.flatten(4) # => [:foo, 0, :bar, :bat, :baz, :bat]
4245 * When +level+ is negative, flattens all nested Arrays:
4246 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4247 * h.flatten(-1) # => [:foo, 0, :bar, :bat, :baz, :bat]
4248 * h.flatten(-2) # => [:foo, 0, :bar, :bat, :baz, :bat]
4250 * When +level+ is zero, returns the equivalent of #to_a :
4251 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4252 * h.flatten(0) # => [[:foo, 0], [:bar, [:bat, 3]], [:baz, 2]]
4253 * h.flatten(0) == h.to_a # => true
4256 static VALUE
4257 rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
4259 VALUE ary;
4261 rb_check_arity(argc, 0, 1);
4263 if (argc) {
4264 int level = NUM2INT(argv[0]);
4266 if (level == 0) return rb_hash_to_a(hash);
4268 ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4269 rb_hash_foreach(hash, flatten_i, ary);
4270 level--;
4272 if (level > 0) {
4273 VALUE ary_flatten_level = INT2FIX(level);
4274 rb_funcallv(ary, id_flatten_bang, 1, &ary_flatten_level);
4276 else if (level < 0) {
4277 /* flatten recursively */
4278 rb_funcallv(ary, id_flatten_bang, 0, 0);
4281 else {
4282 ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4283 rb_hash_foreach(hash, flatten_i, ary);
4286 return ary;
4289 static int
4290 delete_if_nil(VALUE key, VALUE value, VALUE hash)
4292 if (NIL_P(value)) {
4293 return ST_DELETE;
4295 return ST_CONTINUE;
4298 static int
4299 set_if_not_nil(VALUE key, VALUE value, VALUE hash)
4301 if (!NIL_P(value)) {
4302 rb_hash_aset(hash, key, value);
4304 return ST_CONTINUE;
4308 * call-seq:
4309 * hash.compact -> new_hash
4311 * Returns a copy of +self+ with all +nil+-valued entries removed:
4312 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4313 * h1 = h.compact
4314 * h1 # => {:foo=>0, :baz=>2}
4317 static VALUE
4318 rb_hash_compact(VALUE hash)
4320 VALUE result = rb_hash_new();
4321 if (!RHASH_EMPTY_P(hash)) {
4322 rb_hash_foreach(hash, set_if_not_nil, result);
4324 return result;
4328 * call-seq:
4329 * hash.compact! -> self or nil
4331 * Returns +self+ with all its +nil+-valued entries removed (in place):
4332 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4333 * h.compact! # => {:foo=>0, :baz=>2}
4335 * Returns +nil+ if no entries were removed.
4338 static VALUE
4339 rb_hash_compact_bang(VALUE hash)
4341 st_index_t n;
4342 rb_hash_modify_check(hash);
4343 n = RHASH_SIZE(hash);
4344 if (n) {
4345 rb_hash_foreach(hash, delete_if_nil, hash);
4346 if (n != RHASH_SIZE(hash))
4347 return hash;
4349 return Qnil;
4352 static st_table *rb_init_identtable_with_size(st_index_t size);
4355 * call-seq:
4356 * hash.compare_by_identity -> self
4358 * Sets +self+ to consider only identity in comparing keys;
4359 * two keys are considered the same only if they are the same object;
4360 * returns +self+.
4362 * By default, these two object are considered to be the same key,
4363 * so +s1+ will overwrite +s0+:
4364 * s0 = 'x'
4365 * s1 = 'x'
4366 * h = {}
4367 * h.compare_by_identity? # => false
4368 * h[s0] = 0
4369 * h[s1] = 1
4370 * h # => {"x"=>1}
4372 * After calling \#compare_by_identity, the keys are considered to be different,
4373 * and therefore do not overwrite each other:
4374 * h = {}
4375 * h.compare_by_identity # => {}
4376 * h.compare_by_identity? # => true
4377 * h[s0] = 0
4378 * h[s1] = 1
4379 * h # => {"x"=>0, "x"=>1}
4382 VALUE
4383 rb_hash_compare_by_id(VALUE hash)
4385 VALUE tmp;
4386 st_table *identtable;
4388 if (rb_hash_compare_by_id_p(hash)) return hash;
4390 rb_hash_modify_check(hash);
4391 ar_force_convert_table(hash, __FILE__, __LINE__);
4392 HASH_ASSERT(RHASH_ST_TABLE_P(hash));
4394 tmp = hash_alloc(0);
4395 identtable = rb_init_identtable_with_size(RHASH_SIZE(hash));
4396 RHASH_ST_TABLE_SET(tmp, identtable);
4397 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
4398 st_free_table(RHASH_ST_TABLE(hash));
4399 RHASH_ST_TABLE_SET(hash, identtable);
4400 RHASH_ST_CLEAR(tmp);
4402 return hash;
4406 * call-seq:
4407 * hash.compare_by_identity? -> true or false
4409 * Returns +true+ if #compare_by_identity has been called, +false+ otherwise.
4412 MJIT_FUNC_EXPORTED VALUE
4413 rb_hash_compare_by_id_p(VALUE hash)
4415 return RBOOL(RHASH_ST_TABLE_P(hash) && RHASH_ST_TABLE(hash)->type == &identhash);
4418 VALUE
4419 rb_ident_hash_new(void)
4421 VALUE hash = rb_hash_new();
4422 RHASH_ST_TABLE_SET(hash, st_init_table(&identhash));
4423 return hash;
4426 VALUE
4427 rb_ident_hash_new_with_size(st_index_t size)
4429 VALUE hash = rb_hash_new();
4430 RHASH_ST_TABLE_SET(hash, st_init_table_with_size(&identhash, size));
4431 return hash;
4434 st_table *
4435 rb_init_identtable(void)
4437 return st_init_table(&identhash);
4440 static st_table *
4441 rb_init_identtable_with_size(st_index_t size)
4443 return st_init_table_with_size(&identhash, size);
4446 static int
4447 any_p_i(VALUE key, VALUE value, VALUE arg)
4449 VALUE ret = rb_yield(rb_assoc_new(key, value));
4450 if (RTEST(ret)) {
4451 *(VALUE *)arg = Qtrue;
4452 return ST_STOP;
4454 return ST_CONTINUE;
4457 static int
4458 any_p_i_fast(VALUE key, VALUE value, VALUE arg)
4460 VALUE ret = rb_yield_values(2, key, value);
4461 if (RTEST(ret)) {
4462 *(VALUE *)arg = Qtrue;
4463 return ST_STOP;
4465 return ST_CONTINUE;
4468 static int
4469 any_p_i_pattern(VALUE key, VALUE value, VALUE arg)
4471 VALUE ret = rb_funcall(((VALUE *)arg)[1], idEqq, 1, rb_assoc_new(key, value));
4472 if (RTEST(ret)) {
4473 *(VALUE *)arg = Qtrue;
4474 return ST_STOP;
4476 return ST_CONTINUE;
4480 * call-seq:
4481 * hash.any? -> true or false
4482 * hash.any?(object) -> true or false
4483 * hash.any? {|key, value| ... } -> true or false
4485 * Returns +true+ if any element satisfies a given criterion;
4486 * +false+ otherwise.
4488 * With no argument and no block,
4489 * returns +true+ if +self+ is non-empty; +false+ if empty.
4491 * With argument +object+ and no block,
4492 * returns +true+ if for any key +key+
4493 * <tt>h.assoc(key) == object</tt>:
4494 * h = {foo: 0, bar: 1, baz: 2}
4495 * h.any?([:bar, 1]) # => true
4496 * h.any?([:bar, 0]) # => false
4497 * h.any?([:baz, 1]) # => false
4499 * With no argument and a block,
4500 * calls the block with each key-value pair;
4501 * returns +true+ if the block returns any truthy value,
4502 * +false+ otherwise:
4503 * h = {foo: 0, bar: 1, baz: 2}
4504 * h.any? {|key, value| value < 3 } # => true
4505 * h.any? {|key, value| value > 3 } # => false
4508 static VALUE
4509 rb_hash_any_p(int argc, VALUE *argv, VALUE hash)
4511 VALUE args[2];
4512 args[0] = Qfalse;
4514 rb_check_arity(argc, 0, 1);
4515 if (RHASH_EMPTY_P(hash)) return Qfalse;
4516 if (argc) {
4517 if (rb_block_given_p()) {
4518 rb_warn("given block not used");
4520 args[1] = argv[0];
4522 rb_hash_foreach(hash, any_p_i_pattern, (VALUE)args);
4524 else {
4525 if (!rb_block_given_p()) {
4526 /* yields pairs, never false */
4527 return Qtrue;
4529 if (rb_block_pair_yield_optimizable())
4530 rb_hash_foreach(hash, any_p_i_fast, (VALUE)args);
4531 else
4532 rb_hash_foreach(hash, any_p_i, (VALUE)args);
4534 return args[0];
4538 * call-seq:
4539 * hash.dig(key, *identifiers) -> object
4541 * Finds and returns the object in nested objects
4542 * that is specified by +key+ and +identifiers+.
4543 * The nested objects may be instances of various classes.
4544 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
4546 * Nested Hashes:
4547 * h = {foo: {bar: {baz: 2}}}
4548 * h.dig(:foo) # => {:bar=>{:baz=>2}}
4549 * h.dig(:foo, :bar) # => {:baz=>2}
4550 * h.dig(:foo, :bar, :baz) # => 2
4551 * h.dig(:foo, :bar, :BAZ) # => nil
4553 * Nested Hashes and Arrays:
4554 * h = {foo: {bar: [:a, :b, :c]}}
4555 * h.dig(:foo, :bar, 2) # => :c
4557 * This method will use the {default values}[#class-Hash-label-Default+Values]
4558 * for keys that are not present:
4559 * h = {foo: {bar: [:a, :b, :c]}}
4560 * h.dig(:hello) # => nil
4561 * h.default_proc = -> (hash, _key) { hash }
4562 * h.dig(:hello, :world) # => h
4563 * h.dig(:hello, :world, :foo, :bar, 2) # => :c
4566 static VALUE
4567 rb_hash_dig(int argc, VALUE *argv, VALUE self)
4569 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
4570 self = rb_hash_aref(self, *argv);
4571 if (!--argc) return self;
4572 ++argv;
4573 return rb_obj_dig(argc, argv, self, Qnil);
4576 static int
4577 hash_le_i(VALUE key, VALUE value, VALUE arg)
4579 VALUE *args = (VALUE *)arg;
4580 VALUE v = rb_hash_lookup2(args[0], key, Qundef);
4581 if (v != Qundef && rb_equal(value, v)) return ST_CONTINUE;
4582 args[1] = Qfalse;
4583 return ST_STOP;
4586 static VALUE
4587 hash_le(VALUE hash1, VALUE hash2)
4589 VALUE args[2];
4590 args[0] = hash2;
4591 args[1] = Qtrue;
4592 rb_hash_foreach(hash1, hash_le_i, (VALUE)args);
4593 return args[1];
4597 * call-seq:
4598 * hash <= other_hash -> true or false
4600 * Returns +true+ if +hash+ is a subset of +other_hash+, +false+ otherwise:
4601 * h1 = {foo: 0, bar: 1}
4602 * h2 = {foo: 0, bar: 1, baz: 2}
4603 * h1 <= h2 # => true
4604 * h2 <= h1 # => false
4605 * h1 <= h1 # => true
4607 static VALUE
4608 rb_hash_le(VALUE hash, VALUE other)
4610 other = to_hash(other);
4611 if (RHASH_SIZE(hash) > RHASH_SIZE(other)) return Qfalse;
4612 return hash_le(hash, other);
4616 * call-seq:
4617 * hash < other_hash -> true or false
4619 * Returns +true+ if +hash+ is a proper subset of +other_hash+, +false+ otherwise:
4620 * h1 = {foo: 0, bar: 1}
4621 * h2 = {foo: 0, bar: 1, baz: 2}
4622 * h1 < h2 # => true
4623 * h2 < h1 # => false
4624 * h1 < h1 # => false
4626 static VALUE
4627 rb_hash_lt(VALUE hash, VALUE other)
4629 other = to_hash(other);
4630 if (RHASH_SIZE(hash) >= RHASH_SIZE(other)) return Qfalse;
4631 return hash_le(hash, other);
4635 * call-seq:
4636 * hash >= other_hash -> true or false
4638 * Returns +true+ if +hash+ is a superset of +other_hash+, +false+ otherwise:
4639 * h1 = {foo: 0, bar: 1, baz: 2}
4640 * h2 = {foo: 0, bar: 1}
4641 * h1 >= h2 # => true
4642 * h2 >= h1 # => false
4643 * h1 >= h1 # => true
4645 static VALUE
4646 rb_hash_ge(VALUE hash, VALUE other)
4648 other = to_hash(other);
4649 if (RHASH_SIZE(hash) < RHASH_SIZE(other)) return Qfalse;
4650 return hash_le(other, hash);
4654 * call-seq:
4655 * hash > other_hash -> true or false
4657 * Returns +true+ if +hash+ is a proper superset of +other_hash+, +false+ otherwise:
4658 * h1 = {foo: 0, bar: 1, baz: 2}
4659 * h2 = {foo: 0, bar: 1}
4660 * h1 > h2 # => true
4661 * h2 > h1 # => false
4662 * h1 > h1 # => false
4664 static VALUE
4665 rb_hash_gt(VALUE hash, VALUE other)
4667 other = to_hash(other);
4668 if (RHASH_SIZE(hash) <= RHASH_SIZE(other)) return Qfalse;
4669 return hash_le(other, hash);
4672 static VALUE
4673 hash_proc_call(RB_BLOCK_CALL_FUNC_ARGLIST(key, hash))
4675 rb_check_arity(argc, 1, 1);
4676 return rb_hash_aref(hash, *argv);
4680 * call-seq:
4681 * hash.to_proc -> proc
4683 * Returns a \Proc object that maps a key to its value:
4684 * h = {foo: 0, bar: 1, baz: 2}
4685 * proc = h.to_proc
4686 * proc.class # => Proc
4687 * proc.call(:foo) # => 0
4688 * proc.call(:bar) # => 1
4689 * proc.call(:nosuch) # => nil
4691 static VALUE
4692 rb_hash_to_proc(VALUE hash)
4694 return rb_func_lambda_new(hash_proc_call, hash, 1, 1);
4697 static VALUE
4698 rb_hash_deconstruct_keys(VALUE hash, VALUE keys)
4700 return hash;
4703 static int
4704 add_new_i(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
4706 VALUE *args = (VALUE *)arg;
4707 if (existing) return ST_STOP;
4708 RB_OBJ_WRITTEN(args[0], Qundef, (VALUE)*key);
4709 RB_OBJ_WRITE(args[0], (VALUE *)val, args[1]);
4710 return ST_CONTINUE;
4714 * add +key+ to +val+ pair if +hash+ does not contain +key+.
4715 * returns non-zero if +key+ was contained.
4718 rb_hash_add_new_element(VALUE hash, VALUE key, VALUE val)
4720 st_table *tbl;
4721 int ret = 0;
4722 VALUE args[2];
4723 args[0] = hash;
4724 args[1] = val;
4726 if (RHASH_AR_TABLE_P(hash)) {
4727 hash_ar_table(hash);
4729 ret = ar_update(hash, (st_data_t)key, add_new_i, (st_data_t)args);
4730 if (ret != -1) {
4731 return ret;
4733 ar_try_convert_table(hash);
4735 tbl = RHASH_TBL_RAW(hash);
4736 return st_update(tbl, (st_data_t)key, add_new_i, (st_data_t)args);
4740 static st_data_t
4741 key_stringify(VALUE key)
4743 return (rb_obj_class(key) == rb_cString && !RB_OBJ_FROZEN(key)) ?
4744 rb_hash_key_str(key) : key;
4747 static void
4748 ar_bulk_insert(VALUE hash, long argc, const VALUE *argv)
4750 long i;
4751 for (i = 0; i < argc; ) {
4752 st_data_t k = key_stringify(argv[i++]);
4753 st_data_t v = argv[i++];
4754 ar_insert(hash, k, v);
4755 RB_OBJ_WRITTEN(hash, Qundef, k);
4756 RB_OBJ_WRITTEN(hash, Qundef, v);
4760 void
4761 rb_hash_bulk_insert(long argc, const VALUE *argv, VALUE hash)
4763 HASH_ASSERT(argc % 2 == 0);
4764 if (argc > 0) {
4765 st_index_t size = argc / 2;
4767 if (RHASH_TABLE_NULL_P(hash)) {
4768 if (size <= RHASH_AR_TABLE_MAX_SIZE) {
4769 hash_ar_table(hash);
4771 else {
4772 RHASH_TBL_RAW(hash);
4776 if (RHASH_AR_TABLE_P(hash) &&
4777 (RHASH_AR_TABLE_SIZE(hash) + size <= RHASH_AR_TABLE_MAX_SIZE)) {
4778 ar_bulk_insert(hash, argc, argv);
4780 else {
4781 rb_hash_bulk_insert_into_st_table(argc, argv, hash);
4786 static char **origenviron;
4787 #ifdef _WIN32
4788 #define GET_ENVIRON(e) ((e) = rb_w32_get_environ())
4789 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
4790 static char **my_environ;
4791 #undef environ
4792 #define environ my_environ
4793 #undef getenv
4794 #define getenv(n) rb_w32_ugetenv(n)
4795 #elif defined(__APPLE__)
4796 #undef environ
4797 #define environ (*_NSGetEnviron())
4798 #define GET_ENVIRON(e) (e)
4799 #define FREE_ENVIRON(e)
4800 #else
4801 extern char **environ;
4802 #define GET_ENVIRON(e) (e)
4803 #define FREE_ENVIRON(e)
4804 #endif
4805 #ifdef ENV_IGNORECASE
4806 #define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
4807 #define ENVNMATCH(s1, s2, n) (STRNCASECMP((s1), (s2), (n)) == 0)
4808 #else
4809 #define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
4810 #define ENVNMATCH(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
4811 #endif
4813 #define ENV_LOCK() RB_VM_LOCK_ENTER()
4814 #define ENV_UNLOCK() RB_VM_LOCK_LEAVE()
4816 static inline rb_encoding *
4817 env_encoding(void)
4819 #ifdef _WIN32
4820 return rb_utf8_encoding();
4821 #else
4822 return rb_locale_encoding();
4823 #endif
4826 static VALUE
4827 env_enc_str_new(const char *ptr, long len, rb_encoding *enc)
4829 VALUE str = rb_external_str_new_with_enc(ptr, len, enc);
4831 rb_obj_freeze(str);
4832 return str;
4835 static VALUE
4836 env_str_new(const char *ptr, long len)
4838 return env_enc_str_new(ptr, len, env_encoding());
4841 static VALUE
4842 env_str_new2(const char *ptr)
4844 if (!ptr) return Qnil;
4845 return env_str_new(ptr, strlen(ptr));
4848 static VALUE
4849 getenv_with_lock(const char *name)
4851 VALUE ret;
4852 ENV_LOCK();
4854 const char *val = getenv(name);
4855 ret = env_str_new2(val);
4857 ENV_UNLOCK();
4858 return ret;
4861 static bool
4862 has_env_with_lock(const char *name)
4864 const char *val;
4866 ENV_LOCK();
4868 val = getenv(name);
4870 ENV_UNLOCK();
4872 return val ? true : false;
4875 static const char TZ_ENV[] = "TZ";
4877 static void *
4878 get_env_cstr(
4879 VALUE str,
4880 const char *name)
4882 char *var;
4883 rb_encoding *enc = rb_enc_get(str);
4884 if (!rb_enc_asciicompat(enc)) {
4885 rb_raise(rb_eArgError, "bad environment variable %s: ASCII incompatible encoding: %s",
4886 name, rb_enc_name(enc));
4888 var = RSTRING_PTR(str);
4889 if (memchr(var, '\0', RSTRING_LEN(str))) {
4890 rb_raise(rb_eArgError, "bad environment variable %s: contains null byte", name);
4892 return rb_str_fill_terminator(str, 1); /* ASCII compatible */
4895 #define get_env_ptr(var, val) \
4896 (var = get_env_cstr(val, #var))
4898 static inline const char *
4899 env_name(volatile VALUE *s)
4901 const char *name;
4902 SafeStringValue(*s);
4903 get_env_ptr(name, *s);
4904 return name;
4907 #define env_name(s) env_name(&(s))
4909 static VALUE env_aset(VALUE nm, VALUE val);
4911 static void
4912 reset_by_modified_env(const char *nam)
4915 * ENV['TZ'] = nil has a special meaning.
4916 * TZ is no longer considered up-to-date and ruby call tzset() as needed.
4917 * It could be useful if sysadmin change /etc/localtime.
4918 * This hack might works only on Linux glibc.
4920 if (ENVMATCH(nam, TZ_ENV)) {
4921 ruby_reset_timezone();
4925 static VALUE
4926 env_delete(VALUE name)
4928 const char *nam = env_name(name);
4929 reset_by_modified_env(nam);
4930 VALUE val = getenv_with_lock(nam);
4932 if (!NIL_P(val)) {
4933 ruby_setenv(nam, 0);
4935 return val;
4939 * call-seq:
4940 * ENV.delete(name) -> value
4941 * ENV.delete(name) { |name| block } -> value
4942 * ENV.delete(missing_name) -> nil
4943 * ENV.delete(missing_name) { |name| block } -> block_value
4945 * Deletes the environment variable with +name+ if it exists and returns its value:
4946 * ENV['foo'] = '0'
4947 * ENV.delete('foo') # => '0'
4949 * If a block is not given and the named environment variable does not exist, returns +nil+.
4951 * If a block given and the environment variable does not exist,
4952 * yields +name+ to the block and returns the value of the block:
4953 * ENV.delete('foo') { |name| name * 2 } # => "foofoo"
4955 * If a block given and the environment variable exists,
4956 * deletes the environment variable and returns its value (ignoring the block):
4957 * ENV['foo'] = '0'
4958 * ENV.delete('foo') { |name| raise 'ignored' } # => "0"
4960 * Raises an exception if +name+ is invalid.
4961 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
4963 static VALUE
4964 env_delete_m(VALUE obj, VALUE name)
4966 VALUE val;
4968 val = env_delete(name);
4969 if (NIL_P(val) && rb_block_given_p()) val = rb_yield(name);
4970 return val;
4974 * call-seq:
4975 * ENV[name] -> value
4977 * Returns the value for the environment variable +name+ if it exists:
4978 * ENV['foo'] = '0'
4979 * ENV['foo'] # => "0"
4980 * Returns +nil+ if the named variable does not exist.
4982 * Raises an exception if +name+ is invalid.
4983 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
4985 static VALUE
4986 rb_f_getenv(VALUE obj, VALUE name)
4988 const char *nam = env_name(name);
4989 VALUE env = getenv_with_lock(nam);
4990 return env;
4994 * call-seq:
4995 * ENV.fetch(name) -> value
4996 * ENV.fetch(name, default) -> value
4997 * ENV.fetch(name) { |name| block } -> value
4999 * If +name+ is the name of an environment variable, returns its value:
5000 * ENV['foo'] = '0'
5001 * ENV.fetch('foo') # => '0'
5002 * Otherwise if a block is given (but not a default value),
5003 * yields +name+ to the block and returns the block's return value:
5004 * ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string
5005 * Otherwise if a default value is given (but not a block), returns the default value:
5006 * ENV.delete('foo')
5007 * ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string
5008 * If the environment variable does not exist and both default and block are given,
5009 * issues a warning ("warning: block supersedes default value argument"),
5010 * yields +name+ to the block, and returns the block's return value:
5011 * ENV.fetch('foo', :default) { |name| :block_return } # => :block_return
5012 * Raises KeyError if +name+ is valid, but not found,
5013 * and neither default value nor block is given:
5014 * ENV.fetch('foo') # Raises KeyError (key not found: "foo")
5015 * Raises an exception if +name+ is invalid.
5016 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
5018 static VALUE
5019 env_fetch(int argc, VALUE *argv, VALUE _)
5021 VALUE key;
5022 long block_given;
5023 const char *nam;
5024 VALUE env;
5026 rb_check_arity(argc, 1, 2);
5027 key = argv[0];
5028 block_given = rb_block_given_p();
5029 if (block_given && argc == 2) {
5030 rb_warn("block supersedes default value argument");
5032 nam = env_name(key);
5033 env = getenv_with_lock(nam);
5035 if (NIL_P(env)) {
5036 if (block_given) return rb_yield(key);
5037 if (argc == 1) {
5038 rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE"\"", key), envtbl, key);
5040 return argv[1];
5042 return env;
5045 #if defined(_WIN32) || (defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
5046 #elif defined __sun
5047 static int
5048 in_origenv(const char *str)
5050 char **env;
5051 for (env = origenviron; *env; ++env) {
5052 if (*env == str) return 1;
5054 return 0;
5056 #else
5057 static int
5058 envix(const char *nam)
5060 // should be locked
5062 register int i, len = strlen(nam);
5063 char **env;
5065 env = GET_ENVIRON(environ);
5066 for (i = 0; env[i]; i++) {
5067 if (ENVNMATCH(env[i],nam,len) && env[i][len] == '=')
5068 break; /* memcmp must come first to avoid */
5069 } /* potential SEGV's */
5070 FREE_ENVIRON(environ);
5071 return i;
5073 #endif
5075 #if defined(_WIN32)
5076 static size_t
5077 getenvsize(const WCHAR* p)
5079 const WCHAR* porg = p;
5080 while (*p++) p += lstrlenW(p) + 1;
5081 return p - porg + 1;
5084 static size_t
5085 getenvblocksize(void)
5087 #ifdef _MAX_ENV
5088 return _MAX_ENV;
5089 #else
5090 return 32767;
5091 #endif
5094 static int
5095 check_envsize(size_t n)
5097 if (_WIN32_WINNT < 0x0600 && rb_w32_osver() < 6) {
5098 /* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653(v=vs.85).aspx */
5099 /* Windows Server 2003 and Windows XP: The maximum size of the
5100 * environment block for the process is 32,767 characters. */
5101 WCHAR* p = GetEnvironmentStringsW();
5102 if (!p) return -1; /* never happen */
5103 n += getenvsize(p);
5104 FreeEnvironmentStringsW(p);
5105 if (n >= getenvblocksize()) {
5106 return -1;
5109 return 0;
5111 #endif
5113 #if defined(_WIN32) || \
5114 (defined(__sun) && !(defined(HAVE_SETENV) && defined(HAVE_UNSETENV)))
5116 NORETURN(static void invalid_envname(const char *name));
5118 static void
5119 invalid_envname(const char *name)
5121 rb_syserr_fail_str(EINVAL, rb_sprintf("ruby_setenv(%s)", name));
5124 static const char *
5125 check_envname(const char *name)
5127 if (strchr(name, '=')) {
5128 invalid_envname(name);
5130 return name;
5132 #endif
5134 void
5135 ruby_setenv(const char *name, const char *value)
5137 #if defined(_WIN32)
5138 # if defined(MINGW_HAS_SECURE_API) || RUBY_MSVCRT_VERSION >= 80
5139 # define HAVE__WPUTENV_S 1
5140 # endif
5141 VALUE buf;
5142 WCHAR *wname;
5143 WCHAR *wvalue = 0;
5144 int failed = 0;
5145 int len;
5146 check_envname(name);
5147 len = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0);
5148 if (value) {
5149 int len2;
5150 len2 = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0);
5151 if (check_envsize((size_t)len + len2)) { /* len and len2 include '\0' */
5152 goto fail; /* 2 for '=' & '\0' */
5154 wname = ALLOCV_N(WCHAR, buf, len + len2);
5155 wvalue = wname + len;
5156 MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len);
5157 MultiByteToWideChar(CP_UTF8, 0, value, -1, wvalue, len2);
5158 #ifndef HAVE__WPUTENV_S
5159 wname[len-1] = L'=';
5160 #endif
5162 else {
5163 wname = ALLOCV_N(WCHAR, buf, len + 1);
5164 MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len);
5165 wvalue = wname + len;
5166 *wvalue = L'\0';
5167 #ifndef HAVE__WPUTENV_S
5168 wname[len-1] = L'=';
5169 #endif
5172 ENV_LOCK();
5174 #ifndef HAVE__WPUTENV_S
5175 failed = _wputenv(wname);
5176 #else
5177 failed = _wputenv_s(wname, wvalue);
5178 #endif
5180 ENV_UNLOCK();
5182 ALLOCV_END(buf);
5183 /* even if putenv() failed, clean up and try to delete the
5184 * variable from the system area. */
5185 if (!value || !*value) {
5186 /* putenv() doesn't handle empty value */
5187 if (!SetEnvironmentVariable(name, value) &&
5188 GetLastError() != ERROR_ENVVAR_NOT_FOUND) goto fail;
5190 if (failed) {
5191 fail:
5192 invalid_envname(name);
5194 #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
5195 if (value) {
5196 int ret;
5197 ENV_LOCK();
5199 ret = setenv(name, value, 1);
5201 ENV_UNLOCK();
5203 if (ret) rb_sys_fail_str(rb_sprintf("setenv(%s)", name));
5205 else {
5206 #ifdef VOID_UNSETENV
5207 ENV_LOCK();
5209 unsetenv(name);
5211 ENV_UNLOCK();
5212 #else
5213 int ret;
5214 ENV_LOCK();
5216 ret = unsetenv(name);
5218 ENV_UNLOCK();
5220 if (ret) rb_sys_fail_str(rb_sprintf("unsetenv(%s)", name));
5221 #endif
5223 #elif defined __sun
5224 /* Solaris 9 (or earlier) does not have setenv(3C) and unsetenv(3C). */
5225 /* The below code was tested on Solaris 10 by:
5226 % ./configure ac_cv_func_setenv=no ac_cv_func_unsetenv=no
5228 size_t len, mem_size;
5229 char **env_ptr, *str, *mem_ptr;
5231 check_envname(name);
5232 len = strlen(name);
5233 if (value) {
5234 mem_size = len + strlen(value) + 2;
5235 mem_ptr = malloc(mem_size);
5236 if (mem_ptr == NULL)
5237 rb_sys_fail_str(rb_sprintf("malloc(%"PRIuSIZE")", mem_size));
5238 snprintf(mem_ptr, mem_size, "%s=%s", name, value);
5241 ENV_LOCK();
5243 for (env_ptr = GET_ENVIRON(environ); (str = *env_ptr) != 0; ++env_ptr) {
5244 if (!strncmp(str, name, len) && str[len] == '=') {
5245 if (!in_origenv(str)) free(str);
5246 while ((env_ptr[0] = env_ptr[1]) != 0) env_ptr++;
5247 break;
5251 ENV_UNLOCK();
5253 if (value) {
5254 int ret;
5255 ENV_LOCK();
5257 ret = putenv(mem_ptr);
5259 ENV_UNLOCK();
5261 if (ret) {
5262 free(mem_ptr);
5263 rb_sys_fail_str(rb_sprintf("putenv(%s)", name));
5266 #else /* WIN32 */
5267 size_t len;
5268 int i;
5270 ENV_LOCK();
5272 i = envix(name); /* where does it go? */
5274 if (environ == origenviron) { /* need we copy environment? */
5275 int j;
5276 int max;
5277 char **tmpenv;
5279 for (max = i; environ[max]; max++) ;
5280 tmpenv = ALLOC_N(char*, max+2);
5281 for (j=0; j<max; j++) /* copy environment */
5282 tmpenv[j] = ruby_strdup(environ[j]);
5283 tmpenv[max] = 0;
5284 environ = tmpenv; /* tell exec where it is now */
5287 if (environ[i]) {
5288 char **envp = origenviron;
5289 while (*envp && *envp != environ[i]) envp++;
5290 if (!*envp)
5291 xfree(environ[i]);
5292 if (!value) {
5293 while (environ[i]) {
5294 environ[i] = environ[i+1];
5295 i++;
5297 goto finish;
5300 else { /* does not exist yet */
5301 if (!value) goto finish;
5302 REALLOC_N(environ, char*, i+2); /* just expand it a bit */
5303 environ[i+1] = 0; /* make sure it's null terminated */
5306 len = strlen(name) + strlen(value) + 2;
5307 environ[i] = ALLOC_N(char, len);
5308 snprintf(environ[i],len,"%s=%s",name,value); /* all that work just for this */
5310 finish:;
5312 ENV_UNLOCK();
5313 #endif /* WIN32 */
5316 void
5317 ruby_unsetenv(const char *name)
5319 ruby_setenv(name, 0);
5323 * call-seq:
5324 * ENV[name] = value -> value
5325 * ENV.store(name, value) -> value
5327 * ENV.store is an alias for ENV.[]=.
5329 * Creates, updates, or deletes the named environment variable, returning the value.
5330 * Both +name+ and +value+ may be instances of String.
5331 * See {Valid Names and Values}[#class-ENV-label-Valid+Names+and+Values].
5333 * - If the named environment variable does not exist:
5334 * - If +value+ is +nil+, does nothing.
5335 * ENV.clear
5336 * ENV['foo'] = nil # => nil
5337 * ENV.include?('foo') # => false
5338 * ENV.store('bar', nil) # => nil
5339 * ENV.include?('bar') # => false
5340 * - If +value+ is not +nil+, creates the environment variable with +name+ and +value+:
5341 * # Create 'foo' using ENV.[]=.
5342 * ENV['foo'] = '0' # => '0'
5343 * ENV['foo'] # => '0'
5344 * # Create 'bar' using ENV.store.
5345 * ENV.store('bar', '1') # => '1'
5346 * ENV['bar'] # => '1'
5347 * - If the named environment variable exists:
5348 * - If +value+ is not +nil+, updates the environment variable with value +value+:
5349 * # Update 'foo' using ENV.[]=.
5350 * ENV['foo'] = '2' # => '2'
5351 * ENV['foo'] # => '2'
5352 * # Update 'bar' using ENV.store.
5353 * ENV.store('bar', '3') # => '3'
5354 * ENV['bar'] # => '3'
5355 * - If +value+ is +nil+, deletes the environment variable:
5356 * # Delete 'foo' using ENV.[]=.
5357 * ENV['foo'] = nil # => nil
5358 * ENV.include?('foo') # => false
5359 * # Delete 'bar' using ENV.store.
5360 * ENV.store('bar', nil) # => nil
5361 * ENV.include?('bar') # => false
5363 * Raises an exception if +name+ or +value+ is invalid.
5364 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
5366 static VALUE
5367 env_aset_m(VALUE obj, VALUE nm, VALUE val)
5369 return env_aset(nm, val);
5372 static VALUE
5373 env_aset(VALUE nm, VALUE val)
5375 char *name, *value;
5377 if (NIL_P(val)) {
5378 env_delete(nm);
5379 return Qnil;
5381 SafeStringValue(nm);
5382 SafeStringValue(val);
5383 /* nm can be modified in `val.to_str`, don't get `name` before
5384 * check for `val` */
5385 get_env_ptr(name, nm);
5386 get_env_ptr(value, val);
5388 ruby_setenv(name, value);
5389 reset_by_modified_env(name);
5390 return val;
5393 static VALUE
5394 env_keys(int raw)
5396 rb_encoding *enc = raw ? 0 : rb_locale_encoding();
5397 VALUE ary = rb_ary_new();
5399 ENV_LOCK();
5401 char **env = GET_ENVIRON(environ);
5402 while (*env) {
5403 char *s = strchr(*env, '=');
5404 if (s) {
5405 const char *p = *env;
5406 size_t l = s - p;
5407 VALUE e = raw ? rb_utf8_str_new(p, l) : env_enc_str_new(p, l, enc);
5408 rb_ary_push(ary, e);
5410 env++;
5412 FREE_ENVIRON(environ);
5414 ENV_UNLOCK();
5416 return ary;
5420 * call-seq:
5421 * ENV.keys -> array of names
5423 * Returns all variable names in an Array:
5424 * ENV.replace('foo' => '0', 'bar' => '1')
5425 * ENV.keys # => ['bar', 'foo']
5426 * The order of the names is OS-dependent.
5427 * See {About Ordering}[#class-ENV-label-About+Ordering].
5429 * Returns the empty Array if ENV is empty.
5432 static VALUE
5433 env_f_keys(VALUE _)
5435 return env_keys(FALSE);
5438 static VALUE
5439 rb_env_size(VALUE ehash, VALUE args, VALUE eobj)
5441 char **env;
5442 long cnt = 0;
5444 ENV_LOCK();
5446 env = GET_ENVIRON(environ);
5447 for (; *env ; ++env) {
5448 if (strchr(*env, '=')) {
5449 cnt++;
5452 FREE_ENVIRON(environ);
5454 ENV_UNLOCK();
5456 return LONG2FIX(cnt);
5460 * call-seq:
5461 * ENV.each_key { |name| block } -> ENV
5462 * ENV.each_key -> an_enumerator
5464 * Yields each environment variable name:
5465 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5466 * names = []
5467 * ENV.each_key { |name| names.push(name) } # => ENV
5468 * names # => ["bar", "foo"]
5470 * Returns an Enumerator if no block given:
5471 * e = ENV.each_key # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_key>
5472 * names = []
5473 * e.each { |name| names.push(name) } # => ENV
5474 * names # => ["bar", "foo"]
5476 static VALUE
5477 env_each_key(VALUE ehash)
5479 VALUE keys;
5480 long i;
5482 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5483 keys = env_keys(FALSE);
5484 for (i=0; i<RARRAY_LEN(keys); i++) {
5485 rb_yield(RARRAY_AREF(keys, i));
5487 return ehash;
5490 static VALUE
5491 env_values(void)
5493 VALUE ary = rb_ary_new();
5495 ENV_LOCK();
5497 char **env = GET_ENVIRON(environ);
5499 while (*env) {
5500 char *s = strchr(*env, '=');
5501 if (s) {
5502 rb_ary_push(ary, env_str_new2(s+1));
5504 env++;
5506 FREE_ENVIRON(environ);
5508 ENV_UNLOCK();
5510 return ary;
5514 * call-seq:
5515 * ENV.values -> array of values
5517 * Returns all environment variable values in an Array:
5518 * ENV.replace('foo' => '0', 'bar' => '1')
5519 * ENV.values # => ['1', '0']
5520 * The order of the values is OS-dependent.
5521 * See {About Ordering}[#class-ENV-label-About+Ordering].
5523 * Returns the empty Array if ENV is empty.
5525 static VALUE
5526 env_f_values(VALUE _)
5528 return env_values();
5532 * call-seq:
5533 * ENV.each_value { |value| block } -> ENV
5534 * ENV.each_value -> an_enumerator
5536 * Yields each environment variable value:
5537 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5538 * values = []
5539 * ENV.each_value { |value| values.push(value) } # => ENV
5540 * values # => ["1", "0"]
5542 * Returns an Enumerator if no block given:
5543 * e = ENV.each_value # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_value>
5544 * values = []
5545 * e.each { |value| values.push(value) } # => ENV
5546 * values # => ["1", "0"]
5548 static VALUE
5549 env_each_value(VALUE ehash)
5551 VALUE values;
5552 long i;
5554 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5555 values = env_values();
5556 for (i=0; i<RARRAY_LEN(values); i++) {
5557 rb_yield(RARRAY_AREF(values, i));
5559 return ehash;
5563 * call-seq:
5564 * ENV.each { |name, value| block } -> ENV
5565 * ENV.each -> an_enumerator
5566 * ENV.each_pair { |name, value| block } -> ENV
5567 * ENV.each_pair -> an_enumerator
5569 * Yields each environment variable name and its value as a 2-element \Array:
5570 * h = {}
5571 * ENV.each_pair { |name, value| h[name] = value } # => ENV
5572 * h # => {"bar"=>"1", "foo"=>"0"}
5574 * Returns an Enumerator if no block given:
5575 * h = {}
5576 * e = ENV.each_pair # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_pair>
5577 * e.each { |name, value| h[name] = value } # => ENV
5578 * h # => {"bar"=>"1", "foo"=>"0"}
5580 static VALUE
5581 env_each_pair(VALUE ehash)
5583 long i;
5585 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5587 VALUE ary = rb_ary_new();
5589 ENV_LOCK();
5591 char **env = GET_ENVIRON(environ);
5593 while (*env) {
5594 char *s = strchr(*env, '=');
5595 if (s) {
5596 rb_ary_push(ary, env_str_new(*env, s-*env));
5597 rb_ary_push(ary, env_str_new2(s+1));
5599 env++;
5601 FREE_ENVIRON(environ);
5603 ENV_UNLOCK();
5605 if (rb_block_pair_yield_optimizable()) {
5606 for (i=0; i<RARRAY_LEN(ary); i+=2) {
5607 rb_yield_values(2, RARRAY_AREF(ary, i), RARRAY_AREF(ary, i+1));
5610 else {
5611 for (i=0; i<RARRAY_LEN(ary); i+=2) {
5612 rb_yield(rb_assoc_new(RARRAY_AREF(ary, i), RARRAY_AREF(ary, i+1)));
5616 return ehash;
5620 * call-seq:
5621 * ENV.reject! { |name, value| block } -> ENV or nil
5622 * ENV.reject! -> an_enumerator
5624 * Similar to ENV.delete_if, but returns +nil+ if no changes were made.
5626 * Yields each environment variable name and its value as a 2-element Array,
5627 * deleting each environment variable for which the block returns a truthy value,
5628 * and returning ENV (if any deletions) or +nil+ (if not):
5629 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5630 * ENV.reject! { |name, value| name.start_with?('b') } # => ENV
5631 * ENV # => {"foo"=>"0"}
5632 * ENV.reject! { |name, value| name.start_with?('b') } # => nil
5634 * Returns an Enumerator if no block given:
5635 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5636 * e = ENV.reject! # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:reject!>
5637 * e.each { |name, value| name.start_with?('b') } # => ENV
5638 * ENV # => {"foo"=>"0"}
5639 * e.each { |name, value| name.start_with?('b') } # => nil
5641 static VALUE
5642 env_reject_bang(VALUE ehash)
5644 VALUE keys;
5645 long i;
5646 int del = 0;
5648 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5649 keys = env_keys(FALSE);
5650 RBASIC_CLEAR_CLASS(keys);
5651 for (i=0; i<RARRAY_LEN(keys); i++) {
5652 VALUE val = rb_f_getenv(Qnil, RARRAY_AREF(keys, i));
5653 if (!NIL_P(val)) {
5654 if (RTEST(rb_yield_values(2, RARRAY_AREF(keys, i), val))) {
5655 env_delete(RARRAY_AREF(keys, i));
5656 del++;
5660 RB_GC_GUARD(keys);
5661 if (del == 0) return Qnil;
5662 return envtbl;
5666 * call-seq:
5667 * ENV.delete_if { |name, value| block } -> ENV
5668 * ENV.delete_if -> an_enumerator
5670 * Yields each environment variable name and its value as a 2-element Array,
5671 * deleting each environment variable for which the block returns a truthy value,
5672 * and returning ENV (regardless of whether any deletions):
5673 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5674 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5675 * ENV # => {"foo"=>"0"}
5676 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5678 * Returns an Enumerator if no block given:
5679 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5680 * e = ENV.delete_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:delete_if!>
5681 * e.each { |name, value| name.start_with?('b') } # => ENV
5682 * ENV # => {"foo"=>"0"}
5683 * e.each { |name, value| name.start_with?('b') } # => ENV
5685 static VALUE
5686 env_delete_if(VALUE ehash)
5688 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5689 env_reject_bang(ehash);
5690 return envtbl;
5694 * call-seq:
5695 * ENV.values_at(*names) -> array of values
5697 * Returns an Array containing the environment variable values associated with
5698 * the given names:
5699 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5700 * ENV.values_at('foo', 'baz') # => ["0", "2"]
5702 * Returns +nil+ in the Array for each name that is not an ENV name:
5703 * ENV.values_at('foo', 'bat', 'bar', 'bam') # => ["0", nil, "1", nil]
5705 * Returns an empty \Array if no names given.
5707 * Raises an exception if any name is invalid.
5708 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
5710 static VALUE
5711 env_values_at(int argc, VALUE *argv, VALUE _)
5713 VALUE result;
5714 long i;
5716 result = rb_ary_new();
5717 for (i=0; i<argc; i++) {
5718 rb_ary_push(result, rb_f_getenv(Qnil, argv[i]));
5720 return result;
5724 * call-seq:
5725 * ENV.select { |name, value| block } -> hash of name/value pairs
5726 * ENV.select -> an_enumerator
5727 * ENV.filter { |name, value| block } -> hash of name/value pairs
5728 * ENV.filter -> an_enumerator
5730 * ENV.filter is an alias for ENV.select.
5732 * Yields each environment variable name and its value as a 2-element Array,
5733 * returning a Hash of the names and values for which the block returns a truthy value:
5734 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5735 * ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5736 * ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5738 * Returns an Enumerator if no block given:
5739 * e = ENV.select # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:select>
5740 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5741 * e = ENV.filter # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:filter>
5742 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5744 static VALUE
5745 env_select(VALUE ehash)
5747 VALUE result;
5748 VALUE keys;
5749 long i;
5751 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5752 result = rb_hash_new();
5753 keys = env_keys(FALSE);
5754 for (i = 0; i < RARRAY_LEN(keys); ++i) {
5755 VALUE key = RARRAY_AREF(keys, i);
5756 VALUE val = rb_f_getenv(Qnil, key);
5757 if (!NIL_P(val)) {
5758 if (RTEST(rb_yield_values(2, key, val))) {
5759 rb_hash_aset(result, key, val);
5763 RB_GC_GUARD(keys);
5765 return result;
5769 * call-seq:
5770 * ENV.select! { |name, value| block } -> ENV or nil
5771 * ENV.select! -> an_enumerator
5772 * ENV.filter! { |name, value| block } -> ENV or nil
5773 * ENV.filter! -> an_enumerator
5775 * ENV.filter! is an alias for ENV.select!.
5777 * Yields each environment variable name and its value as a 2-element Array,
5778 * deleting each entry for which the block returns +false+ or +nil+,
5779 * and returning ENV if any deletions made, or +nil+ otherwise:
5781 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5782 * ENV.select! { |name, value| name.start_with?('b') } # => ENV
5783 * ENV # => {"bar"=>"1", "baz"=>"2"}
5784 * ENV.select! { |name, value| true } # => nil
5786 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5787 * ENV.filter! { |name, value| name.start_with?('b') } # => ENV
5788 * ENV # => {"bar"=>"1", "baz"=>"2"}
5789 * ENV.filter! { |name, value| true } # => nil
5791 * Returns an Enumerator if no block given:
5793 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5794 * e = ENV.select! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:select!>
5795 * e.each { |name, value| name.start_with?('b') } # => ENV
5796 * ENV # => {"bar"=>"1", "baz"=>"2"}
5797 * e.each { |name, value| true } # => nil
5799 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5800 * e = ENV.filter! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:filter!>
5801 * e.each { |name, value| name.start_with?('b') } # => ENV
5802 * ENV # => {"bar"=>"1", "baz"=>"2"}
5803 * e.each { |name, value| true } # => nil
5805 static VALUE
5806 env_select_bang(VALUE ehash)
5808 VALUE keys;
5809 long i;
5810 int del = 0;
5812 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5813 keys = env_keys(FALSE);
5814 RBASIC_CLEAR_CLASS(keys);
5815 for (i=0; i<RARRAY_LEN(keys); i++) {
5816 VALUE val = rb_f_getenv(Qnil, RARRAY_AREF(keys, i));
5817 if (!NIL_P(val)) {
5818 if (!RTEST(rb_yield_values(2, RARRAY_AREF(keys, i), val))) {
5819 env_delete(RARRAY_AREF(keys, i));
5820 del++;
5824 RB_GC_GUARD(keys);
5825 if (del == 0) return Qnil;
5826 return envtbl;
5830 * call-seq:
5831 * ENV.keep_if { |name, value| block } -> ENV
5832 * ENV.keep_if -> an_enumerator
5834 * Yields each environment variable name and its value as a 2-element Array,
5835 * deleting each environment variable for which the block returns +false+ or +nil+,
5836 * and returning ENV:
5837 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5838 * ENV.keep_if { |name, value| name.start_with?('b') } # => ENV
5839 * ENV # => {"bar"=>"1", "baz"=>"2"}
5841 * Returns an Enumerator if no block given:
5842 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5843 * e = ENV.keep_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:keep_if>
5844 * e.each { |name, value| name.start_with?('b') } # => ENV
5845 * ENV # => {"bar"=>"1", "baz"=>"2"}
5847 static VALUE
5848 env_keep_if(VALUE ehash)
5850 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5851 env_select_bang(ehash);
5852 return envtbl;
5856 * call-seq:
5857 * ENV.slice(*names) -> hash of name/value pairs
5859 * Returns a Hash of the given ENV names and their corresponding values:
5860 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2', 'bat' => '3')
5861 * ENV.slice('foo', 'baz') # => {"foo"=>"0", "baz"=>"2"}
5862 * ENV.slice('baz', 'foo') # => {"baz"=>"2", "foo"=>"0"}
5863 * Raises an exception if any of the +names+ is invalid
5864 * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]):
5865 * ENV.slice('foo', 'bar', :bat) # Raises TypeError (no implicit conversion of Symbol into String)
5867 static VALUE
5868 env_slice(int argc, VALUE *argv, VALUE _)
5870 int i;
5871 VALUE key, value, result;
5873 if (argc == 0) {
5874 return rb_hash_new();
5876 result = rb_hash_new_with_size(argc);
5878 for (i = 0; i < argc; i++) {
5879 key = argv[i];
5880 value = rb_f_getenv(Qnil, key);
5881 if (value != Qnil)
5882 rb_hash_aset(result, key, value);
5885 return result;
5888 VALUE
5889 rb_env_clear(void)
5891 VALUE keys;
5892 long i;
5894 keys = env_keys(TRUE);
5895 for (i=0; i<RARRAY_LEN(keys); i++) {
5896 VALUE key = RARRAY_AREF(keys, i);
5897 const char *nam = RSTRING_PTR(key);
5898 ruby_setenv(nam, 0);
5900 RB_GC_GUARD(keys);
5901 return envtbl;
5905 * call-seq:
5906 * ENV.clear -> ENV
5908 * Removes every environment variable; returns ENV:
5909 * ENV.replace('foo' => '0', 'bar' => '1')
5910 * ENV.size # => 2
5911 * ENV.clear # => ENV
5912 * ENV.size # => 0
5914 static VALUE
5915 env_clear(VALUE _)
5917 return rb_env_clear();
5921 * call-seq:
5922 * ENV.to_s -> "ENV"
5924 * Returns String 'ENV':
5925 * ENV.to_s # => "ENV"
5927 static VALUE
5928 env_to_s(VALUE _)
5930 return rb_usascii_str_new2("ENV");
5934 * call-seq:
5935 * ENV.inspect -> a_string
5937 * Returns the contents of the environment as a String:
5938 * ENV.replace('foo' => '0', 'bar' => '1')
5939 * ENV.inspect # => "{\"bar\"=>\"1\", \"foo\"=>\"0\"}"
5941 static VALUE
5942 env_inspect(VALUE _)
5944 VALUE i;
5945 VALUE str = rb_str_buf_new2("{");
5947 ENV_LOCK();
5949 char **env = GET_ENVIRON(environ);
5950 while (*env) {
5951 char *s = strchr(*env, '=');
5953 if (env != environ) {
5954 rb_str_buf_cat2(str, ", ");
5956 if (s) {
5957 rb_str_buf_cat2(str, "\"");
5958 rb_str_buf_cat(str, *env, s-*env);
5959 rb_str_buf_cat2(str, "\"=>");
5960 i = rb_inspect(rb_str_new2(s+1));
5961 rb_str_buf_append(str, i);
5963 env++;
5965 FREE_ENVIRON(environ);
5967 ENV_UNLOCK();
5969 rb_str_buf_cat2(str, "}");
5971 return str;
5975 * call-seq:
5976 * ENV.to_a -> array of 2-element arrays
5978 * Returns the contents of ENV as an Array of 2-element Arrays,
5979 * each of which is a name/value pair:
5980 * ENV.replace('foo' => '0', 'bar' => '1')
5981 * ENV.to_a # => [["bar", "1"], ["foo", "0"]]
5983 static VALUE
5984 env_to_a(VALUE _)
5986 VALUE ary = rb_ary_new();
5988 ENV_LOCK();
5990 char **env = GET_ENVIRON(environ);
5991 while (*env) {
5992 char *s = strchr(*env, '=');
5993 if (s) {
5994 rb_ary_push(ary, rb_assoc_new(env_str_new(*env, s-*env),
5995 env_str_new2(s+1)));
5997 env++;
5999 FREE_ENVIRON(environ);
6001 ENV_UNLOCK();
6003 return ary;
6007 * call-seq:
6008 * ENV.rehash -> nil
6010 * (Provided for compatibility with Hash.)
6012 * Does not modify ENV; returns +nil+.
6014 static VALUE
6015 env_none(VALUE _)
6017 return Qnil;
6020 static int
6021 env_size_with_lock(void)
6023 int i = 0;
6025 ENV_LOCK();
6027 char **env = GET_ENVIRON(environ);
6028 while (env[i]) i++;
6029 FREE_ENVIRON(environ);
6031 ENV_UNLOCK();
6033 return i;
6037 * call-seq:
6038 * ENV.length -> an_integer
6039 * ENV.size -> an_integer
6041 * Returns the count of environment variables:
6042 * ENV.replace('foo' => '0', 'bar' => '1')
6043 * ENV.length # => 2
6044 * ENV.size # => 2
6046 static VALUE
6047 env_size(VALUE _)
6049 return INT2FIX(env_size_with_lock());
6053 * call-seq:
6054 * ENV.empty? -> true or false
6056 * Returns +true+ when there are no environment variables, +false+ otherwise:
6057 * ENV.clear
6058 * ENV.empty? # => true
6059 * ENV['foo'] = '0'
6060 * ENV.empty? # => false
6062 static VALUE
6063 env_empty_p(VALUE _)
6065 bool empty = true;
6067 ENV_LOCK();
6069 char **env = GET_ENVIRON(environ);
6070 if (env[0] != 0) {
6071 empty = false;
6073 FREE_ENVIRON(environ);
6075 ENV_UNLOCK();
6077 return RBOOL(empty);
6081 * call-seq:
6082 * ENV.include?(name) -> true or false
6083 * ENV.has_key?(name) -> true or false
6084 * ENV.member?(name) -> true or false
6085 * ENV.key?(name) -> true or false
6087 * ENV.has_key?, ENV.member?, and ENV.key? are aliases for ENV.include?.
6089 * Returns +true+ if there is an environment variable with the given +name+:
6090 * ENV.replace('foo' => '0', 'bar' => '1')
6091 * ENV.include?('foo') # => true
6092 * Returns +false+ if +name+ is a valid String and there is no such environment variable:
6093 * ENV.include?('baz') # => false
6094 * Returns +false+ if +name+ is the empty String or is a String containing character <code>'='</code>:
6095 * ENV.include?('') # => false
6096 * ENV.include?('=') # => false
6097 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6098 * ENV.include?("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6099 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6100 * ENV.include?("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6101 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6102 * Raises an exception if +name+ is not a String:
6103 * ENV.include?(Object.new) # TypeError (no implicit conversion of Object into String)
6105 static VALUE
6106 env_has_key(VALUE env, VALUE key)
6108 const char *s = env_name(key);
6109 return RBOOL(has_env_with_lock(s));
6113 * call-seq:
6114 * ENV.assoc(name) -> [name, value] or nil
6116 * Returns a 2-element Array containing the name and value of the environment variable
6117 * for +name+ if it exists:
6118 * ENV.replace('foo' => '0', 'bar' => '1')
6119 * ENV.assoc('foo') # => ['foo', '0']
6120 * Returns +nil+ if +name+ is a valid String and there is no such environment variable.
6122 * Returns +nil+ if +name+ is the empty String or is a String containing character <code>'='</code>.
6124 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6125 * ENV.assoc("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6126 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6127 * ENV.assoc("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6128 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6129 * Raises an exception if +name+ is not a String:
6130 * ENV.assoc(Object.new) # TypeError (no implicit conversion of Object into String)
6132 static VALUE
6133 env_assoc(VALUE env, VALUE key)
6135 const char *s = env_name(key);
6136 VALUE e = getenv_with_lock(s);
6138 if (!NIL_P(e)) {
6139 return rb_assoc_new(key, e);
6141 else {
6142 return Qnil;
6147 * call-seq:
6148 * ENV.value?(value) -> true or false
6149 * ENV.has_value?(value) -> true or false
6151 * Returns +true+ if +value+ is the value for some environment variable name, +false+ otherwise:
6152 * ENV.replace('foo' => '0', 'bar' => '1')
6153 * ENV.value?('0') # => true
6154 * ENV.has_value?('0') # => true
6155 * ENV.value?('2') # => false
6156 * ENV.has_value?('2') # => false
6158 static VALUE
6159 env_has_value(VALUE dmy, VALUE obj)
6161 obj = rb_check_string_type(obj);
6162 if (NIL_P(obj)) return Qnil;
6164 VALUE ret = Qfalse;
6166 ENV_LOCK();
6168 char **env = GET_ENVIRON(environ);
6169 while (*env) {
6170 char *s = strchr(*env, '=');
6171 if (s++) {
6172 long len = strlen(s);
6173 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
6174 ret = Qtrue;
6175 break;
6178 env++;
6180 FREE_ENVIRON(environ);
6182 ENV_UNLOCK();
6184 return ret;
6188 * call-seq:
6189 * ENV.rassoc(value) -> [name, value] or nil
6191 * Returns a 2-element Array containing the name and value of the
6192 * *first* *found* environment variable that has value +value+, if one
6193 * exists:
6194 * ENV.replace('foo' => '0', 'bar' => '0')
6195 * ENV.rassoc('0') # => ["bar", "0"]
6196 * The order in which environment variables are examined is OS-dependent.
6197 * See {About Ordering}[#class-ENV-label-About+Ordering].
6199 * Returns +nil+ if there is no such environment variable.
6201 static VALUE
6202 env_rassoc(VALUE dmy, VALUE obj)
6204 obj = rb_check_string_type(obj);
6205 if (NIL_P(obj)) return Qnil;
6207 VALUE result = Qnil;
6209 ENV_LOCK();
6211 char **env = GET_ENVIRON(environ);
6213 while (*env) {
6214 const char *p = *env;
6215 char *s = strchr(p, '=');
6216 if (s++) {
6217 long len = strlen(s);
6218 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
6219 result = rb_assoc_new(rb_str_new(p, s-p-1), obj);
6220 break;
6223 env++;
6225 FREE_ENVIRON(environ);
6227 ENV_UNLOCK();
6229 return result;
6233 * call-seq:
6234 * ENV.key(value) -> name or nil
6236 * Returns the name of the first environment variable with +value+, if it exists:
6237 * ENV.replace('foo' => '0', 'bar' => '0')
6238 * ENV.key('0') # => "foo"
6239 * The order in which environment variables are examined is OS-dependent.
6240 * See {About Ordering}[#class-ENV-label-About+Ordering].
6242 * Returns +nil+ if there is no such value.
6244 * Raises an exception if +value+ is invalid:
6245 * ENV.key(Object.new) # raises TypeError (no implicit conversion of Object into String)
6246 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
6248 static VALUE
6249 env_key(VALUE dmy, VALUE value)
6251 SafeStringValue(value);
6252 VALUE str = Qnil;
6254 ENV_LOCK();
6256 char **env = GET_ENVIRON(environ);
6257 while (*env) {
6258 char *s = strchr(*env, '=');
6259 if (s++) {
6260 long len = strlen(s);
6261 if (RSTRING_LEN(value) == len && strncmp(s, RSTRING_PTR(value), len) == 0) {
6262 str = env_str_new(*env, s-*env-1);
6263 break;
6266 env++;
6268 FREE_ENVIRON(environ);
6270 ENV_UNLOCK();
6272 return str;
6275 static VALUE
6276 env_to_hash(void)
6278 VALUE hash = rb_hash_new();
6280 ENV_LOCK();
6282 char **env = GET_ENVIRON(environ);
6283 while (*env) {
6284 char *s = strchr(*env, '=');
6285 if (s) {
6286 rb_hash_aset(hash, env_str_new(*env, s-*env),
6287 env_str_new2(s+1));
6289 env++;
6291 FREE_ENVIRON(environ);
6293 ENV_UNLOCK();
6295 return hash;
6298 VALUE
6299 rb_envtbl(void)
6301 return envtbl;
6304 VALUE
6305 rb_env_to_hash(void)
6307 return env_to_hash();
6311 * call-seq:
6312 * ENV.to_hash -> hash of name/value pairs
6314 * Returns a Hash containing all name/value pairs from ENV:
6315 * ENV.replace('foo' => '0', 'bar' => '1')
6316 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6319 static VALUE
6320 env_f_to_hash(VALUE _)
6322 return env_to_hash();
6326 * call-seq:
6327 * ENV.to_h -> hash of name/value pairs
6328 * ENV.to_h {|name, value| block } -> hash of name/value pairs
6330 * With no block, returns a Hash containing all name/value pairs from ENV:
6331 * ENV.replace('foo' => '0', 'bar' => '1')
6332 * ENV.to_h # => {"bar"=>"1", "foo"=>"0"}
6333 * With a block, returns a Hash whose items are determined by the block.
6334 * Each name/value pair in ENV is yielded to the block.
6335 * The block must return a 2-element Array (name/value pair)
6336 * that is added to the return Hash as a key and value:
6337 * ENV.to_h { |name, value| [name.to_sym, value.to_i] } # => {:bar=>1, :foo=>0}
6338 * Raises an exception if the block does not return an Array:
6339 * ENV.to_h { |name, value| name } # Raises TypeError (wrong element type String (expected array))
6340 * Raises an exception if the block returns an Array of the wrong size:
6341 * ENV.to_h { |name, value| [name] } # Raises ArgumentError (element has wrong array length (expected 2, was 1))
6343 static VALUE
6344 env_to_h(VALUE _)
6346 VALUE hash = env_to_hash();
6347 if (rb_block_given_p()) {
6348 hash = rb_hash_to_h_block(hash);
6350 return hash;
6354 * call-seq:
6355 * ENV.except(*keys) -> a_hash
6357 * Returns a hash except the given keys from ENV and their values.
6359 * ENV #=> {"LANG"=>"en_US.UTF-8", "TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"}
6360 * ENV.except("TERM","HOME") #=> {"LANG"=>"en_US.UTF-8"}
6362 static VALUE
6363 env_except(int argc, VALUE *argv, VALUE _)
6365 int i;
6366 VALUE key, hash = env_to_hash();
6368 for (i = 0; i < argc; i++) {
6369 key = argv[i];
6370 rb_hash_delete(hash, key);
6373 return hash;
6377 * call-seq:
6378 * ENV.reject { |name, value| block } -> hash of name/value pairs
6379 * ENV.reject -> an_enumerator
6381 * Yields each environment variable name and its value as a 2-element Array.
6382 * Returns a Hash whose items are determined by the block.
6383 * When the block returns a truthy value, the name/value pair is added to the return Hash;
6384 * otherwise the pair is ignored:
6385 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
6386 * ENV.reject { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6387 * Returns an Enumerator if no block given:
6388 * e = ENV.reject
6389 * e.each { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6391 static VALUE
6392 env_reject(VALUE _)
6394 return rb_hash_delete_if(env_to_hash());
6397 NORETURN(static VALUE env_freeze(VALUE self));
6399 * call-seq:
6400 * ENV.freeze
6402 * Raises an exception:
6403 * ENV.freeze # Raises TypeError (cannot freeze ENV)
6405 static VALUE
6406 env_freeze(VALUE self)
6408 rb_raise(rb_eTypeError, "cannot freeze ENV");
6409 UNREACHABLE_RETURN(self);
6413 * call-seq:
6414 * ENV.shift -> [name, value] or nil
6416 * Removes the first environment variable from ENV and returns
6417 * a 2-element Array containing its name and value:
6418 * ENV.replace('foo' => '0', 'bar' => '1')
6419 * ENV.to_hash # => {'bar' => '1', 'foo' => '0'}
6420 * ENV.shift # => ['bar', '1']
6421 * ENV.to_hash # => {'foo' => '0'}
6422 * Exactly which environment variable is "first" is OS-dependent.
6423 * See {About Ordering}[#class-ENV-label-About+Ordering].
6425 * Returns +nil+ if the environment is empty.
6427 static VALUE
6428 env_shift(VALUE _)
6430 VALUE result = Qnil;
6431 VALUE key = Qnil;
6433 ENV_LOCK();
6435 char **env = GET_ENVIRON(environ);
6436 if (*env) {
6437 const char *p = *env;
6438 char *s = strchr(p, '=');
6439 if (s) {
6440 key = env_str_new(p, s-p);
6441 VALUE val = env_str_new2(getenv(RSTRING_PTR(key)));
6442 result = rb_assoc_new(key, val);
6445 FREE_ENVIRON(environ);
6447 ENV_UNLOCK();
6449 if (!NIL_P(key)) {
6450 env_delete(key);
6453 return result;
6457 * call-seq:
6458 * ENV.invert -> hash of value/name pairs
6460 * Returns a Hash whose keys are the ENV values,
6461 * and whose values are the corresponding ENV names:
6462 * ENV.replace('foo' => '0', 'bar' => '1')
6463 * ENV.invert # => {"1"=>"bar", "0"=>"foo"}
6464 * For a duplicate ENV value, overwrites the hash entry:
6465 * ENV.replace('foo' => '0', 'bar' => '0')
6466 * ENV.invert # => {"0"=>"foo"}
6467 * Note that the order of the ENV processing is OS-dependent,
6468 * which means that the order of overwriting is also OS-dependent.
6469 * See {About Ordering}[#class-ENV-label-About+Ordering].
6471 static VALUE
6472 env_invert(VALUE _)
6474 return rb_hash_invert(env_to_hash());
6477 static void
6478 keylist_delete(VALUE keys, VALUE key)
6480 long keylen, elen;
6481 const char *keyptr, *eptr;
6482 RSTRING_GETMEM(key, keyptr, keylen);
6483 /* Don't stop at first key, as it is possible to have
6484 multiple environment values with the same key.
6486 for (long i=0; i<RARRAY_LEN(keys); i++) {
6487 VALUE e = RARRAY_AREF(keys, i);
6488 RSTRING_GETMEM(e, eptr, elen);
6489 if (elen != keylen) continue;
6490 if (!ENVNMATCH(keyptr, eptr, elen)) continue;
6491 rb_ary_delete_at(keys, i);
6492 i--;
6496 static int
6497 env_replace_i(VALUE key, VALUE val, VALUE keys)
6499 env_name(key);
6500 env_aset(key, val);
6502 keylist_delete(keys, key);
6503 return ST_CONTINUE;
6507 * call-seq:
6508 * ENV.replace(hash) -> ENV
6510 * Replaces the entire content of the environment variables
6511 * with the name/value pairs in the given +hash+;
6512 * returns ENV.
6514 * Replaces the content of ENV with the given pairs:
6515 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
6516 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6518 * Raises an exception if a name or value is invalid
6519 * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]):
6520 * ENV.replace('foo' => '0', :bar => '1') # Raises TypeError (no implicit conversion of Symbol into String)
6521 * ENV.replace('foo' => '0', 'bar' => 1) # Raises TypeError (no implicit conversion of Integer into String)
6522 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6524 static VALUE
6525 env_replace(VALUE env, VALUE hash)
6527 VALUE keys;
6528 long i;
6530 keys = env_keys(TRUE);
6531 if (env == hash) return env;
6532 hash = to_hash(hash);
6533 rb_hash_foreach(hash, env_replace_i, keys);
6535 for (i=0; i<RARRAY_LEN(keys); i++) {
6536 env_delete(RARRAY_AREF(keys, i));
6538 RB_GC_GUARD(keys);
6539 return env;
6542 static int
6543 env_update_i(VALUE key, VALUE val, VALUE _)
6545 env_aset(key, val);
6546 return ST_CONTINUE;
6549 static int
6550 env_update_block_i(VALUE key, VALUE val, VALUE _)
6552 VALUE oldval = rb_f_getenv(Qnil, key);
6553 if (!NIL_P(oldval)) {
6554 val = rb_yield_values(3, key, oldval, val);
6556 env_aset(key, val);
6557 return ST_CONTINUE;
6561 * call-seq:
6562 * ENV.update(hash) -> ENV
6563 * ENV.update(hash) { |name, env_val, hash_val| block } -> ENV
6564 * ENV.merge!(hash) -> ENV
6565 * ENV.merge!(hash) { |name, env_val, hash_val| block } -> ENV
6567 * ENV.update is an alias for ENV.merge!.
6569 * Adds to ENV each key/value pair in the given +hash+; returns ENV:
6570 * ENV.replace('foo' => '0', 'bar' => '1')
6571 * ENV.merge!('baz' => '2', 'bat' => '3') # => {"bar"=>"1", "bat"=>"3", "baz"=>"2", "foo"=>"0"}
6572 * Deletes the ENV entry for a hash value that is +nil+:
6573 * ENV.merge!('baz' => nil, 'bat' => nil) # => {"bar"=>"1", "foo"=>"0"}
6574 * For an already-existing name, if no block given, overwrites the ENV value:
6575 * ENV.merge!('foo' => '4') # => {"bar"=>"1", "foo"=>"4"}
6576 * For an already-existing name, if block given,
6577 * yields the name, its ENV value, and its hash value;
6578 * the block's return value becomes the new name:
6579 * ENV.merge!('foo' => '5') { |name, env_val, hash_val | env_val + hash_val } # => {"bar"=>"1", "foo"=>"45"}
6580 * Raises an exception if a name or value is invalid
6581 * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]);
6582 * ENV.replace('foo' => '0', 'bar' => '1')
6583 * ENV.merge!('foo' => '6', :bar => '7', 'baz' => '9') # Raises TypeError (no implicit conversion of Symbol into String)
6584 * ENV # => {"bar"=>"1", "foo"=>"6"}
6585 * ENV.merge!('foo' => '7', 'bar' => 8, 'baz' => '9') # Raises TypeError (no implicit conversion of Integer into String)
6586 * ENV # => {"bar"=>"1", "foo"=>"7"}
6587 * Raises an exception if the block returns an invalid name:
6588 * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]):
6589 * ENV.merge!('bat' => '8', 'foo' => '9') { |name, env_val, hash_val | 10 } # Raises TypeError (no implicit conversion of Integer into String)
6590 * ENV # => {"bar"=>"1", "bat"=>"8", "foo"=>"7"}
6592 * Note that for the exceptions above,
6593 * hash pairs preceding an invalid name or value are processed normally;
6594 * those following are ignored.
6596 static VALUE
6597 env_update(VALUE env, VALUE hash)
6599 if (env == hash) return env;
6600 hash = to_hash(hash);
6601 rb_foreach_func *func = rb_block_given_p() ?
6602 env_update_block_i : env_update_i;
6603 rb_hash_foreach(hash, func, 0);
6604 return env;
6608 * call-seq:
6609 * ENV.clone(freeze: nil) -> ENV
6611 * Returns ENV itself, and warns because ENV is a wrapper for the
6612 * process-wide environment variables and a clone is useless.
6613 * If +freeze+ keyword is given and not +nil+ or +false+, raises ArgumentError.
6614 * If +freeze+ keyword is given and +true+, raises TypeError, as ENV storage
6615 * cannot be frozen.
6617 static VALUE
6618 env_clone(int argc, VALUE *argv, VALUE obj)
6620 if (argc) {
6621 VALUE opt, kwfreeze;
6622 if (rb_scan_args(argc, argv, "0:", &opt) < argc) {
6623 kwfreeze = rb_get_freeze_opt(1, &opt);
6624 if (RTEST(kwfreeze)) {
6625 rb_raise(rb_eTypeError, "cannot freeze ENV");
6630 rb_warn_deprecated("ENV.clone", "ENV.to_h");
6631 return envtbl;
6634 NORETURN(static VALUE env_dup(VALUE));
6636 * call-seq:
6637 * ENV.dup # raises TypeError
6639 * Raises TypeError, because ENV is a singleton object.
6640 * Use #to_h to get a copy of ENV data as a hash.
6642 static VALUE
6643 env_dup(VALUE obj)
6645 rb_raise(rb_eTypeError, "Cannot dup ENV, use ENV.to_h to get a copy of ENV as a hash");
6648 static const rb_data_type_t env_data_type = {
6649 "ENV",
6651 NULL,
6652 NULL,
6653 NULL,
6654 NULL,
6656 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
6660 * A \Hash maps each of its unique keys to a specific value.
6662 * A \Hash has certain similarities to an \Array, but:
6663 * - An \Array index is always an \Integer.
6664 * - A \Hash key can be (almost) any object.
6666 * === \Hash \Data Syntax
6668 * The older syntax for \Hash data uses the "hash rocket," <tt>=></tt>:
6670 * h = {:foo => 0, :bar => 1, :baz => 2}
6671 * h # => {:foo=>0, :bar=>1, :baz=>2}
6673 * Alternatively, but only for a \Hash key that's a \Symbol,
6674 * you can use a newer JSON-style syntax,
6675 * where each bareword becomes a \Symbol:
6677 * h = {foo: 0, bar: 1, baz: 2}
6678 * h # => {:foo=>0, :bar=>1, :baz=>2}
6680 * You can also use a \String in place of a bareword:
6682 * h = {'foo': 0, 'bar': 1, 'baz': 2}
6683 * h # => {:foo=>0, :bar=>1, :baz=>2}
6685 * And you can mix the styles:
6687 * h = {foo: 0, :bar => 1, 'baz': 2}
6688 * h # => {:foo=>0, :bar=>1, :baz=>2}
6690 * But it's an error to try the JSON-style syntax
6691 * for a key that's not a bareword or a String:
6693 * # Raises SyntaxError (syntax error, unexpected ':', expecting =>):
6694 * h = {0: 'zero'}
6696 * Hash value can be omitted, meaning that value will be fetched from the context
6697 * by the name of the key:
6699 * x = 0
6700 * y = 100
6701 * h = {x:, y:}
6702 * h # => {:x=>0, :y=>100}
6704 * === Common Uses
6706 * You can use a \Hash to give names to objects:
6708 * person = {name: 'Matz', language: 'Ruby'}
6709 * person # => {:name=>"Matz", :language=>"Ruby"}
6711 * You can use a \Hash to give names to method arguments:
6713 * def some_method(hash)
6714 * p hash
6715 * end
6716 * some_method({foo: 0, bar: 1, baz: 2}) # => {:foo=>0, :bar=>1, :baz=>2}
6718 * Note: when the last argument in a method call is a \Hash,
6719 * the curly braces may be omitted:
6721 * some_method(foo: 0, bar: 1, baz: 2) # => {:foo=>0, :bar=>1, :baz=>2}
6723 * You can use a \Hash to initialize an object:
6725 * class Dev
6726 * attr_accessor :name, :language
6727 * def initialize(hash)
6728 * self.name = hash[:name]
6729 * self.language = hash[:language]
6730 * end
6731 * end
6732 * matz = Dev.new(name: 'Matz', language: 'Ruby')
6733 * matz # => #<Dev: @name="Matz", @language="Ruby">
6735 * === Creating a \Hash
6737 * You can create a \Hash object explicitly with:
6739 * - A {hash literal}[doc/syntax/literals_rdoc.html#label-Hash+Literals].
6741 * You can convert certain objects to Hashes with:
6743 * - \Method {Hash}[Kernel.html#method-i-Hash].
6745 * You can create a \Hash by calling method Hash.new.
6747 * Create an empty Hash:
6749 * h = Hash.new
6750 * h # => {}
6751 * h.class # => Hash
6753 * You can create a \Hash by calling method Hash.[].
6755 * Create an empty Hash:
6757 * h = Hash[]
6758 * h # => {}
6760 * Create a \Hash with initial entries:
6762 * h = Hash[foo: 0, bar: 1, baz: 2]
6763 * h # => {:foo=>0, :bar=>1, :baz=>2}
6765 * You can create a \Hash by using its literal form (curly braces).
6767 * Create an empty \Hash:
6769 * h = {}
6770 * h # => {}
6772 * Create a \Hash with initial entries:
6774 * h = {foo: 0, bar: 1, baz: 2}
6775 * h # => {:foo=>0, :bar=>1, :baz=>2}
6778 * === \Hash Value Basics
6780 * The simplest way to retrieve a \Hash value (instance method #[]):
6782 * h = {foo: 0, bar: 1, baz: 2}
6783 * h[:foo] # => 0
6785 * The simplest way to create or update a \Hash value (instance method #[]=):
6787 * h = {foo: 0, bar: 1, baz: 2}
6788 * h[:bat] = 3 # => 3
6789 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
6790 * h[:foo] = 4 # => 4
6791 * h # => {:foo=>4, :bar=>1, :baz=>2, :bat=>3}
6793 * The simplest way to delete a \Hash entry (instance method #delete):
6795 * h = {foo: 0, bar: 1, baz: 2}
6796 * h.delete(:bar) # => 1
6797 * h # => {:foo=>0, :baz=>2}
6799 * === Entry Order
6801 * A \Hash object presents its entries in the order of their creation. This is seen in:
6803 * - Iterative methods such as <tt>each</tt>, <tt>each_key</tt>, <tt>each_pair</tt>, <tt>each_value</tt>.
6804 * - Other order-sensitive methods such as <tt>shift</tt>, <tt>keys</tt>, <tt>values</tt>.
6805 * - The \String returned by method <tt>inspect</tt>.
6807 * A new \Hash has its initial ordering per the given entries:
6809 * h = Hash[foo: 0, bar: 1]
6810 * h # => {:foo=>0, :bar=>1}
6812 * New entries are added at the end:
6814 * h[:baz] = 2
6815 * h # => {:foo=>0, :bar=>1, :baz=>2}
6817 * Updating a value does not affect the order:
6819 * h[:baz] = 3
6820 * h # => {:foo=>0, :bar=>1, :baz=>3}
6822 * But re-creating a deleted entry can affect the order:
6824 * h.delete(:foo)
6825 * h[:foo] = 5
6826 * h # => {:bar=>1, :baz=>3, :foo=>5}
6828 * === \Hash Keys
6830 * ==== \Hash Key Equivalence
6832 * Two objects are treated as the same \hash key when their <code>hash</code> value
6833 * is identical and the two objects are <code>eql?</code> to each other.
6835 * ==== Modifying an Active \Hash Key
6837 * Modifying a \Hash key while it is in use damages the hash's index.
6839 * This \Hash has keys that are Arrays:
6841 * a0 = [ :foo, :bar ]
6842 * a1 = [ :baz, :bat ]
6843 * h = {a0 => 0, a1 => 1}
6844 * h.include?(a0) # => true
6845 * h[a0] # => 0
6846 * a0.hash # => 110002110
6848 * Modifying array element <tt>a0[0]</tt> changes its hash value:
6850 * a0[0] = :bam
6851 * a0.hash # => 1069447059
6853 * And damages the \Hash index:
6855 * h.include?(a0) # => false
6856 * h[a0] # => nil
6858 * You can repair the hash index using method +rehash+:
6860 * h.rehash # => {[:bam, :bar]=>0, [:baz, :bat]=>1}
6861 * h.include?(a0) # => true
6862 * h[a0] # => 0
6864 * A \String key is always safe.
6865 * That's because an unfrozen \String
6866 * passed as a key will be replaced by a duplicated and frozen \String:
6868 * s = 'foo'
6869 * s.frozen? # => false
6870 * h = {s => 0}
6871 * first_key = h.keys.first
6872 * first_key.frozen? # => true
6874 * ==== User-Defined \Hash Keys
6876 * To be useable as a \Hash key, objects must implement the methods <code>hash</code> and <code>eql?</code>.
6877 * Note: this requirement does not apply if the \Hash uses #compare_by_identity since comparison will then
6878 * rely on the keys' object id instead of <code>hash</code> and <code>eql?</code>.
6880 * \Object defines basic implementation for <code>hash</code> and <code>eq?</code> that makes each object
6881 * a distinct key. Typically, user-defined classes will want to override these methods to provide meaningful
6882 * behavior, or for example inherit \Struct that has useful definitions for these.
6884 * A typical implementation of <code>hash</code> is based on the
6885 * object's data while <code>eql?</code> is usually aliased to the overridden
6886 * <code>==</code> method:
6888 * class Book
6889 * attr_reader :author, :title
6891 * def initialize(author, title)
6892 * @author = author
6893 * @title = title
6894 * end
6896 * def ==(other)
6897 * self.class === other &&
6898 * other.author == @author &&
6899 * other.title == @title
6900 * end
6902 * alias eql? ==
6904 * def hash
6905 * @author.hash ^ @title.hash # XOR
6906 * end
6907 * end
6909 * book1 = Book.new 'matz', 'Ruby in a Nutshell'
6910 * book2 = Book.new 'matz', 'Ruby in a Nutshell'
6912 * reviews = {}
6914 * reviews[book1] = 'Great reference!'
6915 * reviews[book2] = 'Nice and compact!'
6917 * reviews.length #=> 1
6919 * === Default Values
6921 * The methods #[], #values_at and #dig need to return the value associated to a certain key.
6922 * When that key is not found, that value will be determined by its default proc (if any)
6923 * or else its default (initially `nil`).
6925 * You can retrieve the default value with method #default:
6927 * h = Hash.new
6928 * h.default # => nil
6930 * You can set the default value by passing an argument to method Hash.new or
6931 * with method #default=
6933 * h = Hash.new(-1)
6934 * h.default # => -1
6935 * h.default = 0
6936 * h.default # => 0
6938 * This default value is returned for #[], #values_at and #dig when a key is
6939 * not found:
6941 * counts = {foo: 42}
6942 * counts.default # => nil (default)
6943 * counts[:foo] = 42
6944 * counts[:bar] # => nil
6945 * counts.default = 0
6946 * counts[:bar] # => 0
6947 * counts.values_at(:foo, :bar, :baz) # => [42, 0, 0]
6948 * counts.dig(:bar) # => 0
6950 * Note that the default value is used without being duplicated. It is not advised to set
6951 * the default value to a mutable object:
6953 * synonyms = Hash.new([])
6954 * synonyms[:hello] # => []
6955 * synonyms[:hello] << :hi # => [:hi], but this mutates the default!
6956 * synonyms.default # => [:hi]
6957 * synonyms[:world] << :universe
6958 * synonyms[:world] # => [:hi, :universe], oops
6959 * synonyms.keys # => [], oops
6961 * To use a mutable object as default, it is recommended to use a default proc
6963 * ==== Default \Proc
6965 * When the default proc for a \Hash is set (i.e., not +nil+),
6966 * the default value returned by method #[] is determined by the default proc alone.
6968 * You can retrieve the default proc with method #default_proc:
6970 * h = Hash.new
6971 * h.default_proc # => nil
6973 * You can set the default proc by calling Hash.new with a block or
6974 * calling the method #default_proc=
6976 * h = Hash.new { |hash, key| "Default value for #{key}" }
6977 * h.default_proc.class # => Proc
6978 * h.default_proc = proc { |hash, key| "Default value for #{key.inspect}" }
6979 * h.default_proc.class # => Proc
6981 * When the default proc is set (i.e., not +nil+)
6982 * and method #[] is called with with a non-existent key,
6983 * #[] calls the default proc with both the \Hash object itself and the missing key,
6984 * then returns the proc's return value:
6986 * h = Hash.new { |hash, key| "Default value for #{key}" }
6987 * h[:nosuch] # => "Default value for nosuch"
6989 * Note that in the example above no entry for key +:nosuch+ is created:
6991 * h.include?(:nosuch) # => false
6993 * However, the proc itself can add a new entry:
6995 * synonyms = Hash.new { |hash, key| hash[key] = [] }
6996 * synonyms.include?(:hello) # => false
6997 * synonyms[:hello] << :hi # => [:hi]
6998 * synonyms[:world] << :universe # => [:universe]
6999 * synonyms.keys # => [:hello, :world]
7001 * Note that setting the default proc will clear the default value and vice versa.
7003 * === What's Here
7005 * First, what's elsewhere. \Class \Hash:
7007 * - Inherits from {class Object}[Object.html#class-Object-label-What-27s+Here].
7008 * - Includes {module Enumerable}[Enumerable.html#module-Enumerable-label-What-27s+Here],
7009 * which provides dozens of additional methods.
7011 * Here, class \Hash provides methods that are useful for:
7013 * - {Creating a Hash}[#class-Hash-label-Methods+for+Creating+a+Hash]
7014 * - {Setting Hash State}[#class-Hash-label-Methods+for+Setting+Hash+State]
7015 * - {Querying}[#class-Hash-label-Methods+for+Querying]
7016 * - {Comparing}[#class-Hash-label-Methods+for+Comparing]
7017 * - {Fetching}[#class-Hash-label-Methods+for+Fetching]
7018 * - {Assigning}[#class-Hash-label-Methods+for+Assigning]
7019 * - {Deleting}[#class-Hash-label-Methods+for+Deleting]
7020 * - {Iterating}[#class-Hash-label-Methods+for+Iterating]
7021 * - {Converting}[#class-Hash-label-Methods+for+Converting]
7022 * - {Transforming Keys and Values}[#class-Hash-label-Methods+for+Transforming+Keys+and+Values]
7023 * - {And more....}[#class-Hash-label-Other+Methods]
7025 * \Class \Hash also includes methods from module Enumerable.
7027 * ==== Methods for Creating a \Hash
7029 * ::[]:: Returns a new hash populated with given objects.
7030 * ::new:: Returns a new empty hash.
7031 * ::try_convert:: Returns a new hash created from a given object.
7033 * ==== Methods for Setting \Hash State
7035 * #compare_by_identity:: Sets +self+ to consider only identity in comparing keys.
7036 * #default=:: Sets the default to a given value.
7037 * #default_proc=:: Sets the default proc to a given proc.
7038 * #rehash:: Rebuilds the hash table by recomputing the hash index for each key.
7040 * ==== Methods for Querying
7042 * #any?:: Returns whether any element satisfies a given criterion.
7043 * #compare_by_identity?:: Returns whether the hash considers only identity when comparing keys.
7044 * #default:: Returns the default value, or the default value for a given key.
7045 * #default_proc:: Returns the default proc.
7046 * #empty?:: Returns whether there are no entries.
7047 * #eql?:: Returns whether a given object is equal to +self+.
7048 * #hash:: Returns the integer hash code.
7049 * #has_value?:: Returns whether a given object is a value in +self+.
7050 * #include?, #has_key?, #member?, #key?:: Returns whether a given object is a key in +self+.
7051 * #length, #size:: Returns the count of entries.
7052 * #value?:: Returns whether a given object is a value in +self+.
7054 * ==== Methods for Comparing
7056 * {#<}[#method-i-3C]:: Returns whether +self+ is a proper subset of a given object.
7057 * {#<=}[#method-i-3C-3D]:: Returns whether +self+ is a subset of a given object.
7058 * {#==}[#method-i-3D-3D]:: Returns whether a given object is equal to +self+.
7059 * {#>}[#method-i-3E]:: Returns whether +self+ is a proper superset of a given object
7060 * {#>=}[#method-i-3E-3D]:: Returns whether +self+ is a proper superset of a given object.
7062 * ==== Methods for Fetching
7064 * #[]:: Returns the value associated with a given key.
7065 * #assoc:: Returns a 2-element array containing a given key and its value.
7066 * #dig:: Returns the object in nested objects that is specified
7067 * by a given key and additional arguments.
7068 * #fetch:: Returns the value for a given key.
7069 * #fetch_values:: Returns array containing the values associated with given keys.
7070 * #key:: Returns the key for the first-found entry with a given value.
7071 * #keys:: Returns an array containing all keys in +self+.
7072 * #rassoc:: Returns a 2-element array consisting of the key and value
7073 of the first-found entry having a given value.
7074 * #values:: Returns an array containing all values in +self+/
7075 * #values_at:: Returns an array containing values for given keys.
7077 * ==== Methods for Assigning
7079 * #[]=, #store:: Associates a given key with a given value.
7080 * #merge:: Returns the hash formed by merging each given hash into a copy of +self+.
7081 * #merge!, #update:: Merges each given hash into +self+.
7082 * #replace:: Replaces the entire contents of +self+ with the contents of a givan hash.
7084 * ==== Methods for Deleting
7086 * These methods remove entries from +self+:
7088 * #clear:: Removes all entries from +self+.
7089 * #compact!:: Removes all +nil+-valued entries from +self+.
7090 * #delete:: Removes the entry for a given key.
7091 * #delete_if:: Removes entries selected by a given block.
7092 * #filter!, #select!:: Keep only those entries selected by a given block.
7093 * #keep_if:: Keep only those entries selected by a given block.
7094 * #reject!:: Removes entries selected by a given block.
7095 * #shift:: Removes and returns the first entry.
7097 * These methods return a copy of +self+ with some entries removed:
7099 * #compact:: Returns a copy of +self+ with all +nil+-valued entries removed.
7100 * #except:: Returns a copy of +self+ with entries removed for specified keys.
7101 * #filter, #select:: Returns a copy of +self+ with only those entries selected by a given block.
7102 * #reject:: Returns a copy of +self+ with entries removed as specified by a given block.
7103 * #slice:: Returns a hash containing the entries for given keys.
7105 * ==== Methods for Iterating
7106 * #each, #each_pair:: Calls a given block with each key-value pair.
7107 * #each_key:: Calls a given block with each key.
7108 * #each_value:: Calls a given block with each value.
7110 * ==== Methods for Converting
7112 * #inspect, #to_s:: Returns a new String containing the hash entries.
7113 * #to_a:: Returns a new array of 2-element arrays;
7114 * each nested array contains a key-value pair from +self+.
7115 * #to_h:: Returns +self+ if a \Hash;
7116 * if a subclass of \Hash, returns a \Hash containing the entries from +self+.
7117 * #to_hash:: Returns +self+.
7118 * #to_proc:: Returns a proc that maps a given key to its value.
7120 * ==== Methods for Transforming Keys and Values
7122 * #transform_keys:: Returns a copy of +self+ with modified keys.
7123 * #transform_keys!:: Modifies keys in +self+
7124 * #transform_values:: Returns a copy of +self+ with modified values.
7125 * #transform_values!:: Modifies values in +self+.
7127 * ==== Other Methods
7128 * #flatten:: Returns an array that is a 1-dimensional flattening of +self+.
7129 * #invert:: Returns a hash with the each key-value pair inverted.
7133 void
7134 Init_Hash(void)
7136 id_hash = rb_intern_const("hash");
7137 id_default = rb_intern_const("default");
7138 id_flatten_bang = rb_intern_const("flatten!");
7139 id_hash_iter_lev = rb_make_internal_id();
7141 rb_cHash = rb_define_class("Hash", rb_cObject);
7143 rb_include_module(rb_cHash, rb_mEnumerable);
7145 rb_define_alloc_func(rb_cHash, empty_hash_alloc);
7146 rb_define_singleton_method(rb_cHash, "[]", rb_hash_s_create, -1);
7147 rb_define_singleton_method(rb_cHash, "try_convert", rb_hash_s_try_convert, 1);
7148 rb_define_method(rb_cHash, "initialize", rb_hash_initialize, -1);
7149 rb_define_method(rb_cHash, "initialize_copy", rb_hash_replace, 1);
7150 rb_define_method(rb_cHash, "rehash", rb_hash_rehash, 0);
7152 rb_define_method(rb_cHash, "to_hash", rb_hash_to_hash, 0);
7153 rb_define_method(rb_cHash, "to_h", rb_hash_to_h, 0);
7154 rb_define_method(rb_cHash, "to_a", rb_hash_to_a, 0);
7155 rb_define_method(rb_cHash, "inspect", rb_hash_inspect, 0);
7156 rb_define_alias(rb_cHash, "to_s", "inspect");
7157 rb_define_method(rb_cHash, "to_proc", rb_hash_to_proc, 0);
7159 rb_define_method(rb_cHash, "==", rb_hash_equal, 1);
7160 rb_define_method(rb_cHash, "[]", rb_hash_aref, 1);
7161 rb_define_method(rb_cHash, "hash", rb_hash_hash, 0);
7162 rb_define_method(rb_cHash, "eql?", rb_hash_eql, 1);
7163 rb_define_method(rb_cHash, "fetch", rb_hash_fetch_m, -1);
7164 rb_define_method(rb_cHash, "[]=", rb_hash_aset, 2);
7165 rb_define_method(rb_cHash, "store", rb_hash_aset, 2);
7166 rb_define_method(rb_cHash, "default", rb_hash_default, -1);
7167 rb_define_method(rb_cHash, "default=", rb_hash_set_default, 1);
7168 rb_define_method(rb_cHash, "default_proc", rb_hash_default_proc, 0);
7169 rb_define_method(rb_cHash, "default_proc=", rb_hash_set_default_proc, 1);
7170 rb_define_method(rb_cHash, "key", rb_hash_key, 1);
7171 rb_define_method(rb_cHash, "size", rb_hash_size, 0);
7172 rb_define_method(rb_cHash, "length", rb_hash_size, 0);
7173 rb_define_method(rb_cHash, "empty?", rb_hash_empty_p, 0);
7175 rb_define_method(rb_cHash, "each_value", rb_hash_each_value, 0);
7176 rb_define_method(rb_cHash, "each_key", rb_hash_each_key, 0);
7177 rb_define_method(rb_cHash, "each_pair", rb_hash_each_pair, 0);
7178 rb_define_method(rb_cHash, "each", rb_hash_each_pair, 0);
7180 rb_define_method(rb_cHash, "transform_keys", rb_hash_transform_keys, -1);
7181 rb_define_method(rb_cHash, "transform_keys!", rb_hash_transform_keys_bang, -1);
7182 rb_define_method(rb_cHash, "transform_values", rb_hash_transform_values, 0);
7183 rb_define_method(rb_cHash, "transform_values!", rb_hash_transform_values_bang, 0);
7185 rb_define_method(rb_cHash, "keys", rb_hash_keys, 0);
7186 rb_define_method(rb_cHash, "values", rb_hash_values, 0);
7187 rb_define_method(rb_cHash, "values_at", rb_hash_values_at, -1);
7188 rb_define_method(rb_cHash, "fetch_values", rb_hash_fetch_values, -1);
7190 rb_define_method(rb_cHash, "shift", rb_hash_shift, 0);
7191 rb_define_method(rb_cHash, "delete", rb_hash_delete_m, 1);
7192 rb_define_method(rb_cHash, "delete_if", rb_hash_delete_if, 0);
7193 rb_define_method(rb_cHash, "keep_if", rb_hash_keep_if, 0);
7194 rb_define_method(rb_cHash, "select", rb_hash_select, 0);
7195 rb_define_method(rb_cHash, "select!", rb_hash_select_bang, 0);
7196 rb_define_method(rb_cHash, "filter", rb_hash_select, 0);
7197 rb_define_method(rb_cHash, "filter!", rb_hash_select_bang, 0);
7198 rb_define_method(rb_cHash, "reject", rb_hash_reject, 0);
7199 rb_define_method(rb_cHash, "reject!", rb_hash_reject_bang, 0);
7200 rb_define_method(rb_cHash, "slice", rb_hash_slice, -1);
7201 rb_define_method(rb_cHash, "except", rb_hash_except, -1);
7202 rb_define_method(rb_cHash, "clear", rb_hash_clear, 0);
7203 rb_define_method(rb_cHash, "invert", rb_hash_invert, 0);
7204 rb_define_method(rb_cHash, "update", rb_hash_update, -1);
7205 rb_define_method(rb_cHash, "replace", rb_hash_replace, 1);
7206 rb_define_method(rb_cHash, "merge!", rb_hash_update, -1);
7207 rb_define_method(rb_cHash, "merge", rb_hash_merge, -1);
7208 rb_define_method(rb_cHash, "assoc", rb_hash_assoc, 1);
7209 rb_define_method(rb_cHash, "rassoc", rb_hash_rassoc, 1);
7210 rb_define_method(rb_cHash, "flatten", rb_hash_flatten, -1);
7211 rb_define_method(rb_cHash, "compact", rb_hash_compact, 0);
7212 rb_define_method(rb_cHash, "compact!", rb_hash_compact_bang, 0);
7214 rb_define_method(rb_cHash, "include?", rb_hash_has_key, 1);
7215 rb_define_method(rb_cHash, "member?", rb_hash_has_key, 1);
7216 rb_define_method(rb_cHash, "has_key?", rb_hash_has_key, 1);
7217 rb_define_method(rb_cHash, "has_value?", rb_hash_has_value, 1);
7218 rb_define_method(rb_cHash, "key?", rb_hash_has_key, 1);
7219 rb_define_method(rb_cHash, "value?", rb_hash_has_value, 1);
7221 rb_define_method(rb_cHash, "compare_by_identity", rb_hash_compare_by_id, 0);
7222 rb_define_method(rb_cHash, "compare_by_identity?", rb_hash_compare_by_id_p, 0);
7224 rb_define_method(rb_cHash, "any?", rb_hash_any_p, -1);
7225 rb_define_method(rb_cHash, "dig", rb_hash_dig, -1);
7227 rb_define_method(rb_cHash, "<=", rb_hash_le, 1);
7228 rb_define_method(rb_cHash, "<", rb_hash_lt, 1);
7229 rb_define_method(rb_cHash, ">=", rb_hash_ge, 1);
7230 rb_define_method(rb_cHash, ">", rb_hash_gt, 1);
7232 rb_define_method(rb_cHash, "deconstruct_keys", rb_hash_deconstruct_keys, 1);
7234 rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash?", rb_hash_s_ruby2_keywords_hash_p, 1);
7235 rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash", rb_hash_s_ruby2_keywords_hash, 1);
7237 /* Document-class: ENV
7239 * ENV is a hash-like accessor for environment variables.
7241 * === Interaction with the Operating System
7243 * The ENV object interacts with the operating system's environment variables:
7245 * - When you get the value for a name in ENV, the value is retrieved from among the current environment variables.
7246 * - When you create or set a name-value pair in ENV, the name and value are immediately set in the environment variables.
7247 * - When you delete a name-value pair in ENV, it is immediately deleted from the environment variables.
7249 * === Names and Values
7251 * Generally, a name or value is a String.
7253 * ==== Valid Names and Values
7255 * Each name or value must be one of the following:
7257 * - A String.
7258 * - An object that responds to \#to_str by returning a String, in which case that String will be used as the name or value.
7260 * ==== Invalid Names and Values
7262 * A new name:
7264 * - May not be the empty string:
7265 * ENV[''] = '0'
7266 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv())
7268 * - May not contain character <code>"="</code>:
7269 * ENV['='] = '0'
7270 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv(=))
7272 * A new name or value:
7274 * - May not be a non-String that does not respond to \#to_str:
7276 * ENV['foo'] = Object.new
7277 * # Raises TypeError (no implicit conversion of Object into String)
7278 * ENV[Object.new] = '0'
7279 * # Raises TypeError (no implicit conversion of Object into String)
7281 * - May not contain the NUL character <code>"\0"</code>:
7283 * ENV['foo'] = "\0"
7284 * # Raises ArgumentError (bad environment variable value: contains null byte)
7285 * ENV["\0"] == '0'
7286 * # Raises ArgumentError (bad environment variable name: contains null byte)
7288 * - May not have an ASCII-incompatible encoding such as UTF-16LE or ISO-2022-JP:
7290 * ENV['foo'] = '0'.force_encoding(Encoding::ISO_2022_JP)
7291 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7292 * ENV["foo".force_encoding(Encoding::ISO_2022_JP)] = '0'
7293 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7295 * === About Ordering
7297 * ENV enumerates its name/value pairs in the order found
7298 * in the operating system's environment variables.
7299 * Therefore the ordering of ENV content is OS-dependent, and may be indeterminate.
7301 * This will be seen in:
7302 * - A Hash returned by an ENV method.
7303 * - An Enumerator returned by an ENV method.
7304 * - An Array returned by ENV.keys, ENV.values, or ENV.to_a.
7305 * - The String returned by ENV.inspect.
7306 * - The Array returned by ENV.shift.
7307 * - The name returned by ENV.key.
7309 * === About the Examples
7310 * Some methods in ENV return ENV itself. Typically, there are many environment variables.
7311 * It's not useful to display a large ENV in the examples here,
7312 * so most example snippets begin by resetting the contents of ENV:
7313 * - ENV.replace replaces ENV with a new collection of entries.
7314 * - ENV.clear empties ENV.
7316 * == What's Here
7318 * First, what's elsewhere. \Class \ENV:
7320 * - Inherits from {class Object}[Object.html#class-Object-label-What-27s+Here].
7321 * - Extends {module Enumerable}[Enumerable.html#module-Enumerable-label-What-27s+Here],
7323 * Here, class \ENV provides methods that are useful for:
7325 * - {Querying}[#class-ENV-label-Methods+for+Querying]
7326 * - {Assigning}[#class-ENV-label-Methods+for+Assigning]
7327 * - {Deleting}[#class-ENV-label-Methods+for+Deleting]
7328 * - {Iterating}[#class-ENV-label-Methods+for+Iterating]
7329 * - {Converting}[#class-ENV-label-Methods+for+Converting]
7330 * - {And more ....}[#class-ENV-label-More+Methods]
7332 * === Methods for Querying
7334 * - ::[]:: Returns the value for the given environment variable name if it exists:
7335 * - ::empty?:: Returns whether \ENV is empty.
7336 * - ::has_value?, ::value?:: Returns whether the given value is in \ENV.
7337 * - ::include?, ::has_key?, ::key?, ::member?:: Returns whether the given name
7338 is in \ENV.
7339 * - ::key:: Returns the name of the first entry with the given value.
7340 * - ::size, ::length:: Returns the number of entries.
7341 * - ::value?:: Returns whether any entry has the given value.
7343 * === Methods for Assigning
7345 * - ::[]=, ::store:: Creates, updates, or deletes the named environment variable.
7346 * - ::clear:: Removes every environment variable; returns \ENV:
7347 * - ::update, ::merge!:: Adds to \ENV each key/value pair in the given hash.
7348 * - ::replace:: Replaces the entire content of the \ENV
7349 * with the name/value pairs in the given hash.
7351 * === Methods for Deleting
7353 * - ::delete:: Deletes the named environment variable name if it exists.
7354 * - ::delete_if:: Deletes entries selected by the block.
7355 * - ::keep_if:: Deletes entries not selected by the block.
7356 * - ::reject!:: Similar to #delete_if, but returns +nil+ if no change was made.
7357 * - ::select!, ::filter!:: Deletes entries selected by the block.
7358 * - ::shift:: Removes and returns the first entry.
7360 * === Methods for Iterating
7362 * - ::each, ::each_pair:: Calls the block with each name/value pair.
7363 * - ::each_key:: Calls the block with each name.
7364 * - ::each_value:: Calls the block with each value.
7366 * === Methods for Converting
7368 * - ::assoc:: Returns a 2-element array containing the name and value
7369 * of the named environment variable if it exists:
7370 * - ::clone:: Returns \ENV (and issues a warning).
7371 * - ::except:: Returns a hash of all name/value pairs except those given.
7372 * - ::fetch:: Returns the value for the given name.
7373 * - ::inspect:: Returns the contents of \ENV as a string.
7374 * - ::invert:: Returns a hash whose keys are the ENV values,
7375 and whose values are the corresponding ENV names.
7376 * - ::keys:: Returns an array of all names.
7377 * - ::rassoc:: Returns the name and value of the first found entry
7378 * that has the given value.
7379 * - ::reject:: Returns a hash of those entries not rejected by the block.
7380 * - ::select, ::filter:: Returns a hash of name/value pairs selected by the block.
7381 * - ::slice:: Returns a hash of the given names and their corresponding values.
7382 * - ::to_a:: Returns the entries as an array of 2-element Arrays.
7383 * - ::to_h:: Returns a hash of entries selected by the block.
7384 * - ::to_hash:: Returns a hash of all entries.
7385 * - ::to_s:: Returns the string <tt>'ENV'</tt>.
7386 * - ::values:: Returns all values as an array.
7387 * - ::values_at:: Returns an array of the values for the given name.
7389 * === More Methods
7391 * - ::dup:: Raises an exception.
7392 * - ::freeze:: Raises an exception.
7393 * - ::rehash:: Returns +nil+, without modifying \ENV.
7398 * Hack to get RDoc to regard ENV as a class:
7399 * envtbl = rb_define_class("ENV", rb_cObject);
7401 origenviron = environ;
7402 envtbl = TypedData_Wrap_Struct(rb_cObject, &env_data_type, NULL);
7403 rb_extend_object(envtbl, rb_mEnumerable);
7404 FL_SET_RAW(envtbl, RUBY_FL_SHAREABLE);
7407 rb_define_singleton_method(envtbl, "[]", rb_f_getenv, 1);
7408 rb_define_singleton_method(envtbl, "fetch", env_fetch, -1);
7409 rb_define_singleton_method(envtbl, "[]=", env_aset_m, 2);
7410 rb_define_singleton_method(envtbl, "store", env_aset_m, 2);
7411 rb_define_singleton_method(envtbl, "each", env_each_pair, 0);
7412 rb_define_singleton_method(envtbl, "each_pair", env_each_pair, 0);
7413 rb_define_singleton_method(envtbl, "each_key", env_each_key, 0);
7414 rb_define_singleton_method(envtbl, "each_value", env_each_value, 0);
7415 rb_define_singleton_method(envtbl, "delete", env_delete_m, 1);
7416 rb_define_singleton_method(envtbl, "delete_if", env_delete_if, 0);
7417 rb_define_singleton_method(envtbl, "keep_if", env_keep_if, 0);
7418 rb_define_singleton_method(envtbl, "slice", env_slice, -1);
7419 rb_define_singleton_method(envtbl, "except", env_except, -1);
7420 rb_define_singleton_method(envtbl, "clear", env_clear, 0);
7421 rb_define_singleton_method(envtbl, "reject", env_reject, 0);
7422 rb_define_singleton_method(envtbl, "reject!", env_reject_bang, 0);
7423 rb_define_singleton_method(envtbl, "select", env_select, 0);
7424 rb_define_singleton_method(envtbl, "select!", env_select_bang, 0);
7425 rb_define_singleton_method(envtbl, "filter", env_select, 0);
7426 rb_define_singleton_method(envtbl, "filter!", env_select_bang, 0);
7427 rb_define_singleton_method(envtbl, "shift", env_shift, 0);
7428 rb_define_singleton_method(envtbl, "freeze", env_freeze, 0);
7429 rb_define_singleton_method(envtbl, "invert", env_invert, 0);
7430 rb_define_singleton_method(envtbl, "replace", env_replace, 1);
7431 rb_define_singleton_method(envtbl, "update", env_update, 1);
7432 rb_define_singleton_method(envtbl, "merge!", env_update, 1);
7433 rb_define_singleton_method(envtbl, "inspect", env_inspect, 0);
7434 rb_define_singleton_method(envtbl, "rehash", env_none, 0);
7435 rb_define_singleton_method(envtbl, "to_a", env_to_a, 0);
7436 rb_define_singleton_method(envtbl, "to_s", env_to_s, 0);
7437 rb_define_singleton_method(envtbl, "key", env_key, 1);
7438 rb_define_singleton_method(envtbl, "size", env_size, 0);
7439 rb_define_singleton_method(envtbl, "length", env_size, 0);
7440 rb_define_singleton_method(envtbl, "empty?", env_empty_p, 0);
7441 rb_define_singleton_method(envtbl, "keys", env_f_keys, 0);
7442 rb_define_singleton_method(envtbl, "values", env_f_values, 0);
7443 rb_define_singleton_method(envtbl, "values_at", env_values_at, -1);
7444 rb_define_singleton_method(envtbl, "include?", env_has_key, 1);
7445 rb_define_singleton_method(envtbl, "member?", env_has_key, 1);
7446 rb_define_singleton_method(envtbl, "has_key?", env_has_key, 1);
7447 rb_define_singleton_method(envtbl, "has_value?", env_has_value, 1);
7448 rb_define_singleton_method(envtbl, "key?", env_has_key, 1);
7449 rb_define_singleton_method(envtbl, "value?", env_has_value, 1);
7450 rb_define_singleton_method(envtbl, "to_hash", env_f_to_hash, 0);
7451 rb_define_singleton_method(envtbl, "to_h", env_to_h, 0);
7452 rb_define_singleton_method(envtbl, "assoc", env_assoc, 1);
7453 rb_define_singleton_method(envtbl, "rassoc", env_rassoc, 1);
7454 rb_define_singleton_method(envtbl, "clone", env_clone, -1);
7455 rb_define_singleton_method(envtbl, "dup", env_dup, 0);
7457 VALUE envtbl_class = rb_singleton_class(envtbl);
7458 rb_undef_method(envtbl_class, "initialize");
7459 rb_undef_method(envtbl_class, "initialize_clone");
7460 rb_undef_method(envtbl_class, "initialize_copy");
7461 rb_undef_method(envtbl_class, "initialize_dup");
7464 * ENV is a Hash-like accessor for environment variables.
7466 * See ENV (the class) for more details.
7468 rb_define_global_const("ENV", envtbl);
7470 /* for callcc */
7471 ruby_register_rollback_func_for_ensure(hash_foreach_ensure, hash_foreach_ensure_rollback);
7473 HASH_ASSERT(sizeof(ar_hint_t) * RHASH_AR_TABLE_MAX_SIZE == sizeof(VALUE));