[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / hash.c
blobf34f64065b67d1d63d62e27b0349a726a8ca07ec
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/basic_operators.h"
32 #include "internal/class.h"
33 #include "internal/cont.h"
34 #include "internal/error.h"
35 #include "internal/hash.h"
36 #include "internal/object.h"
37 #include "internal/proc.h"
38 #include "internal/st.h"
39 #include "internal/symbol.h"
40 #include "internal/thread.h"
41 #include "internal/time.h"
42 #include "internal/vm.h"
43 #include "probes.h"
44 #include "ruby/st.h"
45 #include "ruby/util.h"
46 #include "ruby_assert.h"
47 #include "symbol.h"
48 #include "ruby/thread_native.h"
49 #include "ruby/ractor.h"
50 #include "vm_sync.h"
52 /* Flags of RHash
54 * 1: RHASH_PASS_AS_KEYWORDS
55 * The hash is flagged as Ruby 2 keywords hash.
56 * 2: RHASH_PROC_DEFAULT
57 * The hash has a default proc (rather than a default value).
58 * 3: RHASH_ST_TABLE_FLAG
59 * The hash uses a ST table (rather than an AR table).
60 * 4-7: RHASH_AR_TABLE_SIZE_MASK
61 * The size of the AR table.
62 * 8-11: RHASH_AR_TABLE_BOUND_MASK
63 * The bounds of the AR table.
64 * 13-19: RHASH_LEV_MASK
65 * The iterational level of the hash. Used to prevent modifications
66 * to the hash during interation.
69 #ifndef HASH_DEBUG
70 #define HASH_DEBUG 0
71 #endif
73 #if HASH_DEBUG
74 #include "internal/gc.h"
75 #endif
77 #define SET_DEFAULT(hash, ifnone) ( \
78 FL_UNSET_RAW(hash, RHASH_PROC_DEFAULT), \
79 RHASH_SET_IFNONE(hash, ifnone))
81 #define SET_PROC_DEFAULT(hash, proc) set_proc_default(hash, proc)
83 #define COPY_DEFAULT(hash, hash2) copy_default(RHASH(hash), RHASH(hash2))
85 static inline void
86 copy_default(struct RHash *hash, const struct RHash *hash2)
88 hash->basic.flags &= ~RHASH_PROC_DEFAULT;
89 hash->basic.flags |= hash2->basic.flags & RHASH_PROC_DEFAULT;
90 RHASH_SET_IFNONE(hash, RHASH_IFNONE((VALUE)hash2));
93 static VALUE rb_hash_s_try_convert(VALUE, VALUE);
96 * Hash WB strategy:
97 * 1. Check mutate st_* functions
98 * * st_insert()
99 * * st_insert2()
100 * * st_update()
101 * * st_add_direct()
102 * 2. Insert WBs
105 VALUE
106 rb_hash_freeze(VALUE hash)
108 return rb_obj_freeze(hash);
111 VALUE rb_cHash;
113 static VALUE envtbl;
114 static ID id_hash, id_flatten_bang;
115 static ID id_hash_iter_lev;
117 #define id_default idDefault
119 VALUE
120 rb_hash_set_ifnone(VALUE hash, VALUE ifnone)
122 RB_OBJ_WRITE(hash, (&RHASH(hash)->ifnone), ifnone);
123 return hash;
127 rb_any_cmp(VALUE a, VALUE b)
129 if (a == b) return 0;
130 if (RB_TYPE_P(a, T_STRING) && RBASIC(a)->klass == rb_cString &&
131 RB_TYPE_P(b, T_STRING) && RBASIC(b)->klass == rb_cString) {
132 return rb_str_hash_cmp(a, b);
134 if (UNDEF_P(a) || UNDEF_P(b)) return -1;
135 if (SYMBOL_P(a) && SYMBOL_P(b)) {
136 return a != b;
139 return !rb_eql(a, b);
142 static VALUE
143 hash_recursive(VALUE obj, VALUE arg, int recurse)
145 if (recurse) return INT2FIX(0);
146 return rb_funcallv(obj, id_hash, 0, 0);
149 static long rb_objid_hash(st_index_t index);
151 static st_index_t
152 dbl_to_index(double d)
154 union {double d; st_index_t i;} u;
155 u.d = d;
156 return u.i;
159 long
160 rb_dbl_long_hash(double d)
162 /* normalize -0.0 to 0.0 */
163 if (d == 0.0) d = 0.0;
164 #if SIZEOF_INT == SIZEOF_VOIDP
165 return rb_memhash(&d, sizeof(d));
166 #else
167 return rb_objid_hash(dbl_to_index(d));
168 #endif
171 static inline long
172 any_hash(VALUE a, st_index_t (*other_func)(VALUE))
174 VALUE hval;
175 st_index_t hnum;
177 switch (TYPE(a)) {
178 case T_SYMBOL:
179 if (STATIC_SYM_P(a)) {
180 hnum = a >> (RUBY_SPECIAL_SHIFT + ID_SCOPE_SHIFT);
181 hnum = rb_hash_start(hnum);
183 else {
184 hnum = RSYMBOL(a)->hashval;
186 break;
187 case T_FIXNUM:
188 case T_TRUE:
189 case T_FALSE:
190 case T_NIL:
191 hnum = rb_objid_hash((st_index_t)a);
192 break;
193 case T_STRING:
194 hnum = rb_str_hash(a);
195 break;
196 case T_BIGNUM:
197 hval = rb_big_hash(a);
198 hnum = FIX2LONG(hval);
199 break;
200 case T_FLOAT: /* prevent pathological behavior: [Bug #10761] */
201 hnum = rb_dbl_long_hash(rb_float_value(a));
202 break;
203 default:
204 hnum = other_func(a);
206 if ((SIGNED_VALUE)hnum > 0)
207 hnum &= FIXNUM_MAX;
208 else
209 hnum |= FIXNUM_MIN;
210 return (long)hnum;
213 VALUE rb_obj_hash(VALUE obj);
214 VALUE rb_vm_call0(rb_execution_context_t *ec, VALUE recv, ID id, int argc, const VALUE *argv, const rb_callable_method_entry_t *cme, int kw_splat);
216 static st_index_t
217 obj_any_hash(VALUE obj)
219 VALUE hval = Qundef;
220 VALUE klass = CLASS_OF(obj);
221 if (klass) {
222 const rb_callable_method_entry_t *cme = rb_callable_method_entry(klass, id_hash);
223 if (cme && METHOD_ENTRY_BASIC(cme)) {
224 // Optimize away the frame push overhead if it's the default Kernel#hash
225 if (cme->def->type == VM_METHOD_TYPE_CFUNC && cme->def->body.cfunc.func == (rb_cfunc_t)rb_obj_hash) {
226 hval = rb_obj_hash(obj);
228 else if (RBASIC_CLASS(cme->defined_class) == rb_mKernel) {
229 hval = rb_vm_call0(GET_EC(), obj, id_hash, 0, 0, cme, 0);
234 if (UNDEF_P(hval)) {
235 hval = rb_exec_recursive_outer_mid(hash_recursive, obj, 0, id_hash);
238 while (!FIXNUM_P(hval)) {
239 if (RB_TYPE_P(hval, T_BIGNUM)) {
240 int sign;
241 unsigned long ul;
242 sign = rb_integer_pack(hval, &ul, 1, sizeof(ul), 0,
243 INTEGER_PACK_NATIVE_BYTE_ORDER);
244 if (sign < 0) {
245 hval = LONG2FIX(ul | FIXNUM_MIN);
247 else {
248 hval = LONG2FIX(ul & FIXNUM_MAX);
251 hval = rb_to_int(hval);
254 return FIX2LONG(hval);
257 st_index_t
258 rb_any_hash(VALUE a)
260 return any_hash(a, obj_any_hash);
263 VALUE
264 rb_hash(VALUE obj)
266 return LONG2FIX(any_hash(obj, obj_any_hash));
270 /* Here is a hash function for 64-bit key. It is about 5 times faster
271 (2 times faster when uint128 type is absent) on Haswell than
272 tailored Spooky or City hash function can be. */
274 /* Here we two primes with random bit generation. */
275 static const uint64_t prime1 = ((uint64_t)0x2e0bb864 << 32) | 0xe9ea7df5;
276 static const uint32_t prime2 = 0x830fcab9;
279 static inline uint64_t
280 mult_and_mix(uint64_t m1, uint64_t m2)
282 #if defined HAVE_UINT128_T
283 uint128_t r = (uint128_t) m1 * (uint128_t) m2;
284 return (uint64_t) (r >> 64) ^ (uint64_t) r;
285 #else
286 uint64_t hm1 = m1 >> 32, hm2 = m2 >> 32;
287 uint64_t lm1 = m1, lm2 = m2;
288 uint64_t v64_128 = hm1 * hm2;
289 uint64_t v32_96 = hm1 * lm2 + lm1 * hm2;
290 uint64_t v1_32 = lm1 * lm2;
292 return (v64_128 + (v32_96 >> 32)) ^ ((v32_96 << 32) + v1_32);
293 #endif
296 static inline uint64_t
297 key64_hash(uint64_t key, uint32_t seed)
299 return mult_and_mix(key + seed, prime1);
302 /* Should cast down the result for each purpose */
303 #define st_index_hash(index) key64_hash(rb_hash_start(index), prime2)
305 static long
306 rb_objid_hash(st_index_t index)
308 return (long)st_index_hash(index);
311 static st_index_t
312 objid_hash(VALUE obj)
314 VALUE object_id = rb_obj_id(obj);
315 if (!FIXNUM_P(object_id))
316 object_id = rb_big_hash(object_id);
318 #if SIZEOF_LONG == SIZEOF_VOIDP
319 return (st_index_t)st_index_hash((st_index_t)NUM2LONG(object_id));
320 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
321 return (st_index_t)st_index_hash((st_index_t)NUM2LL(object_id));
322 #endif
326 * call-seq:
327 * obj.hash -> integer
329 * Generates an Integer hash value for this object. This function must have the
330 * property that <code>a.eql?(b)</code> implies <code>a.hash == b.hash</code>.
332 * The hash value is used along with #eql? by the Hash class to determine if
333 * two objects reference the same hash key. Any hash value that exceeds the
334 * capacity of an Integer will be truncated before being used.
336 * The hash value for an object may not be identical across invocations or
337 * implementations of Ruby. If you need a stable identifier across Ruby
338 * invocations and implementations you will need to generate one with a custom
339 * method.
341 * Certain core classes such as Integer use built-in hash calculations and
342 * do not call the #hash method when used as a hash key.
344 * When implementing your own #hash based on multiple values, the best
345 * practice is to combine the class and any values using the hash code of an
346 * array:
348 * For example:
350 * def hash
351 * [self.class, a, b, c].hash
352 * end
354 * The reason for this is that the Array#hash method already has logic for
355 * safely and efficiently combining multiple hash values.
357 * \private
360 VALUE
361 rb_obj_hash(VALUE obj)
363 long hnum = any_hash(obj, objid_hash);
364 return ST2FIX(hnum);
367 static const struct st_hash_type objhash = {
368 rb_any_cmp,
369 rb_any_hash,
372 #define rb_ident_cmp st_numcmp
374 static st_index_t
375 rb_ident_hash(st_data_t n)
377 #ifdef USE_FLONUM /* RUBY */
379 * - flonum (on 64-bit) is pathologically bad, mix the actual
380 * float value in, but do not use the float value as-is since
381 * many integers get interpreted as 2.0 or -2.0 [Bug #10761]
383 if (FLONUM_P(n)) {
384 n ^= dbl_to_index(rb_float_value(n));
386 #endif
388 return (st_index_t)st_index_hash((st_index_t)n);
391 #define identhash rb_hashtype_ident
392 const struct st_hash_type rb_hashtype_ident = {
393 rb_ident_cmp,
394 rb_ident_hash,
397 #define RHASH_IDENTHASH_P(hash) (RHASH_TYPE(hash) == &identhash)
398 #define RHASH_STRING_KEY_P(hash, key) (!RHASH_IDENTHASH_P(hash) && (rb_obj_class(key) == rb_cString))
400 typedef st_index_t st_hash_t;
403 * RHASH_AR_TABLE_P(h):
404 * RHASH_AR_TABLE points to ar_table.
406 * !RHASH_AR_TABLE_P(h):
407 * RHASH_ST_TABLE points st_table.
410 #define RHASH_AR_TABLE_MAX_BOUND RHASH_AR_TABLE_MAX_SIZE
412 #define RHASH_AR_TABLE_REF(hash, n) (&RHASH_AR_TABLE(hash)->pairs[n])
413 #define RHASH_AR_CLEARED_HINT 0xff
415 static inline st_hash_t
416 ar_do_hash(st_data_t key)
418 return (st_hash_t)rb_any_hash(key);
421 static inline ar_hint_t
422 ar_do_hash_hint(st_hash_t hash_value)
424 return (ar_hint_t)hash_value;
427 static inline ar_hint_t
428 ar_hint(VALUE hash, unsigned int index)
430 return RHASH_AR_TABLE(hash)->ar_hint.ary[index];
433 static inline void
434 ar_hint_set_hint(VALUE hash, unsigned int index, ar_hint_t hint)
436 RHASH_AR_TABLE(hash)->ar_hint.ary[index] = hint;
439 static inline void
440 ar_hint_set(VALUE hash, unsigned int index, st_hash_t hash_value)
442 ar_hint_set_hint(hash, index, ar_do_hash_hint(hash_value));
445 static inline void
446 ar_clear_entry(VALUE hash, unsigned int index)
448 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
449 pair->key = Qundef;
450 ar_hint_set_hint(hash, index, RHASH_AR_CLEARED_HINT);
453 static inline int
454 ar_cleared_entry(VALUE hash, unsigned int index)
456 if (ar_hint(hash, index) == RHASH_AR_CLEARED_HINT) {
457 /* RHASH_AR_CLEARED_HINT is only a hint, not mean cleared entry,
458 * so you need to check key == Qundef
460 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
461 return UNDEF_P(pair->key);
463 else {
464 return FALSE;
468 static inline void
469 ar_set_entry(VALUE hash, unsigned int index, st_data_t key, st_data_t val, st_hash_t hash_value)
471 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
472 pair->key = key;
473 pair->val = val;
474 ar_hint_set(hash, index, hash_value);
477 #define RHASH_AR_TABLE_SIZE(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
478 RHASH_AR_TABLE_SIZE_RAW(h))
480 #define RHASH_AR_TABLE_BOUND_RAW(h) \
481 ((unsigned int)((RBASIC(h)->flags >> RHASH_AR_TABLE_BOUND_SHIFT) & \
482 (RHASH_AR_TABLE_BOUND_MASK >> RHASH_AR_TABLE_BOUND_SHIFT)))
484 #define RHASH_ST_TABLE_SET(h, s) rb_hash_st_table_set(h, s)
485 #define RHASH_TYPE(hash) (RHASH_AR_TABLE_P(hash) ? &objhash : RHASH_ST_TABLE(hash)->type)
487 #define HASH_ASSERT(expr) RUBY_ASSERT_MESG_WHEN(HASH_DEBUG, expr, #expr)
489 static inline unsigned int
490 RHASH_AR_TABLE_BOUND(VALUE h)
492 HASH_ASSERT(RHASH_AR_TABLE_P(h));
493 const unsigned int bound = RHASH_AR_TABLE_BOUND_RAW(h);
494 HASH_ASSERT(bound <= RHASH_AR_TABLE_MAX_SIZE);
495 return bound;
498 #if HASH_DEBUG
499 #define hash_verify(hash) hash_verify_(hash, __FILE__, __LINE__)
501 void
502 rb_hash_dump(VALUE hash)
504 rb_obj_info_dump(hash);
506 if (RHASH_AR_TABLE_P(hash)) {
507 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
509 fprintf(stderr, " size:%u bound:%u\n",
510 RHASH_AR_TABLE_SIZE(hash), bound);
512 for (i=0; i<bound; i++) {
513 st_data_t k, v;
515 if (!ar_cleared_entry(hash, i)) {
516 char b1[0x100], b2[0x100];
517 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
518 k = pair->key;
519 v = pair->val;
520 fprintf(stderr, " %d key:%s val:%s hint:%02x\n", i,
521 rb_raw_obj_info(b1, 0x100, k),
522 rb_raw_obj_info(b2, 0x100, v),
523 ar_hint(hash, i));
525 else {
526 fprintf(stderr, " %d empty\n", i);
532 static VALUE
533 hash_verify_(VALUE hash, const char *file, int line)
535 HASH_ASSERT(RB_TYPE_P(hash, T_HASH));
537 if (RHASH_AR_TABLE_P(hash)) {
538 unsigned i, n = 0, bound = RHASH_AR_TABLE_BOUND(hash);
540 for (i=0; i<bound; i++) {
541 st_data_t k, v;
542 if (!ar_cleared_entry(hash, i)) {
543 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
544 k = pair->key;
545 v = pair->val;
546 HASH_ASSERT(!UNDEF_P(k));
547 HASH_ASSERT(!UNDEF_P(v));
548 n++;
551 if (n != RHASH_AR_TABLE_SIZE(hash)) {
552 rb_bug("n:%u, RHASH_AR_TABLE_SIZE:%u", n, RHASH_AR_TABLE_SIZE(hash));
555 else {
556 HASH_ASSERT(RHASH_ST_TABLE(hash) != NULL);
557 HASH_ASSERT(RHASH_AR_TABLE_SIZE_RAW(hash) == 0);
558 HASH_ASSERT(RHASH_AR_TABLE_BOUND_RAW(hash) == 0);
561 return hash;
564 #else
565 #define hash_verify(h) ((void)0)
566 #endif
568 static inline int
569 RHASH_TABLE_EMPTY_P(VALUE hash)
571 return RHASH_SIZE(hash) == 0;
574 #define RHASH_SET_ST_FLAG(h) FL_SET_RAW(h, RHASH_ST_TABLE_FLAG)
575 #define RHASH_UNSET_ST_FLAG(h) FL_UNSET_RAW(h, RHASH_ST_TABLE_FLAG)
577 static void
578 hash_st_table_init(VALUE hash, const struct st_hash_type *type, st_index_t size)
580 st_init_existing_table_with_size(RHASH_ST_TABLE(hash), type, size);
581 RHASH_SET_ST_FLAG(hash);
584 void
585 rb_hash_st_table_set(VALUE hash, st_table *st)
587 HASH_ASSERT(st != NULL);
588 RHASH_SET_ST_FLAG(hash);
590 *RHASH_ST_TABLE(hash) = *st;
593 static inline void
594 RHASH_AR_TABLE_BOUND_SET(VALUE h, st_index_t n)
596 HASH_ASSERT(RHASH_AR_TABLE_P(h));
597 HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_BOUND);
599 RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
600 RBASIC(h)->flags |= n << RHASH_AR_TABLE_BOUND_SHIFT;
603 static inline void
604 RHASH_AR_TABLE_SIZE_SET(VALUE h, st_index_t n)
606 HASH_ASSERT(RHASH_AR_TABLE_P(h));
607 HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_SIZE);
609 RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
610 RBASIC(h)->flags |= n << RHASH_AR_TABLE_SIZE_SHIFT;
613 static inline void
614 HASH_AR_TABLE_SIZE_ADD(VALUE h, st_index_t n)
616 HASH_ASSERT(RHASH_AR_TABLE_P(h));
618 RHASH_AR_TABLE_SIZE_SET(h, RHASH_AR_TABLE_SIZE(h) + n);
620 hash_verify(h);
623 #define RHASH_AR_TABLE_SIZE_INC(h) HASH_AR_TABLE_SIZE_ADD(h, 1)
625 static inline void
626 RHASH_AR_TABLE_SIZE_DEC(VALUE h)
628 HASH_ASSERT(RHASH_AR_TABLE_P(h));
629 int new_size = RHASH_AR_TABLE_SIZE(h) - 1;
631 if (new_size != 0) {
632 RHASH_AR_TABLE_SIZE_SET(h, new_size);
634 else {
635 RHASH_AR_TABLE_SIZE_SET(h, 0);
636 RHASH_AR_TABLE_BOUND_SET(h, 0);
638 hash_verify(h);
641 static inline void
642 RHASH_AR_TABLE_CLEAR(VALUE h)
644 RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
645 RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
647 memset(RHASH_AR_TABLE(h), 0, sizeof(ar_table));
650 NOINLINE(static int ar_equal(VALUE x, VALUE y));
652 static int
653 ar_equal(VALUE x, VALUE y)
655 return rb_any_cmp(x, y) == 0;
658 static unsigned
659 ar_find_entry_hint(VALUE hash, ar_hint_t hint, st_data_t key)
661 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
662 const ar_hint_t *hints = RHASH_AR_TABLE(hash)->ar_hint.ary;
664 /* if table is NULL, then bound also should be 0 */
666 for (i = 0; i < bound; i++) {
667 if (hints[i] == hint) {
668 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
669 if (ar_equal(key, pair->key)) {
670 RB_DEBUG_COUNTER_INC(artable_hint_hit);
671 return i;
673 else {
674 #if 0
675 static int pid;
676 static char fname[256];
677 static FILE *fp;
679 if (pid != getpid()) {
680 snprintf(fname, sizeof(fname), "/tmp/ruby-armiss.%d", pid = getpid());
681 if ((fp = fopen(fname, "w")) == NULL) rb_bug("fopen");
684 st_hash_t h1 = ar_do_hash(key);
685 st_hash_t h2 = ar_do_hash(pair->key);
687 fprintf(fp, "miss: hash_eq:%d hints[%d]:%02x hint:%02x\n"
688 " key :%016lx %s\n"
689 " pair->key:%016lx %s\n",
690 h1 == h2, i, hints[i], hint,
691 h1, rb_obj_info(key), h2, rb_obj_info(pair->key));
692 #endif
693 RB_DEBUG_COUNTER_INC(artable_hint_miss);
697 RB_DEBUG_COUNTER_INC(artable_hint_notfound);
698 return RHASH_AR_TABLE_MAX_BOUND;
701 static unsigned
702 ar_find_entry(VALUE hash, st_hash_t hash_value, st_data_t key)
704 ar_hint_t hint = ar_do_hash_hint(hash_value);
705 return ar_find_entry_hint(hash, hint, key);
708 static inline void
709 hash_ar_free_and_clear_table(VALUE hash)
711 RHASH_AR_TABLE_CLEAR(hash);
713 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
714 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
717 void rb_st_add_direct_with_hash(st_table *tab, st_data_t key, st_data_t value, st_hash_t hash); // st.c
719 enum ar_each_key_type {
720 ar_each_key_copy,
721 ar_each_key_cmp,
722 ar_each_key_insert,
725 static inline int
726 ar_each_key(ar_table *ar, int max, enum ar_each_key_type type, st_data_t *dst_keys, st_table *new_tab, st_hash_t *hashes)
728 for (int i = 0; i < max; i++) {
729 ar_table_pair *pair = &ar->pairs[i];
731 switch (type) {
732 case ar_each_key_copy:
733 dst_keys[i] = pair->key;
734 break;
735 case ar_each_key_cmp:
736 if (dst_keys[i] != pair->key) return 1;
737 break;
738 case ar_each_key_insert:
739 if (UNDEF_P(pair->key)) continue; // deleted entry
740 rb_st_add_direct_with_hash(new_tab, pair->key, pair->val, hashes[i]);
741 break;
745 return 0;
748 static st_table *
749 ar_force_convert_table(VALUE hash, const char *file, int line)
751 if (RHASH_ST_TABLE_P(hash)) {
752 return RHASH_ST_TABLE(hash);
754 else {
755 ar_table *ar = RHASH_AR_TABLE(hash);
756 st_hash_t hashes[RHASH_AR_TABLE_MAX_SIZE];
757 unsigned int bound, size;
759 // prepare hash values
760 do {
761 st_data_t keys[RHASH_AR_TABLE_MAX_SIZE];
762 bound = RHASH_AR_TABLE_BOUND(hash);
763 size = RHASH_AR_TABLE_SIZE(hash);
764 ar_each_key(ar, bound, ar_each_key_copy, keys, NULL, NULL);
766 for (unsigned int i = 0; i < bound; i++) {
767 // do_hash calls #hash method and it can modify hash object
768 hashes[i] = UNDEF_P(keys[i]) ? 0 : ar_do_hash(keys[i]);
771 // check if modified
772 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) return RHASH_ST_TABLE(hash);
773 if (UNLIKELY(RHASH_AR_TABLE_BOUND(hash) != bound)) continue;
774 if (UNLIKELY(ar_each_key(ar, bound, ar_each_key_cmp, keys, NULL, NULL))) continue;
775 } while (0);
777 // make st
778 st_table tab;
779 st_table *new_tab = &tab;
780 st_init_existing_table_with_size(new_tab, &objhash, size);
781 ar_each_key(ar, bound, ar_each_key_insert, NULL, new_tab, hashes);
782 hash_ar_free_and_clear_table(hash);
783 RHASH_ST_TABLE_SET(hash, new_tab);
784 return RHASH_ST_TABLE(hash);
788 static int
789 ar_compact_table(VALUE hash)
791 const unsigned bound = RHASH_AR_TABLE_BOUND(hash);
792 const unsigned size = RHASH_AR_TABLE_SIZE(hash);
794 if (size == bound) {
795 return size;
797 else {
798 unsigned i, j=0;
799 ar_table_pair *pairs = RHASH_AR_TABLE(hash)->pairs;
801 for (i=0; i<bound; i++) {
802 if (ar_cleared_entry(hash, i)) {
803 if (j <= i) j = i+1;
804 for (; j<bound; j++) {
805 if (!ar_cleared_entry(hash, j)) {
806 pairs[i] = pairs[j];
807 ar_hint_set_hint(hash, i, (st_hash_t)ar_hint(hash, j));
808 ar_clear_entry(hash, j);
809 j++;
810 goto found;
813 /* non-empty is not found */
814 goto done;
815 found:;
818 done:
819 HASH_ASSERT(i<=bound);
821 RHASH_AR_TABLE_BOUND_SET(hash, size);
822 hash_verify(hash);
823 return size;
827 static int
828 ar_add_direct_with_hash(VALUE hash, st_data_t key, st_data_t val, st_hash_t hash_value)
830 unsigned bin = RHASH_AR_TABLE_BOUND(hash);
832 if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
833 return 1;
835 else {
836 if (UNLIKELY(bin >= RHASH_AR_TABLE_MAX_BOUND)) {
837 bin = ar_compact_table(hash);
839 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
841 ar_set_entry(hash, bin, key, val, hash_value);
842 RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
843 RHASH_AR_TABLE_SIZE_INC(hash);
844 return 0;
848 static void
849 ensure_ar_table(VALUE hash)
851 if (!RHASH_AR_TABLE_P(hash)) {
852 rb_raise(rb_eRuntimeError, "hash representation was changed during iteration");
856 static int
857 ar_general_foreach(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
859 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
860 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
862 for (i = 0; i < bound; i++) {
863 if (ar_cleared_entry(hash, i)) continue;
865 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
866 st_data_t key = (st_data_t)pair->key;
867 st_data_t val = (st_data_t)pair->val;
868 enum st_retval retval = (*func)(key, val, arg, 0);
869 ensure_ar_table(hash);
870 /* pair may be not valid here because of theap */
872 switch (retval) {
873 case ST_CONTINUE:
874 break;
875 case ST_CHECK:
876 case ST_STOP:
877 return 0;
878 case ST_REPLACE:
879 if (replace) {
880 retval = (*replace)(&key, &val, arg, TRUE);
882 // TODO: pair should be same as pair before.
883 pair = RHASH_AR_TABLE_REF(hash, i);
884 pair->key = (VALUE)key;
885 pair->val = (VALUE)val;
887 break;
888 case ST_DELETE:
889 ar_clear_entry(hash, i);
890 RHASH_AR_TABLE_SIZE_DEC(hash);
891 break;
895 return 0;
898 static int
899 ar_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
901 return ar_general_foreach(hash, func, replace, arg);
904 struct functor {
905 st_foreach_callback_func *func;
906 st_data_t arg;
909 static int
910 apply_functor(st_data_t k, st_data_t v, st_data_t d, int _)
912 const struct functor *f = (void *)d;
913 return f->func(k, v, f->arg);
916 static int
917 ar_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
919 const struct functor f = { func, arg };
920 return ar_general_foreach(hash, apply_functor, NULL, (st_data_t)&f);
923 static int
924 ar_foreach_check(VALUE hash, st_foreach_check_callback_func *func, st_data_t arg,
925 st_data_t never)
927 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
928 unsigned i, ret = 0, bound = RHASH_AR_TABLE_BOUND(hash);
929 enum st_retval retval;
930 st_data_t key;
931 ar_table_pair *pair;
932 ar_hint_t hint;
934 for (i = 0; i < bound; i++) {
935 if (ar_cleared_entry(hash, i)) continue;
937 pair = RHASH_AR_TABLE_REF(hash, i);
938 key = pair->key;
939 hint = ar_hint(hash, i);
941 retval = (*func)(key, pair->val, arg, 0);
942 ensure_ar_table(hash);
943 hash_verify(hash);
945 switch (retval) {
946 case ST_CHECK: {
947 pair = RHASH_AR_TABLE_REF(hash, i);
948 if (pair->key == never) break;
949 ret = ar_find_entry_hint(hash, hint, key);
950 if (ret == RHASH_AR_TABLE_MAX_BOUND) {
951 retval = (*func)(0, 0, arg, 1);
952 return 2;
955 case ST_CONTINUE:
956 break;
957 case ST_STOP:
958 case ST_REPLACE:
959 return 0;
960 case ST_DELETE: {
961 if (!ar_cleared_entry(hash, i)) {
962 ar_clear_entry(hash, i);
963 RHASH_AR_TABLE_SIZE_DEC(hash);
965 break;
970 return 0;
973 static int
974 ar_update(VALUE hash, st_data_t key,
975 st_update_callback_func *func, st_data_t arg)
977 int retval, existing;
978 unsigned bin = RHASH_AR_TABLE_MAX_BOUND;
979 st_data_t value = 0, old_key;
980 st_hash_t hash_value = ar_do_hash(key);
982 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
983 // `#hash` changes ar_table -> st_table
984 return -1;
987 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
988 bin = ar_find_entry(hash, hash_value, key);
989 existing = (bin != RHASH_AR_TABLE_MAX_BOUND) ? TRUE : FALSE;
991 else {
992 existing = FALSE;
995 if (existing) {
996 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
997 key = pair->key;
998 value = pair->val;
1000 old_key = key;
1001 retval = (*func)(&key, &value, arg, existing);
1002 /* pair can be invalid here because of theap */
1003 ensure_ar_table(hash);
1005 switch (retval) {
1006 case ST_CONTINUE:
1007 if (!existing) {
1008 if (ar_add_direct_with_hash(hash, key, value, hash_value)) {
1009 return -1;
1012 else {
1013 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1014 if (old_key != key) {
1015 pair->key = key;
1017 pair->val = value;
1019 break;
1020 case ST_DELETE:
1021 if (existing) {
1022 ar_clear_entry(hash, bin);
1023 RHASH_AR_TABLE_SIZE_DEC(hash);
1025 break;
1027 return existing;
1030 static int
1031 ar_insert(VALUE hash, st_data_t key, st_data_t value)
1033 unsigned bin = RHASH_AR_TABLE_BOUND(hash);
1034 st_hash_t hash_value = ar_do_hash(key);
1036 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1037 // `#hash` changes ar_table -> st_table
1038 return -1;
1041 bin = ar_find_entry(hash, hash_value, key);
1042 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1043 if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
1044 return -1;
1046 else if (bin >= RHASH_AR_TABLE_MAX_BOUND) {
1047 bin = ar_compact_table(hash);
1049 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1051 ar_set_entry(hash, bin, key, value, hash_value);
1052 RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
1053 RHASH_AR_TABLE_SIZE_INC(hash);
1054 return 0;
1056 else {
1057 RHASH_AR_TABLE_REF(hash, bin)->val = value;
1058 return 1;
1062 static int
1063 ar_lookup(VALUE hash, st_data_t key, st_data_t *value)
1065 if (RHASH_AR_TABLE_SIZE(hash) == 0) {
1066 return 0;
1068 else {
1069 st_hash_t hash_value = ar_do_hash(key);
1070 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1071 // `#hash` changes ar_table -> st_table
1072 return st_lookup(RHASH_ST_TABLE(hash), key, value);
1074 unsigned bin = ar_find_entry(hash, hash_value, key);
1076 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1077 return 0;
1079 else {
1080 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1081 if (value != NULL) {
1082 *value = RHASH_AR_TABLE_REF(hash, bin)->val;
1084 return 1;
1089 static int
1090 ar_delete(VALUE hash, st_data_t *key, st_data_t *value)
1092 unsigned bin;
1093 st_hash_t hash_value = ar_do_hash(*key);
1095 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1096 // `#hash` changes ar_table -> st_table
1097 return st_delete(RHASH_ST_TABLE(hash), key, value);
1100 bin = ar_find_entry(hash, hash_value, *key);
1102 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1103 if (value != 0) *value = 0;
1104 return 0;
1106 else {
1107 if (value != 0) {
1108 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1109 *value = pair->val;
1111 ar_clear_entry(hash, bin);
1112 RHASH_AR_TABLE_SIZE_DEC(hash);
1113 return 1;
1117 static int
1118 ar_shift(VALUE hash, st_data_t *key, st_data_t *value)
1120 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
1121 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1123 for (i = 0; i < bound; i++) {
1124 if (!ar_cleared_entry(hash, i)) {
1125 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
1126 if (value != 0) *value = pair->val;
1127 *key = pair->key;
1128 ar_clear_entry(hash, i);
1129 RHASH_AR_TABLE_SIZE_DEC(hash);
1130 return 1;
1134 if (value != NULL) *value = 0;
1135 return 0;
1138 static long
1139 ar_keys(VALUE hash, st_data_t *keys, st_index_t size)
1141 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1142 st_data_t *keys_start = keys, *keys_end = keys + size;
1144 for (i = 0; i < bound; i++) {
1145 if (keys == keys_end) {
1146 break;
1148 else {
1149 if (!ar_cleared_entry(hash, i)) {
1150 *keys++ = RHASH_AR_TABLE_REF(hash, i)->key;
1155 return keys - keys_start;
1158 static long
1159 ar_values(VALUE hash, st_data_t *values, st_index_t size)
1161 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1162 st_data_t *values_start = values, *values_end = values + size;
1164 for (i = 0; i < bound; i++) {
1165 if (values == values_end) {
1166 break;
1168 else {
1169 if (!ar_cleared_entry(hash, i)) {
1170 *values++ = RHASH_AR_TABLE_REF(hash, i)->val;
1175 return values - values_start;
1178 static ar_table*
1179 ar_copy(VALUE hash1, VALUE hash2)
1181 ar_table *old_tab = RHASH_AR_TABLE(hash2);
1182 ar_table *new_tab = RHASH_AR_TABLE(hash1);
1184 *new_tab = *old_tab;
1185 RHASH_AR_TABLE(hash1)->ar_hint.word = RHASH_AR_TABLE(hash2)->ar_hint.word;
1186 RHASH_AR_TABLE_BOUND_SET(hash1, RHASH_AR_TABLE_BOUND(hash2));
1187 RHASH_AR_TABLE_SIZE_SET(hash1, RHASH_AR_TABLE_SIZE(hash2));
1189 rb_gc_writebarrier_remember(hash1);
1191 return new_tab;
1194 static void
1195 ar_clear(VALUE hash)
1197 if (RHASH_AR_TABLE(hash) != NULL) {
1198 RHASH_AR_TABLE_SIZE_SET(hash, 0);
1199 RHASH_AR_TABLE_BOUND_SET(hash, 0);
1201 else {
1202 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
1203 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
1207 static void
1208 hash_st_free(VALUE hash)
1210 HASH_ASSERT(RHASH_ST_TABLE_P(hash));
1212 st_table *tab = RHASH_ST_TABLE(hash);
1214 xfree(tab->bins);
1215 xfree(tab->entries);
1218 static void
1219 hash_st_free_and_clear_table(VALUE hash)
1221 hash_st_free(hash);
1223 RHASH_ST_CLEAR(hash);
1226 void
1227 rb_hash_free(VALUE hash)
1229 if (RHASH_ST_TABLE_P(hash)) {
1230 hash_st_free(hash);
1234 typedef int st_foreach_func(st_data_t, st_data_t, st_data_t);
1236 struct foreach_safe_arg {
1237 st_table *tbl;
1238 st_foreach_func *func;
1239 st_data_t arg;
1242 static int
1243 foreach_safe_i(st_data_t key, st_data_t value, st_data_t args, int error)
1245 int status;
1246 struct foreach_safe_arg *arg = (void *)args;
1248 if (error) return ST_STOP;
1249 status = (*arg->func)(key, value, arg->arg);
1250 if (status == ST_CONTINUE) {
1251 return ST_CHECK;
1253 return status;
1256 void
1257 st_foreach_safe(st_table *table, st_foreach_func *func, st_data_t a)
1259 struct foreach_safe_arg arg;
1261 arg.tbl = table;
1262 arg.func = (st_foreach_func *)func;
1263 arg.arg = a;
1264 if (st_foreach_check(table, foreach_safe_i, (st_data_t)&arg, 0)) {
1265 rb_raise(rb_eRuntimeError, "hash modified during iteration");
1269 typedef int rb_foreach_func(VALUE, VALUE, VALUE);
1271 struct hash_foreach_arg {
1272 VALUE hash;
1273 rb_foreach_func *func;
1274 VALUE arg;
1277 static int
1278 hash_iter_status_check(int status)
1280 switch (status) {
1281 case ST_DELETE:
1282 return ST_DELETE;
1283 case ST_CONTINUE:
1284 break;
1285 case ST_STOP:
1286 return ST_STOP;
1289 return ST_CHECK;
1292 static int
1293 hash_ar_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1295 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1297 if (error) return ST_STOP;
1299 int status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1300 /* TODO: rehash check? rb_raise(rb_eRuntimeError, "rehash occurred during iteration"); */
1302 return hash_iter_status_check(status);
1305 static int
1306 hash_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1308 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1310 if (error) return ST_STOP;
1312 st_table *tbl = RHASH_ST_TABLE(arg->hash);
1313 int status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1315 if (RHASH_ST_TABLE(arg->hash) != tbl) {
1316 rb_raise(rb_eRuntimeError, "rehash occurred during iteration");
1319 return hash_iter_status_check(status);
1322 static unsigned long
1323 iter_lev_in_ivar(VALUE hash)
1325 VALUE levval = rb_ivar_get(hash, id_hash_iter_lev);
1326 HASH_ASSERT(FIXNUM_P(levval));
1327 long lev = FIX2LONG(levval);
1328 HASH_ASSERT(lev >= 0);
1329 return (unsigned long)lev;
1332 void rb_ivar_set_internal(VALUE obj, ID id, VALUE val);
1334 static void
1335 iter_lev_in_ivar_set(VALUE hash, unsigned long lev)
1337 HASH_ASSERT(lev >= RHASH_LEV_MAX);
1338 HASH_ASSERT(POSFIXABLE(lev)); /* POSFIXABLE means fitting to long */
1339 rb_ivar_set_internal(hash, id_hash_iter_lev, LONG2FIX((long)lev));
1342 static inline unsigned long
1343 iter_lev_in_flags(VALUE hash)
1345 return (unsigned long)((RBASIC(hash)->flags >> RHASH_LEV_SHIFT) & RHASH_LEV_MAX);
1348 static inline void
1349 iter_lev_in_flags_set(VALUE hash, unsigned long lev)
1351 HASH_ASSERT(lev <= RHASH_LEV_MAX);
1352 RBASIC(hash)->flags = ((RBASIC(hash)->flags & ~RHASH_LEV_MASK) | ((VALUE)lev << RHASH_LEV_SHIFT));
1355 static inline bool
1356 hash_iterating_p(VALUE hash)
1358 return iter_lev_in_flags(hash) > 0;
1361 static void
1362 hash_iter_lev_inc(VALUE hash)
1364 unsigned long lev = iter_lev_in_flags(hash);
1365 if (lev == RHASH_LEV_MAX) {
1366 lev = iter_lev_in_ivar(hash) + 1;
1367 if (!POSFIXABLE(lev)) { /* paranoiac check */
1368 rb_raise(rb_eRuntimeError, "too much nested iterations");
1371 else {
1372 lev += 1;
1373 iter_lev_in_flags_set(hash, lev);
1374 if (lev < RHASH_LEV_MAX) return;
1376 iter_lev_in_ivar_set(hash, lev);
1379 static void
1380 hash_iter_lev_dec(VALUE hash)
1382 unsigned long lev = iter_lev_in_flags(hash);
1383 if (lev == RHASH_LEV_MAX) {
1384 lev = iter_lev_in_ivar(hash);
1385 if (lev > RHASH_LEV_MAX) {
1386 iter_lev_in_ivar_set(hash, lev-1);
1387 return;
1389 rb_attr_delete(hash, id_hash_iter_lev);
1391 else if (lev == 0) {
1392 rb_raise(rb_eRuntimeError, "iteration level underflow");
1394 iter_lev_in_flags_set(hash, lev - 1);
1397 static VALUE
1398 hash_foreach_ensure_rollback(VALUE hash)
1400 hash_iter_lev_inc(hash);
1401 return 0;
1404 static VALUE
1405 hash_foreach_ensure(VALUE hash)
1407 hash_iter_lev_dec(hash);
1408 return 0;
1412 rb_hash_stlike_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
1414 if (RHASH_AR_TABLE_P(hash)) {
1415 return ar_foreach(hash, func, arg);
1417 else {
1418 return st_foreach(RHASH_ST_TABLE(hash), func, arg);
1423 rb_hash_stlike_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
1425 if (RHASH_AR_TABLE_P(hash)) {
1426 return ar_foreach_with_replace(hash, func, replace, arg);
1428 else {
1429 return st_foreach_with_replace(RHASH_ST_TABLE(hash), func, replace, arg);
1433 static VALUE
1434 hash_foreach_call(VALUE arg)
1436 VALUE hash = ((struct hash_foreach_arg *)arg)->hash;
1437 int ret = 0;
1438 if (RHASH_AR_TABLE_P(hash)) {
1439 ret = ar_foreach_check(hash, hash_ar_foreach_iter,
1440 (st_data_t)arg, (st_data_t)Qundef);
1442 else if (RHASH_ST_TABLE_P(hash)) {
1443 ret = st_foreach_check(RHASH_ST_TABLE(hash), hash_foreach_iter,
1444 (st_data_t)arg, (st_data_t)Qundef);
1446 if (ret) {
1447 rb_raise(rb_eRuntimeError, "ret: %d, hash modified during iteration", ret);
1449 return Qnil;
1452 void
1453 rb_hash_foreach(VALUE hash, rb_foreach_func *func, VALUE farg)
1455 struct hash_foreach_arg arg;
1457 if (RHASH_TABLE_EMPTY_P(hash))
1458 return;
1459 arg.hash = hash;
1460 arg.func = (rb_foreach_func *)func;
1461 arg.arg = farg;
1462 if (RB_OBJ_FROZEN(hash)) {
1463 hash_foreach_call((VALUE)&arg);
1465 else {
1466 hash_iter_lev_inc(hash);
1467 rb_ensure(hash_foreach_call, (VALUE)&arg, hash_foreach_ensure, hash);
1469 hash_verify(hash);
1472 void rb_st_compact_table(st_table *tab);
1474 static void
1475 compact_after_delete(VALUE hash)
1477 if (!hash_iterating_p(hash) && RHASH_ST_TABLE_P(hash)) {
1478 rb_st_compact_table(RHASH_ST_TABLE(hash));
1482 static VALUE
1483 hash_alloc_flags(VALUE klass, VALUE flags, VALUE ifnone, bool st)
1485 const VALUE wb = (RGENGC_WB_PROTECTED_HASH ? FL_WB_PROTECTED : 0);
1486 const size_t size = sizeof(struct RHash) + (st ? sizeof(st_table) : sizeof(ar_table));
1488 NEWOBJ_OF(hash, struct RHash, klass, T_HASH | wb | flags, size, 0);
1490 RHASH_SET_IFNONE((VALUE)hash, ifnone);
1492 return (VALUE)hash;
1495 static VALUE
1496 hash_alloc(VALUE klass)
1498 /* Allocate to be able to fit both st_table and ar_table. */
1499 return hash_alloc_flags(klass, 0, Qnil, sizeof(st_table) > sizeof(ar_table));
1502 static VALUE
1503 empty_hash_alloc(VALUE klass)
1505 RUBY_DTRACE_CREATE_HOOK(HASH, 0);
1507 return hash_alloc(klass);
1510 VALUE
1511 rb_hash_new(void)
1513 return hash_alloc(rb_cHash);
1516 static VALUE
1517 copy_compare_by_id(VALUE hash, VALUE basis)
1519 if (rb_hash_compare_by_id_p(basis)) {
1520 return rb_hash_compare_by_id(hash);
1522 return hash;
1525 VALUE
1526 rb_hash_new_with_size(st_index_t size)
1528 bool st = size > RHASH_AR_TABLE_MAX_SIZE;
1529 VALUE ret = hash_alloc_flags(rb_cHash, 0, Qnil, st);
1531 if (st) {
1532 hash_st_table_init(ret, &objhash, size);
1535 return ret;
1538 VALUE
1539 rb_hash_new_capa(long capa)
1541 return rb_hash_new_with_size((st_index_t)capa);
1544 static VALUE
1545 hash_copy(VALUE ret, VALUE hash)
1547 if (RHASH_AR_TABLE_P(hash)) {
1548 if (RHASH_AR_TABLE_P(ret)) {
1549 ar_copy(ret, hash);
1551 else {
1552 st_table *tab = RHASH_ST_TABLE(ret);
1553 st_init_existing_table_with_size(tab, &objhash, RHASH_AR_TABLE_SIZE(hash));
1555 int bound = RHASH_AR_TABLE_BOUND(hash);
1556 for (int i = 0; i < bound; i++) {
1557 if (ar_cleared_entry(hash, i)) continue;
1559 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
1560 st_add_direct(tab, pair->key, pair->val);
1561 RB_OBJ_WRITTEN(ret, Qundef, pair->key);
1562 RB_OBJ_WRITTEN(ret, Qundef, pair->val);
1566 else {
1567 HASH_ASSERT(sizeof(st_table) <= sizeof(ar_table));
1569 RHASH_SET_ST_FLAG(ret);
1570 st_replace(RHASH_ST_TABLE(ret), RHASH_ST_TABLE(hash));
1572 rb_gc_writebarrier_remember(ret);
1574 return ret;
1577 static VALUE
1578 hash_dup_with_compare_by_id(VALUE hash)
1580 VALUE dup = hash_alloc_flags(rb_cHash, 0, Qnil, RHASH_ST_TABLE_P(hash));
1581 if (RHASH_ST_TABLE_P(hash)) {
1582 RHASH_SET_ST_FLAG(dup);
1584 else {
1585 RHASH_UNSET_ST_FLAG(dup);
1588 return hash_copy(dup, hash);
1591 static VALUE
1592 hash_dup(VALUE hash, VALUE klass, VALUE flags)
1594 return hash_copy(hash_alloc_flags(klass, flags, RHASH_IFNONE(hash), !RHASH_EMPTY_P(hash) && RHASH_ST_TABLE_P(hash)),
1595 hash);
1598 VALUE
1599 rb_hash_dup(VALUE hash)
1601 const VALUE flags = RBASIC(hash)->flags;
1602 VALUE ret = hash_dup(hash, rb_obj_class(hash),
1603 flags & (FL_EXIVAR|RHASH_PROC_DEFAULT));
1604 if (flags & FL_EXIVAR)
1605 rb_copy_generic_ivar(ret, hash);
1606 return ret;
1609 VALUE
1610 rb_hash_resurrect(VALUE hash)
1612 VALUE ret = hash_dup(hash, rb_cHash, 0);
1613 return ret;
1616 static void
1617 rb_hash_modify_check(VALUE hash)
1619 rb_check_frozen(hash);
1622 struct st_table *
1623 rb_hash_tbl_raw(VALUE hash, const char *file, int line)
1625 return ar_force_convert_table(hash, file, line);
1628 struct st_table *
1629 rb_hash_tbl(VALUE hash, const char *file, int line)
1631 OBJ_WB_UNPROTECT(hash);
1632 return rb_hash_tbl_raw(hash, file, line);
1635 static void
1636 rb_hash_modify(VALUE hash)
1638 rb_hash_modify_check(hash);
1641 NORETURN(static void no_new_key(void));
1642 static void
1643 no_new_key(void)
1645 rb_raise(rb_eRuntimeError, "can't add a new key into hash during iteration");
1648 struct update_callback_arg {
1649 VALUE hash;
1650 st_data_t arg;
1653 #define NOINSERT_UPDATE_CALLBACK(func) \
1654 static int \
1655 func##_noinsert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1657 if (!existing) no_new_key(); \
1658 return func(key, val, (struct update_arg *)arg, existing); \
1661 static int \
1662 func##_insert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1664 return func(key, val, (struct update_arg *)arg, existing); \
1667 struct update_arg {
1668 st_data_t arg;
1669 st_update_callback_func *func;
1670 VALUE hash;
1671 VALUE key;
1672 VALUE value;
1675 typedef int (*tbl_update_func)(st_data_t *, st_data_t *, st_data_t, int);
1678 rb_hash_stlike_update(VALUE hash, st_data_t key, st_update_callback_func *func, st_data_t arg)
1680 if (RHASH_AR_TABLE_P(hash)) {
1681 int result = ar_update(hash, key, func, arg);
1682 if (result == -1) {
1683 ar_force_convert_table(hash, __FILE__, __LINE__);
1685 else {
1686 return result;
1690 return st_update(RHASH_ST_TABLE(hash), key, func, arg);
1693 static int
1694 tbl_update_modify(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
1696 struct update_arg *p = (struct update_arg *)arg;
1697 st_data_t old_key = *key;
1698 st_data_t old_value = *val;
1699 VALUE hash = p->hash;
1700 int ret = (p->func)(key, val, arg, existing);
1701 switch (ret) {
1702 default:
1703 break;
1704 case ST_CONTINUE:
1705 if (!existing || *key != old_key || *val != old_value) {
1706 rb_hash_modify(hash);
1707 p->key = *key;
1708 p->value = *val;
1710 break;
1711 case ST_DELETE:
1712 if (existing)
1713 rb_hash_modify(hash);
1714 break;
1717 return ret;
1720 static int
1721 tbl_update(VALUE hash, VALUE key, tbl_update_func func, st_data_t optional_arg)
1723 struct update_arg arg = {
1724 .arg = optional_arg,
1725 .func = func,
1726 .hash = hash,
1727 .key = key,
1728 .value = (VALUE)optional_arg,
1731 int ret = rb_hash_stlike_update(hash, key, tbl_update_modify, (st_data_t)&arg);
1733 /* write barrier */
1734 RB_OBJ_WRITTEN(hash, Qundef, arg.key);
1735 RB_OBJ_WRITTEN(hash, Qundef, arg.value);
1737 return ret;
1740 #define UPDATE_CALLBACK(iter_p, func) ((iter_p) ? func##_noinsert : func##_insert)
1742 #define RHASH_UPDATE_ITER(h, iter_p, key, func, a) do { \
1743 tbl_update((h), (key), UPDATE_CALLBACK(iter_p, func), (st_data_t)(a)); \
1744 } while (0)
1746 #define RHASH_UPDATE(hash, key, func, arg) \
1747 RHASH_UPDATE_ITER(hash, hash_iterating_p(hash), key, func, arg)
1749 static void
1750 set_proc_default(VALUE hash, VALUE proc)
1752 if (rb_proc_lambda_p(proc)) {
1753 int n = rb_proc_arity(proc);
1755 if (n != 2 && (n >= 0 || n < -3)) {
1756 if (n < 0) n = -n-1;
1757 rb_raise(rb_eTypeError, "default_proc takes two arguments (2 for %d)", n);
1761 FL_SET_RAW(hash, RHASH_PROC_DEFAULT);
1762 RHASH_SET_IFNONE(hash, proc);
1766 * call-seq:
1767 * Hash.new(default_value = nil) -> new_hash
1768 * Hash.new {|hash, key| ... } -> new_hash
1770 * Returns a new empty +Hash+ object.
1772 * The initial default value and initial default proc for the new hash
1773 * depend on which form above was used. See {Default Values}[rdoc-ref:Hash@Default+Values].
1775 * If neither an argument nor a block given,
1776 * initializes both the default value and the default proc to <tt>nil</tt>:
1777 * h = Hash.new
1778 * h.default # => nil
1779 * h.default_proc # => nil
1781 * If argument <tt>default_value</tt> given but no block given,
1782 * initializes the default value to the given <tt>default_value</tt>
1783 * and the default proc to <tt>nil</tt>:
1784 * h = Hash.new(false)
1785 * h.default # => false
1786 * h.default_proc # => nil
1788 * If a block given but no argument, stores the block as the default proc
1789 * and sets the default value to <tt>nil</tt>:
1790 * h = Hash.new {|hash, key| "Default value for #{key}" }
1791 * h.default # => nil
1792 * h.default_proc.class # => Proc
1793 * h[:nosuch] # => "Default value for nosuch"
1796 static VALUE
1797 rb_hash_initialize(int argc, VALUE *argv, VALUE hash)
1799 rb_hash_modify(hash);
1801 if (rb_block_given_p()) {
1802 rb_check_arity(argc, 0, 0);
1803 SET_PROC_DEFAULT(hash, rb_block_proc());
1805 else {
1806 rb_check_arity(argc, 0, 1);
1808 VALUE options, ifnone;
1809 rb_scan_args(argc, argv, "01:", &ifnone, &options);
1810 if (NIL_P(ifnone) && !NIL_P(options)) {
1811 ifnone = options;
1812 rb_warn_deprecated_to_remove("3.4", "Calling Hash.new with keyword arguments", "Hash.new({ key: value })");
1814 RHASH_SET_IFNONE(hash, ifnone);
1817 return hash;
1820 static VALUE rb_hash_to_a(VALUE hash);
1823 * call-seq:
1824 * Hash[] -> new_empty_hash
1825 * Hash[hash] -> new_hash
1826 * Hash[ [*2_element_arrays] ] -> new_hash
1827 * Hash[*objects] -> new_hash
1829 * Returns a new +Hash+ object populated with the given objects, if any.
1830 * See Hash::new.
1832 * With no argument, returns a new empty +Hash+.
1834 * When the single given argument is a +Hash+, returns a new +Hash+
1835 * populated with the entries from the given +Hash+, excluding the
1836 * default value or proc.
1838 * h = {foo: 0, bar: 1, baz: 2}
1839 * Hash[h] # => {:foo=>0, :bar=>1, :baz=>2}
1841 * When the single given argument is an Array of 2-element Arrays,
1842 * returns a new +Hash+ object wherein each 2-element array forms a
1843 * key-value entry:
1845 * Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {:foo=>0, :bar=>1}
1847 * When the argument count is an even number;
1848 * returns a new +Hash+ object wherein each successive pair of arguments
1849 * has become a key-value entry:
1851 * Hash[:foo, 0, :bar, 1] # => {:foo=>0, :bar=>1}
1853 * Raises an exception if the argument list does not conform to any
1854 * of the above.
1857 static VALUE
1858 rb_hash_s_create(int argc, VALUE *argv, VALUE klass)
1860 VALUE hash, tmp;
1862 if (argc == 1) {
1863 tmp = rb_hash_s_try_convert(Qnil, argv[0]);
1864 if (!NIL_P(tmp)) {
1865 if (!RHASH_EMPTY_P(tmp) && rb_hash_compare_by_id_p(tmp)) {
1866 /* hash_copy for non-empty hash will copy compare_by_identity
1867 flag, but we don't want it copied. Work around by
1868 converting hash to flattened array and using that. */
1869 tmp = rb_hash_to_a(tmp);
1871 else {
1872 hash = hash_alloc(klass);
1873 if (!RHASH_EMPTY_P(tmp))
1874 hash_copy(hash, tmp);
1875 return hash;
1878 else {
1879 tmp = rb_check_array_type(argv[0]);
1882 if (!NIL_P(tmp)) {
1883 long i;
1885 hash = hash_alloc(klass);
1886 for (i = 0; i < RARRAY_LEN(tmp); ++i) {
1887 VALUE e = RARRAY_AREF(tmp, i);
1888 VALUE v = rb_check_array_type(e);
1889 VALUE key, val = Qnil;
1891 if (NIL_P(v)) {
1892 rb_raise(rb_eArgError, "wrong element type %s at %ld (expected array)",
1893 rb_builtin_class_name(e), i);
1895 switch (RARRAY_LEN(v)) {
1896 default:
1897 rb_raise(rb_eArgError, "invalid number of elements (%ld for 1..2)",
1898 RARRAY_LEN(v));
1899 case 2:
1900 val = RARRAY_AREF(v, 1);
1901 case 1:
1902 key = RARRAY_AREF(v, 0);
1903 rb_hash_aset(hash, key, val);
1906 return hash;
1909 if (argc % 2 != 0) {
1910 rb_raise(rb_eArgError, "odd number of arguments for Hash");
1913 hash = hash_alloc(klass);
1914 rb_hash_bulk_insert(argc, argv, hash);
1915 hash_verify(hash);
1916 return hash;
1919 VALUE
1920 rb_to_hash_type(VALUE hash)
1922 return rb_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1924 #define to_hash rb_to_hash_type
1926 VALUE
1927 rb_check_hash_type(VALUE hash)
1929 return rb_check_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1933 * call-seq:
1934 * Hash.try_convert(obj) -> obj, new_hash, or nil
1936 * If +obj+ is a +Hash+ object, returns +obj+.
1938 * Otherwise if +obj+ responds to <tt>:to_hash</tt>,
1939 * calls <tt>obj.to_hash</tt> and returns the result.
1941 * Returns +nil+ if +obj+ does not respond to <tt>:to_hash</tt>
1943 * Raises an exception unless <tt>obj.to_hash</tt> returns a +Hash+ object.
1945 static VALUE
1946 rb_hash_s_try_convert(VALUE dummy, VALUE hash)
1948 return rb_check_hash_type(hash);
1952 * call-seq:
1953 * Hash.ruby2_keywords_hash?(hash) -> true or false
1955 * Checks if a given hash is flagged by Module#ruby2_keywords (or
1956 * Proc#ruby2_keywords).
1957 * This method is not for casual use; debugging, researching, and
1958 * some truly necessary cases like serialization of arguments.
1960 * ruby2_keywords def foo(*args)
1961 * Hash.ruby2_keywords_hash?(args.last)
1962 * end
1963 * foo(k: 1) #=> true
1964 * foo({k: 1}) #=> false
1966 static VALUE
1967 rb_hash_s_ruby2_keywords_hash_p(VALUE dummy, VALUE hash)
1969 Check_Type(hash, T_HASH);
1970 return RBOOL(RHASH(hash)->basic.flags & RHASH_PASS_AS_KEYWORDS);
1974 * call-seq:
1975 * Hash.ruby2_keywords_hash(hash) -> hash
1977 * Duplicates a given hash and adds a ruby2_keywords flag.
1978 * This method is not for casual use; debugging, researching, and
1979 * some truly necessary cases like deserialization of arguments.
1981 * h = {k: 1}
1982 * h = Hash.ruby2_keywords_hash(h)
1983 * def foo(k: 42)
1985 * end
1986 * foo(*[h]) #=> 1 with neither a warning or an error
1988 static VALUE
1989 rb_hash_s_ruby2_keywords_hash(VALUE dummy, VALUE hash)
1991 Check_Type(hash, T_HASH);
1992 VALUE tmp = rb_hash_dup(hash);
1993 if (RHASH_EMPTY_P(hash) && rb_hash_compare_by_id_p(hash)) {
1994 rb_hash_compare_by_id(tmp);
1996 RHASH(tmp)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
1997 return tmp;
2000 struct rehash_arg {
2001 VALUE hash;
2002 st_table *tbl;
2005 static int
2006 rb_hash_rehash_i(VALUE key, VALUE value, VALUE arg)
2008 if (RHASH_AR_TABLE_P(arg)) {
2009 ar_insert(arg, (st_data_t)key, (st_data_t)value);
2011 else {
2012 st_insert(RHASH_ST_TABLE(arg), (st_data_t)key, (st_data_t)value);
2014 return ST_CONTINUE;
2018 * call-seq:
2019 * hash.rehash -> self
2021 * Rebuilds the hash table by recomputing the hash index for each key;
2022 * returns <tt>self</tt>.
2024 * The hash table becomes invalid if the hash value of a key
2025 * has changed after the entry was created.
2026 * See {Modifying an Active Hash Key}[rdoc-ref:Hash@Modifying+an+Active+Hash+Key].
2029 VALUE
2030 rb_hash_rehash(VALUE hash)
2032 VALUE tmp;
2033 st_table *tbl;
2035 if (hash_iterating_p(hash)) {
2036 rb_raise(rb_eRuntimeError, "rehash during iteration");
2038 rb_hash_modify_check(hash);
2039 if (RHASH_AR_TABLE_P(hash)) {
2040 tmp = hash_alloc(0);
2041 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
2043 hash_ar_free_and_clear_table(hash);
2044 ar_copy(hash, tmp);
2046 else if (RHASH_ST_TABLE_P(hash)) {
2047 st_table *old_tab = RHASH_ST_TABLE(hash);
2048 tmp = hash_alloc(0);
2050 hash_st_table_init(tmp, old_tab->type, old_tab->num_entries);
2051 tbl = RHASH_ST_TABLE(tmp);
2053 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
2055 hash_st_free(hash);
2056 RHASH_ST_TABLE_SET(hash, tbl);
2057 RHASH_ST_CLEAR(tmp);
2059 hash_verify(hash);
2060 return hash;
2063 static VALUE
2064 call_default_proc(VALUE proc, VALUE hash, VALUE key)
2066 VALUE args[2] = {hash, key};
2067 return rb_proc_call_with_block(proc, 2, args, Qnil);
2070 static bool
2071 rb_hash_default_unredefined(VALUE hash)
2073 VALUE klass = RBASIC_CLASS(hash);
2074 if (LIKELY(klass == rb_cHash)) {
2075 return !!BASIC_OP_UNREDEFINED_P(BOP_DEFAULT, HASH_REDEFINED_OP_FLAG);
2077 else {
2078 return LIKELY(rb_method_basic_definition_p(klass, id_default));
2082 VALUE
2083 rb_hash_default_value(VALUE hash, VALUE key)
2085 RUBY_ASSERT(RB_TYPE_P(hash, T_HASH));
2087 if (LIKELY(rb_hash_default_unredefined(hash))) {
2088 VALUE ifnone = RHASH_IFNONE(hash);
2089 if (LIKELY(!FL_TEST_RAW(hash, RHASH_PROC_DEFAULT))) return ifnone;
2090 if (UNDEF_P(key)) return Qnil;
2091 return call_default_proc(ifnone, hash, key);
2093 else {
2094 return rb_funcall(hash, id_default, 1, key);
2098 static inline int
2099 hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2101 hash_verify(hash);
2103 if (RHASH_AR_TABLE_P(hash)) {
2104 return ar_lookup(hash, key, pval);
2106 else {
2107 extern st_index_t rb_iseq_cdhash_hash(VALUE);
2108 RUBY_ASSERT(RHASH_ST_TABLE(hash)->type->hash == rb_any_hash ||
2109 RHASH_ST_TABLE(hash)->type->hash == rb_ident_hash ||
2110 RHASH_ST_TABLE(hash)->type->hash == rb_iseq_cdhash_hash);
2111 return st_lookup(RHASH_ST_TABLE(hash), key, pval);
2116 rb_hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2118 return hash_stlike_lookup(hash, key, pval);
2122 * call-seq:
2123 * hash[key] -> value
2125 * Returns the value associated with the given +key+, if found:
2126 * h = {foo: 0, bar: 1, baz: 2}
2127 * h[:foo] # => 0
2129 * If +key+ is not found, returns a default value
2130 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2131 * h = {foo: 0, bar: 1, baz: 2}
2132 * h[:nosuch] # => nil
2135 VALUE
2136 rb_hash_aref(VALUE hash, VALUE key)
2138 st_data_t val;
2140 if (hash_stlike_lookup(hash, key, &val)) {
2141 return (VALUE)val;
2143 else {
2144 return rb_hash_default_value(hash, key);
2148 VALUE
2149 rb_hash_lookup2(VALUE hash, VALUE key, VALUE def)
2151 st_data_t val;
2153 if (hash_stlike_lookup(hash, key, &val)) {
2154 return (VALUE)val;
2156 else {
2157 return def; /* without Hash#default */
2161 VALUE
2162 rb_hash_lookup(VALUE hash, VALUE key)
2164 return rb_hash_lookup2(hash, key, Qnil);
2168 * call-seq:
2169 * hash.fetch(key) -> object
2170 * hash.fetch(key, default_value) -> object
2171 * hash.fetch(key) {|key| ... } -> object
2173 * Returns the value for the given +key+, if found.
2174 * h = {foo: 0, bar: 1, baz: 2}
2175 * h.fetch(:bar) # => 1
2177 * If +key+ is not found and no block was given,
2178 * returns +default_value+:
2179 * {}.fetch(:nosuch, :default) # => :default
2181 * If +key+ is not found and a block was given,
2182 * yields +key+ to the block and returns the block's return value:
2183 * {}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
2185 * Raises KeyError if neither +default_value+ nor a block was given.
2187 * Note that this method does not use the values of either #default or #default_proc.
2190 static VALUE
2191 rb_hash_fetch_m(int argc, VALUE *argv, VALUE hash)
2193 VALUE key;
2194 st_data_t val;
2195 long block_given;
2197 rb_check_arity(argc, 1, 2);
2198 key = argv[0];
2200 block_given = rb_block_given_p();
2201 if (block_given && argc == 2) {
2202 rb_warn("block supersedes default value argument");
2205 if (hash_stlike_lookup(hash, key, &val)) {
2206 return (VALUE)val;
2208 else {
2209 if (block_given) {
2210 return rb_yield(key);
2212 else if (argc == 1) {
2213 VALUE desc = rb_protect(rb_inspect, key, 0);
2214 if (NIL_P(desc)) {
2215 desc = rb_any_to_s(key);
2217 desc = rb_str_ellipsize(desc, 65);
2218 rb_key_err_raise(rb_sprintf("key not found: %"PRIsVALUE, desc), hash, key);
2220 else {
2221 return argv[1];
2226 VALUE
2227 rb_hash_fetch(VALUE hash, VALUE key)
2229 return rb_hash_fetch_m(1, &key, hash);
2233 * call-seq:
2234 * hash.default -> object
2235 * hash.default(key) -> object
2237 * Returns the default value for the given +key+.
2238 * The returned value will be determined either by the default proc or by the default value.
2239 * See {Default Values}[rdoc-ref:Hash@Default+Values].
2241 * With no argument, returns the current default value:
2242 * h = {}
2243 * h.default # => nil
2245 * If +key+ is given, returns the default value for +key+,
2246 * regardless of whether that key exists:
2247 * h = Hash.new { |hash, key| hash[key] = "No key #{key}"}
2248 * h[:foo] = "Hello"
2249 * h.default(:foo) # => "No key foo"
2252 static VALUE
2253 rb_hash_default(int argc, VALUE *argv, VALUE hash)
2255 VALUE ifnone;
2257 rb_check_arity(argc, 0, 1);
2258 ifnone = RHASH_IFNONE(hash);
2259 if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2260 if (argc == 0) return Qnil;
2261 return call_default_proc(ifnone, hash, argv[0]);
2263 return ifnone;
2267 * call-seq:
2268 * hash.default = value -> object
2270 * Sets the default value to +value+; returns +value+:
2271 * h = {}
2272 * h.default # => nil
2273 * h.default = false # => false
2274 * h.default # => false
2276 * See {Default Values}[rdoc-ref:Hash@Default+Values].
2279 static VALUE
2280 rb_hash_set_default(VALUE hash, VALUE ifnone)
2282 rb_hash_modify_check(hash);
2283 SET_DEFAULT(hash, ifnone);
2284 return ifnone;
2288 * call-seq:
2289 * hash.default_proc -> proc or nil
2291 * Returns the default proc for +self+
2292 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2293 * h = {}
2294 * h.default_proc # => nil
2295 * h.default_proc = proc {|hash, key| "Default value for #{key}" }
2296 * h.default_proc.class # => Proc
2299 static VALUE
2300 rb_hash_default_proc(VALUE hash)
2302 if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2303 return RHASH_IFNONE(hash);
2305 return Qnil;
2309 * call-seq:
2310 * hash.default_proc = proc -> proc
2312 * Sets the default proc for +self+ to +proc+
2313 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2314 * h = {}
2315 * h.default_proc # => nil
2316 * h.default_proc = proc { |hash, key| "Default value for #{key}" }
2317 * h.default_proc.class # => Proc
2318 * h.default_proc = nil
2319 * h.default_proc # => nil
2322 VALUE
2323 rb_hash_set_default_proc(VALUE hash, VALUE proc)
2325 VALUE b;
2327 rb_hash_modify_check(hash);
2328 if (NIL_P(proc)) {
2329 SET_DEFAULT(hash, proc);
2330 return proc;
2332 b = rb_check_convert_type_with_id(proc, T_DATA, "Proc", idTo_proc);
2333 if (NIL_P(b) || !rb_obj_is_proc(b)) {
2334 rb_raise(rb_eTypeError,
2335 "wrong default_proc type %s (expected Proc)",
2336 rb_obj_classname(proc));
2338 proc = b;
2339 SET_PROC_DEFAULT(hash, proc);
2340 return proc;
2343 static int
2344 key_i(VALUE key, VALUE value, VALUE arg)
2346 VALUE *args = (VALUE *)arg;
2348 if (rb_equal(value, args[0])) {
2349 args[1] = key;
2350 return ST_STOP;
2352 return ST_CONTINUE;
2356 * call-seq:
2357 * hash.key(value) -> key or nil
2359 * Returns the key for the first-found entry with the given +value+
2360 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2361 * h = {foo: 0, bar: 2, baz: 2}
2362 * h.key(0) # => :foo
2363 * h.key(2) # => :bar
2365 * Returns +nil+ if no such value is found.
2368 static VALUE
2369 rb_hash_key(VALUE hash, VALUE value)
2371 VALUE args[2];
2373 args[0] = value;
2374 args[1] = Qnil;
2376 rb_hash_foreach(hash, key_i, (VALUE)args);
2378 return args[1];
2382 rb_hash_stlike_delete(VALUE hash, st_data_t *pkey, st_data_t *pval)
2384 if (RHASH_AR_TABLE_P(hash)) {
2385 return ar_delete(hash, pkey, pval);
2387 else {
2388 return st_delete(RHASH_ST_TABLE(hash), pkey, pval);
2393 * delete a specified entry by a given key.
2394 * if there is the corresponding entry, return a value of the entry.
2395 * if there is no corresponding entry, return Qundef.
2397 VALUE
2398 rb_hash_delete_entry(VALUE hash, VALUE key)
2400 st_data_t ktmp = (st_data_t)key, val;
2402 if (rb_hash_stlike_delete(hash, &ktmp, &val)) {
2403 return (VALUE)val;
2405 else {
2406 return Qundef;
2411 * delete a specified entry by a given key.
2412 * if there is the corresponding entry, return a value of the entry.
2413 * if there is no corresponding entry, return Qnil.
2415 VALUE
2416 rb_hash_delete(VALUE hash, VALUE key)
2418 VALUE deleted_value = rb_hash_delete_entry(hash, key);
2420 if (!UNDEF_P(deleted_value)) { /* likely pass */
2421 return deleted_value;
2423 else {
2424 return Qnil;
2429 * call-seq:
2430 * hash.delete(key) -> value or nil
2431 * hash.delete(key) {|key| ... } -> object
2433 * Deletes the entry for the given +key+ and returns its associated value.
2435 * If no block is given and +key+ is found, deletes the entry and returns the associated value:
2436 * h = {foo: 0, bar: 1, baz: 2}
2437 * h.delete(:bar) # => 1
2438 * h # => {:foo=>0, :baz=>2}
2440 * If no block given and +key+ is not found, returns +nil+.
2442 * If a block is given and +key+ is found, ignores the block,
2443 * deletes the entry, and returns the associated value:
2444 * h = {foo: 0, bar: 1, baz: 2}
2445 * h.delete(:baz) { |key| raise 'Will never happen'} # => 2
2446 * h # => {:foo=>0, :bar=>1}
2448 * If a block is given and +key+ is not found,
2449 * calls the block and returns the block's return value:
2450 * h = {foo: 0, bar: 1, baz: 2}
2451 * h.delete(:nosuch) { |key| "Key #{key} not found" } # => "Key nosuch not found"
2452 * h # => {:foo=>0, :bar=>1, :baz=>2}
2455 static VALUE
2456 rb_hash_delete_m(VALUE hash, VALUE key)
2458 VALUE val;
2460 rb_hash_modify_check(hash);
2461 val = rb_hash_delete_entry(hash, key);
2463 if (!UNDEF_P(val)) {
2464 compact_after_delete(hash);
2465 return val;
2467 else {
2468 if (rb_block_given_p()) {
2469 return rb_yield(key);
2471 else {
2472 return Qnil;
2477 struct shift_var {
2478 VALUE key;
2479 VALUE val;
2482 static int
2483 shift_i_safe(VALUE key, VALUE value, VALUE arg)
2485 struct shift_var *var = (struct shift_var *)arg;
2487 var->key = key;
2488 var->val = value;
2489 return ST_STOP;
2493 * call-seq:
2494 * hash.shift -> [key, value] or nil
2496 * Removes the first hash entry
2497 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]);
2498 * returns a 2-element Array containing the removed key and value:
2499 * h = {foo: 0, bar: 1, baz: 2}
2500 * h.shift # => [:foo, 0]
2501 * h # => {:bar=>1, :baz=>2}
2503 * Returns nil if the hash is empty.
2506 static VALUE
2507 rb_hash_shift(VALUE hash)
2509 struct shift_var var;
2511 rb_hash_modify_check(hash);
2512 if (RHASH_AR_TABLE_P(hash)) {
2513 var.key = Qundef;
2514 if (!hash_iterating_p(hash)) {
2515 if (ar_shift(hash, &var.key, &var.val)) {
2516 return rb_assoc_new(var.key, var.val);
2519 else {
2520 rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2521 if (!UNDEF_P(var.key)) {
2522 rb_hash_delete_entry(hash, var.key);
2523 return rb_assoc_new(var.key, var.val);
2527 if (RHASH_ST_TABLE_P(hash)) {
2528 var.key = Qundef;
2529 if (!hash_iterating_p(hash)) {
2530 if (st_shift(RHASH_ST_TABLE(hash), &var.key, &var.val)) {
2531 return rb_assoc_new(var.key, var.val);
2534 else {
2535 rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2536 if (!UNDEF_P(var.key)) {
2537 rb_hash_delete_entry(hash, var.key);
2538 return rb_assoc_new(var.key, var.val);
2542 return Qnil;
2545 static int
2546 delete_if_i(VALUE key, VALUE value, VALUE hash)
2548 if (RTEST(rb_yield_values(2, key, value))) {
2549 rb_hash_modify(hash);
2550 return ST_DELETE;
2552 return ST_CONTINUE;
2555 static VALUE
2556 hash_enum_size(VALUE hash, VALUE args, VALUE eobj)
2558 return rb_hash_size(hash);
2562 * call-seq:
2563 * hash.delete_if {|key, value| ... } -> self
2564 * hash.delete_if -> new_enumerator
2566 * If a block given, calls the block with each key-value pair;
2567 * deletes each entry for which the block returns a truthy value;
2568 * returns +self+:
2569 * h = {foo: 0, bar: 1, baz: 2}
2570 * h.delete_if {|key, value| value > 0 } # => {:foo=>0}
2572 * If no block given, returns a new Enumerator:
2573 * h = {foo: 0, bar: 1, baz: 2}
2574 * e = h.delete_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:delete_if>
2575 * e.each { |key, value| value > 0 } # => {:foo=>0}
2578 VALUE
2579 rb_hash_delete_if(VALUE hash)
2581 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2582 rb_hash_modify_check(hash);
2583 if (!RHASH_TABLE_EMPTY_P(hash)) {
2584 rb_hash_foreach(hash, delete_if_i, hash);
2585 compact_after_delete(hash);
2587 return hash;
2591 * call-seq:
2592 * hash.reject! {|key, value| ... } -> self or nil
2593 * hash.reject! -> new_enumerator
2595 * Returns +self+, whose remaining entries are those
2596 * for which the block returns +false+ or +nil+:
2597 * h = {foo: 0, bar: 1, baz: 2}
2598 * h.reject! {|key, value| value < 2 } # => {:baz=>2}
2600 * Returns +nil+ if no entries are removed.
2602 * Returns a new Enumerator if no block given:
2603 * h = {foo: 0, bar: 1, baz: 2}
2604 * e = h.reject! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject!>
2605 * e.each {|key, value| key.start_with?('b') } # => {:foo=>0}
2608 static VALUE
2609 rb_hash_reject_bang(VALUE hash)
2611 st_index_t n;
2613 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2614 rb_hash_modify(hash);
2615 n = RHASH_SIZE(hash);
2616 if (!n) return Qnil;
2617 rb_hash_foreach(hash, delete_if_i, hash);
2618 if (n == RHASH_SIZE(hash)) return Qnil;
2619 return hash;
2623 * call-seq:
2624 * hash.reject {|key, value| ... } -> new_hash
2625 * hash.reject -> new_enumerator
2627 * Returns a new +Hash+ object whose entries are all those
2628 * from +self+ for which the block returns +false+ or +nil+:
2629 * h = {foo: 0, bar: 1, baz: 2}
2630 * h1 = h.reject {|key, value| key.start_with?('b') }
2631 * h1 # => {:foo=>0}
2633 * Returns a new Enumerator if no block given:
2634 * h = {foo: 0, bar: 1, baz: 2}
2635 * e = h.reject # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject>
2636 * h1 = e.each {|key, value| key.start_with?('b') }
2637 * h1 # => {:foo=>0}
2640 static VALUE
2641 rb_hash_reject(VALUE hash)
2643 VALUE result;
2645 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2646 result = hash_dup_with_compare_by_id(hash);
2647 if (!RHASH_EMPTY_P(hash)) {
2648 rb_hash_foreach(result, delete_if_i, result);
2649 compact_after_delete(result);
2651 return result;
2655 * call-seq:
2656 * hash.slice(*keys) -> new_hash
2658 * Returns a new +Hash+ object containing the entries for the given +keys+:
2659 * h = {foo: 0, bar: 1, baz: 2}
2660 * h.slice(:baz, :foo) # => {:baz=>2, :foo=>0}
2662 * Any given +keys+ that are not found are ignored.
2665 static VALUE
2666 rb_hash_slice(int argc, VALUE *argv, VALUE hash)
2668 int i;
2669 VALUE key, value, result;
2671 if (argc == 0 || RHASH_EMPTY_P(hash)) {
2672 return copy_compare_by_id(rb_hash_new(), hash);
2674 result = copy_compare_by_id(rb_hash_new_with_size(argc), hash);
2676 for (i = 0; i < argc; i++) {
2677 key = argv[i];
2678 value = rb_hash_lookup2(hash, key, Qundef);
2679 if (!UNDEF_P(value))
2680 rb_hash_aset(result, key, value);
2683 return result;
2687 * call-seq:
2688 * hsh.except(*keys) -> a_hash
2690 * Returns a new +Hash+ excluding entries for the given +keys+:
2691 * h = { a: 100, b: 200, c: 300 }
2692 * h.except(:a) #=> {:b=>200, :c=>300}
2694 * Any given +keys+ that are not found are ignored.
2697 static VALUE
2698 rb_hash_except(int argc, VALUE *argv, VALUE hash)
2700 int i;
2701 VALUE key, result;
2703 result = hash_dup_with_compare_by_id(hash);
2705 for (i = 0; i < argc; i++) {
2706 key = argv[i];
2707 rb_hash_delete(result, key);
2709 compact_after_delete(result);
2711 return result;
2715 * call-seq:
2716 * hash.values_at(*keys) -> new_array
2718 * Returns a new Array containing values for the given +keys+:
2719 * h = {foo: 0, bar: 1, baz: 2}
2720 * h.values_at(:baz, :foo) # => [2, 0]
2722 * The {default values}[rdoc-ref:Hash@Default+Values] are returned
2723 * for any keys that are not found:
2724 * h.values_at(:hello, :foo) # => [nil, 0]
2727 static VALUE
2728 rb_hash_values_at(int argc, VALUE *argv, VALUE hash)
2730 VALUE result = rb_ary_new2(argc);
2731 long i;
2733 for (i=0; i<argc; i++) {
2734 rb_ary_push(result, rb_hash_aref(hash, argv[i]));
2736 return result;
2740 * call-seq:
2741 * hash.fetch_values(*keys) -> new_array
2742 * hash.fetch_values(*keys) {|key| ... } -> new_array
2744 * Returns a new Array containing the values associated with the given keys *keys:
2745 * h = {foo: 0, bar: 1, baz: 2}
2746 * h.fetch_values(:baz, :foo) # => [2, 0]
2748 * Returns a new empty Array if no arguments given.
2750 * When a block is given, calls the block with each missing key,
2751 * treating the block's return value as the value for that key:
2752 * h = {foo: 0, bar: 1, baz: 2}
2753 * values = h.fetch_values(:bar, :foo, :bad, :bam) {|key| key.to_s}
2754 * values # => [1, 0, "bad", "bam"]
2756 * When no block is given, raises an exception if any given key is not found.
2759 static VALUE
2760 rb_hash_fetch_values(int argc, VALUE *argv, VALUE hash)
2762 VALUE result = rb_ary_new2(argc);
2763 long i;
2765 for (i=0; i<argc; i++) {
2766 rb_ary_push(result, rb_hash_fetch(hash, argv[i]));
2768 return result;
2771 static int
2772 keep_if_i(VALUE key, VALUE value, VALUE hash)
2774 if (!RTEST(rb_yield_values(2, key, value))) {
2775 rb_hash_modify(hash);
2776 return ST_DELETE;
2778 return ST_CONTINUE;
2782 * call-seq:
2783 * hash.select {|key, value| ... } -> new_hash
2784 * hash.select -> new_enumerator
2786 * Returns a new +Hash+ object whose entries are those for which the block returns a truthy value:
2787 * h = {foo: 0, bar: 1, baz: 2}
2788 * h.select {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2790 * Returns a new Enumerator if no block given:
2791 * h = {foo: 0, bar: 1, baz: 2}
2792 * e = h.select # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select>
2793 * e.each {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2796 static VALUE
2797 rb_hash_select(VALUE hash)
2799 VALUE result;
2801 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2802 result = hash_dup_with_compare_by_id(hash);
2803 if (!RHASH_EMPTY_P(hash)) {
2804 rb_hash_foreach(result, keep_if_i, result);
2805 compact_after_delete(result);
2807 return result;
2811 * call-seq:
2812 * hash.select! {|key, value| ... } -> self or nil
2813 * hash.select! -> new_enumerator
2815 * Returns +self+, whose entries are those for which the block returns a truthy value:
2816 * h = {foo: 0, bar: 1, baz: 2}
2817 * h.select! {|key, value| value < 2 } => {:foo=>0, :bar=>1}
2819 * Returns +nil+ if no entries were removed.
2821 * Returns a new Enumerator if no block given:
2822 * h = {foo: 0, bar: 1, baz: 2}
2823 * e = h.select! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select!>
2824 * e.each { |key, value| value < 2 } # => {:foo=>0, :bar=>1}
2827 static VALUE
2828 rb_hash_select_bang(VALUE hash)
2830 st_index_t n;
2832 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2833 rb_hash_modify_check(hash);
2834 n = RHASH_SIZE(hash);
2835 if (!n) return Qnil;
2836 rb_hash_foreach(hash, keep_if_i, hash);
2837 if (n == RHASH_SIZE(hash)) return Qnil;
2838 return hash;
2842 * call-seq:
2843 * hash.keep_if {|key, value| ... } -> self
2844 * hash.keep_if -> new_enumerator
2846 * Calls the block for each key-value pair;
2847 * retains the entry if the block returns a truthy value;
2848 * otherwise deletes the entry; returns +self+.
2849 * h = {foo: 0, bar: 1, baz: 2}
2850 * h.keep_if { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2852 * Returns a new Enumerator if no block given:
2853 * h = {foo: 0, bar: 1, baz: 2}
2854 * e = h.keep_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:keep_if>
2855 * e.each { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2858 static VALUE
2859 rb_hash_keep_if(VALUE hash)
2861 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2862 rb_hash_modify_check(hash);
2863 if (!RHASH_TABLE_EMPTY_P(hash)) {
2864 rb_hash_foreach(hash, keep_if_i, hash);
2866 return hash;
2869 static int
2870 clear_i(VALUE key, VALUE value, VALUE dummy)
2872 return ST_DELETE;
2876 * call-seq:
2877 * hash.clear -> self
2879 * Removes all hash entries; returns +self+.
2882 VALUE
2883 rb_hash_clear(VALUE hash)
2885 rb_hash_modify_check(hash);
2887 if (hash_iterating_p(hash)) {
2888 rb_hash_foreach(hash, clear_i, 0);
2890 else if (RHASH_AR_TABLE_P(hash)) {
2891 ar_clear(hash);
2893 else {
2894 st_clear(RHASH_ST_TABLE(hash));
2895 compact_after_delete(hash);
2898 return hash;
2901 static int
2902 hash_aset(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2904 *val = arg->arg;
2905 return ST_CONTINUE;
2908 VALUE
2909 rb_hash_key_str(VALUE key)
2911 if (!RB_FL_ANY_RAW(key, FL_EXIVAR) && RBASIC_CLASS(key) == rb_cString) {
2912 return rb_fstring(key);
2914 else {
2915 return rb_str_new_frozen(key);
2919 static int
2920 hash_aset_str(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2922 if (!existing && !RB_OBJ_FROZEN(*key)) {
2923 *key = rb_hash_key_str(*key);
2925 return hash_aset(key, val, arg, existing);
2928 NOINSERT_UPDATE_CALLBACK(hash_aset)
2929 NOINSERT_UPDATE_CALLBACK(hash_aset_str)
2932 * call-seq:
2933 * hash[key] = value -> value
2934 * hash.store(key, value)
2936 * Associates the given +value+ with the given +key+; returns +value+.
2938 * If the given +key+ exists, replaces its value with the given +value+;
2939 * the ordering is not affected
2940 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2941 * h = {foo: 0, bar: 1}
2942 * h[:foo] = 2 # => 2
2943 * h.store(:bar, 3) # => 3
2944 * h # => {:foo=>2, :bar=>3}
2946 * If +key+ does not exist, adds the +key+ and +value+;
2947 * the new entry is last in the order
2948 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2949 * h = {foo: 0, bar: 1}
2950 * h[:baz] = 2 # => 2
2951 * h.store(:bat, 3) # => 3
2952 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
2955 VALUE
2956 rb_hash_aset(VALUE hash, VALUE key, VALUE val)
2958 bool iter_p = hash_iterating_p(hash);
2960 rb_hash_modify(hash);
2962 if (!RHASH_STRING_KEY_P(hash, key)) {
2963 RHASH_UPDATE_ITER(hash, iter_p, key, hash_aset, val);
2965 else {
2966 RHASH_UPDATE_ITER(hash, iter_p, key, hash_aset_str, val);
2968 return val;
2972 * call-seq:
2973 * hash.replace(other_hash) -> self
2975 * Replaces the entire contents of +self+ with the contents of +other_hash+;
2976 * returns +self+:
2977 * h = {foo: 0, bar: 1, baz: 2}
2978 * h.replace({bat: 3, bam: 4}) # => {:bat=>3, :bam=>4}
2981 static VALUE
2982 rb_hash_replace(VALUE hash, VALUE hash2)
2984 rb_hash_modify_check(hash);
2985 if (hash == hash2) return hash;
2986 if (hash_iterating_p(hash)) {
2987 rb_raise(rb_eRuntimeError, "can't replace hash during iteration");
2989 hash2 = to_hash(hash2);
2991 COPY_DEFAULT(hash, hash2);
2993 if (RHASH_AR_TABLE_P(hash)) {
2994 hash_ar_free_and_clear_table(hash);
2996 else {
2997 hash_st_free_and_clear_table(hash);
3000 hash_copy(hash, hash2);
3002 return hash;
3006 * call-seq:
3007 * hash.length -> integer
3008 * hash.size -> integer
3010 * Returns the count of entries in +self+:
3012 * {foo: 0, bar: 1, baz: 2}.length # => 3
3016 VALUE
3017 rb_hash_size(VALUE hash)
3019 return INT2FIX(RHASH_SIZE(hash));
3022 size_t
3023 rb_hash_size_num(VALUE hash)
3025 return (long)RHASH_SIZE(hash);
3029 * call-seq:
3030 * hash.empty? -> true or false
3032 * Returns +true+ if there are no hash entries, +false+ otherwise:
3033 * {}.empty? # => true
3034 * {foo: 0, bar: 1, baz: 2}.empty? # => false
3037 VALUE
3038 rb_hash_empty_p(VALUE hash)
3040 return RBOOL(RHASH_EMPTY_P(hash));
3043 static int
3044 each_value_i(VALUE key, VALUE value, VALUE _)
3046 rb_yield(value);
3047 return ST_CONTINUE;
3051 * call-seq:
3052 * hash.each_value {|value| ... } -> self
3053 * hash.each_value -> new_enumerator
3055 * Calls the given block with each value; returns +self+:
3056 * h = {foo: 0, bar: 1, baz: 2}
3057 * h.each_value {|value| puts value } # => {:foo=>0, :bar=>1, :baz=>2}
3058 * Output:
3063 * Returns a new Enumerator if no block given:
3064 * h = {foo: 0, bar: 1, baz: 2}
3065 * e = h.each_value # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_value>
3066 * h1 = e.each {|value| puts value }
3067 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3068 * Output:
3074 static VALUE
3075 rb_hash_each_value(VALUE hash)
3077 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3078 rb_hash_foreach(hash, each_value_i, 0);
3079 return hash;
3082 static int
3083 each_key_i(VALUE key, VALUE value, VALUE _)
3085 rb_yield(key);
3086 return ST_CONTINUE;
3090 * call-seq:
3091 * hash.each_key {|key| ... } -> self
3092 * hash.each_key -> new_enumerator
3094 * Calls the given block with each key; returns +self+:
3095 * h = {foo: 0, bar: 1, baz: 2}
3096 * h.each_key {|key| puts key } # => {:foo=>0, :bar=>1, :baz=>2}
3097 * Output:
3098 * foo
3099 * bar
3100 * baz
3102 * Returns a new Enumerator if no block given:
3103 * h = {foo: 0, bar: 1, baz: 2}
3104 * e = h.each_key # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_key>
3105 * h1 = e.each {|key| puts key }
3106 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3107 * Output:
3108 * foo
3109 * bar
3110 * baz
3112 static VALUE
3113 rb_hash_each_key(VALUE hash)
3115 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3116 rb_hash_foreach(hash, each_key_i, 0);
3117 return hash;
3120 static int
3121 each_pair_i(VALUE key, VALUE value, VALUE _)
3123 rb_yield(rb_assoc_new(key, value));
3124 return ST_CONTINUE;
3127 static int
3128 each_pair_i_fast(VALUE key, VALUE value, VALUE _)
3130 VALUE argv[2];
3131 argv[0] = key;
3132 argv[1] = value;
3133 rb_yield_values2(2, argv);
3134 return ST_CONTINUE;
3138 * call-seq:
3139 * hash.each {|key, value| ... } -> self
3140 * hash.each_pair {|key, value| ... } -> self
3141 * hash.each -> new_enumerator
3142 * hash.each_pair -> new_enumerator
3144 * Calls the given block with each key-value pair; returns +self+:
3145 * h = {foo: 0, bar: 1, baz: 2}
3146 * h.each_pair {|key, value| puts "#{key}: #{value}"} # => {:foo=>0, :bar=>1, :baz=>2}
3147 * Output:
3148 * foo: 0
3149 * bar: 1
3150 * baz: 2
3152 * Returns a new Enumerator if no block given:
3153 * h = {foo: 0, bar: 1, baz: 2}
3154 * e = h.each_pair # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_pair>
3155 * h1 = e.each {|key, value| puts "#{key}: #{value}"}
3156 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3157 * Output:
3158 * foo: 0
3159 * bar: 1
3160 * baz: 2
3163 static VALUE
3164 rb_hash_each_pair(VALUE hash)
3166 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3167 if (rb_block_pair_yield_optimizable())
3168 rb_hash_foreach(hash, each_pair_i_fast, 0);
3169 else
3170 rb_hash_foreach(hash, each_pair_i, 0);
3171 return hash;
3174 struct transform_keys_args{
3175 VALUE trans;
3176 VALUE result;
3177 int block_given;
3180 static int
3181 transform_keys_hash_i(VALUE key, VALUE value, VALUE transarg)
3183 struct transform_keys_args *p = (void *)transarg;
3184 VALUE trans = p->trans, result = p->result;
3185 VALUE new_key = rb_hash_lookup2(trans, key, Qundef);
3186 if (UNDEF_P(new_key)) {
3187 if (p->block_given)
3188 new_key = rb_yield(key);
3189 else
3190 new_key = key;
3192 rb_hash_aset(result, new_key, value);
3193 return ST_CONTINUE;
3196 static int
3197 transform_keys_i(VALUE key, VALUE value, VALUE result)
3199 VALUE new_key = rb_yield(key);
3200 rb_hash_aset(result, new_key, value);
3201 return ST_CONTINUE;
3205 * call-seq:
3206 * hash.transform_keys {|key| ... } -> new_hash
3207 * hash.transform_keys(hash2) -> new_hash
3208 * hash.transform_keys(hash2) {|other_key| ...} -> new_hash
3209 * hash.transform_keys -> new_enumerator
3211 * Returns a new +Hash+ object; each entry has:
3212 * * A key provided by the block.
3213 * * The value from +self+.
3215 * An optional hash argument can be provided to map keys to new keys.
3216 * Any key not given will be mapped using the provided block,
3217 * or remain the same if no block is given.
3219 * Transform keys:
3220 * h = {foo: 0, bar: 1, baz: 2}
3221 * h1 = h.transform_keys {|key| key.to_s }
3222 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3224 * h.transform_keys(foo: :bar, bar: :foo)
3225 * #=> {bar: 0, foo: 1, baz: 2}
3227 * h.transform_keys(foo: :hello, &:to_s)
3228 * #=> {:hello=>0, "bar"=>1, "baz"=>2}
3230 * Overwrites values for duplicate keys:
3231 * h = {foo: 0, bar: 1, baz: 2}
3232 * h1 = h.transform_keys {|key| :bat }
3233 * h1 # => {:bat=>2}
3235 * Returns a new Enumerator if no block given:
3236 * h = {foo: 0, bar: 1, baz: 2}
3237 * e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys>
3238 * h1 = e.each { |key| key.to_s }
3239 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3241 static VALUE
3242 rb_hash_transform_keys(int argc, VALUE *argv, VALUE hash)
3244 VALUE result;
3245 struct transform_keys_args transarg = {0};
3247 argc = rb_check_arity(argc, 0, 1);
3248 if (argc > 0) {
3249 transarg.trans = to_hash(argv[0]);
3250 transarg.block_given = rb_block_given_p();
3252 else {
3253 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3255 result = rb_hash_new();
3256 if (!RHASH_EMPTY_P(hash)) {
3257 if (transarg.trans) {
3258 transarg.result = result;
3259 rb_hash_foreach(hash, transform_keys_hash_i, (VALUE)&transarg);
3261 else {
3262 rb_hash_foreach(hash, transform_keys_i, result);
3266 return result;
3269 static int flatten_i(VALUE key, VALUE val, VALUE ary);
3272 * call-seq:
3273 * hash.transform_keys! {|key| ... } -> self
3274 * hash.transform_keys!(hash2) -> self
3275 * hash.transform_keys!(hash2) {|other_key| ...} -> self
3276 * hash.transform_keys! -> new_enumerator
3278 * Same as Hash#transform_keys but modifies the receiver in place
3279 * instead of returning a new hash.
3281 static VALUE
3282 rb_hash_transform_keys_bang(int argc, VALUE *argv, VALUE hash)
3284 VALUE trans = 0;
3285 int block_given = 0;
3287 argc = rb_check_arity(argc, 0, 1);
3288 if (argc > 0) {
3289 trans = to_hash(argv[0]);
3290 block_given = rb_block_given_p();
3292 else {
3293 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3295 rb_hash_modify_check(hash);
3296 if (!RHASH_TABLE_EMPTY_P(hash)) {
3297 long i;
3298 VALUE new_keys = hash_alloc(0);
3299 VALUE pairs = rb_ary_hidden_new(RHASH_SIZE(hash) * 2);
3300 rb_hash_foreach(hash, flatten_i, pairs);
3301 for (i = 0; i < RARRAY_LEN(pairs); i += 2) {
3302 VALUE key = RARRAY_AREF(pairs, i), new_key, val;
3304 if (!trans) {
3305 new_key = rb_yield(key);
3307 else if (!UNDEF_P(new_key = rb_hash_lookup2(trans, key, Qundef))) {
3308 /* use the transformed key */
3310 else if (block_given) {
3311 new_key = rb_yield(key);
3313 else {
3314 new_key = key;
3316 val = RARRAY_AREF(pairs, i+1);
3317 if (!hash_stlike_lookup(new_keys, key, NULL)) {
3318 rb_hash_stlike_delete(hash, &key, NULL);
3320 rb_hash_aset(hash, new_key, val);
3321 rb_hash_aset(new_keys, new_key, Qnil);
3323 rb_ary_clear(pairs);
3324 rb_hash_clear(new_keys);
3326 compact_after_delete(hash);
3327 return hash;
3330 static int
3331 transform_values_foreach_func(st_data_t key, st_data_t value, st_data_t argp, int error)
3333 return ST_REPLACE;
3336 static int
3337 transform_values_foreach_replace(st_data_t *key, st_data_t *value, st_data_t argp, int existing)
3339 VALUE new_value = rb_yield((VALUE)*value);
3340 VALUE hash = (VALUE)argp;
3341 rb_hash_modify(hash);
3342 RB_OBJ_WRITE(hash, value, new_value);
3343 return ST_CONTINUE;
3347 * call-seq:
3348 * hash.transform_values {|value| ... } -> new_hash
3349 * hash.transform_values -> new_enumerator
3351 * Returns a new +Hash+ object; each entry has:
3352 * * A key from +self+.
3353 * * A value provided by the block.
3355 * Transform values:
3356 * h = {foo: 0, bar: 1, baz: 2}
3357 * h1 = h.transform_values {|value| value * 100}
3358 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3360 * Returns a new Enumerator if no block given:
3361 * h = {foo: 0, bar: 1, baz: 2}
3362 * e = h.transform_values # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_values>
3363 * h1 = e.each { |value| value * 100}
3364 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3366 static VALUE
3367 rb_hash_transform_values(VALUE hash)
3369 VALUE result;
3371 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3372 result = hash_dup_with_compare_by_id(hash);
3373 SET_DEFAULT(result, Qnil);
3375 if (!RHASH_EMPTY_P(hash)) {
3376 rb_hash_stlike_foreach_with_replace(result, transform_values_foreach_func, transform_values_foreach_replace, result);
3377 compact_after_delete(result);
3380 return result;
3384 * call-seq:
3385 * hash.transform_values! {|value| ... } -> self
3386 * hash.transform_values! -> new_enumerator
3388 * Returns +self+, whose keys are unchanged, and whose values are determined by the given block.
3389 * h = {foo: 0, bar: 1, baz: 2}
3390 * h.transform_values! {|value| value * 100} # => {:foo=>0, :bar=>100, :baz=>200}
3392 * Returns a new Enumerator if no block given:
3393 * h = {foo: 0, bar: 1, baz: 2}
3394 * e = h.transform_values! # => #<Enumerator: {:foo=>0, :bar=>100, :baz=>200}:transform_values!>
3395 * h1 = e.each {|value| value * 100}
3396 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3398 static VALUE
3399 rb_hash_transform_values_bang(VALUE hash)
3401 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3402 rb_hash_modify_check(hash);
3404 if (!RHASH_TABLE_EMPTY_P(hash)) {
3405 rb_hash_stlike_foreach_with_replace(hash, transform_values_foreach_func, transform_values_foreach_replace, hash);
3408 return hash;
3411 static int
3412 to_a_i(VALUE key, VALUE value, VALUE ary)
3414 rb_ary_push(ary, rb_assoc_new(key, value));
3415 return ST_CONTINUE;
3419 * call-seq:
3420 * hash.to_a -> new_array
3422 * Returns a new Array of 2-element Array objects;
3423 * each nested Array contains a key-value pair from +self+:
3424 * h = {foo: 0, bar: 1, baz: 2}
3425 * h.to_a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3428 static VALUE
3429 rb_hash_to_a(VALUE hash)
3431 VALUE ary;
3433 ary = rb_ary_new_capa(RHASH_SIZE(hash));
3434 rb_hash_foreach(hash, to_a_i, ary);
3436 return ary;
3439 static int
3440 inspect_i(VALUE key, VALUE value, VALUE str)
3442 VALUE str2;
3444 str2 = rb_inspect(key);
3445 if (RSTRING_LEN(str) > 1) {
3446 rb_str_buf_cat_ascii(str, ", ");
3448 else {
3449 rb_enc_copy(str, str2);
3451 rb_str_buf_append(str, str2);
3452 rb_str_buf_cat_ascii(str, "=>");
3453 str2 = rb_inspect(value);
3454 rb_str_buf_append(str, str2);
3456 return ST_CONTINUE;
3459 static VALUE
3460 inspect_hash(VALUE hash, VALUE dummy, int recur)
3462 VALUE str;
3464 if (recur) return rb_usascii_str_new2("{...}");
3465 str = rb_str_buf_new2("{");
3466 rb_hash_foreach(hash, inspect_i, str);
3467 rb_str_buf_cat2(str, "}");
3469 return str;
3473 * call-seq:
3474 * hash.inspect -> new_string
3476 * Returns a new String containing the hash entries:
3478 * h = {foo: 0, bar: 1, baz: 2}
3479 * h.inspect # => "{:foo=>0, :bar=>1, :baz=>2}"
3483 static VALUE
3484 rb_hash_inspect(VALUE hash)
3486 if (RHASH_EMPTY_P(hash))
3487 return rb_usascii_str_new2("{}");
3488 return rb_exec_recursive(inspect_hash, hash, 0);
3492 * call-seq:
3493 * hash.to_hash -> self
3495 * Returns +self+.
3497 static VALUE
3498 rb_hash_to_hash(VALUE hash)
3500 return hash;
3503 VALUE
3504 rb_hash_set_pair(VALUE hash, VALUE arg)
3506 VALUE pair;
3508 pair = rb_check_array_type(arg);
3509 if (NIL_P(pair)) {
3510 rb_raise(rb_eTypeError, "wrong element type %s (expected array)",
3511 rb_builtin_class_name(arg));
3513 if (RARRAY_LEN(pair) != 2) {
3514 rb_raise(rb_eArgError, "element has wrong array length (expected 2, was %ld)",
3515 RARRAY_LEN(pair));
3517 rb_hash_aset(hash, RARRAY_AREF(pair, 0), RARRAY_AREF(pair, 1));
3518 return hash;
3521 static int
3522 to_h_i(VALUE key, VALUE value, VALUE hash)
3524 rb_hash_set_pair(hash, rb_yield_values(2, key, value));
3525 return ST_CONTINUE;
3528 static VALUE
3529 rb_hash_to_h_block(VALUE hash)
3531 VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
3532 rb_hash_foreach(hash, to_h_i, h);
3533 return h;
3537 * call-seq:
3538 * hash.to_h -> self or new_hash
3539 * hash.to_h {|key, value| ... } -> new_hash
3541 * For an instance of +Hash+, returns +self+.
3543 * For a subclass of +Hash+, returns a new +Hash+
3544 * containing the content of +self+.
3546 * When a block is given, returns a new +Hash+ object
3547 * whose content is based on the block;
3548 * the block should return a 2-element Array object
3549 * specifying the key-value pair to be included in the returned Array:
3550 * h = {foo: 0, bar: 1, baz: 2}
3551 * h1 = h.to_h {|key, value| [value, key] }
3552 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3555 static VALUE
3556 rb_hash_to_h(VALUE hash)
3558 if (rb_block_given_p()) {
3559 return rb_hash_to_h_block(hash);
3561 if (rb_obj_class(hash) != rb_cHash) {
3562 const VALUE flags = RBASIC(hash)->flags;
3563 hash = hash_dup(hash, rb_cHash, flags & RHASH_PROC_DEFAULT);
3565 return hash;
3568 static int
3569 keys_i(VALUE key, VALUE value, VALUE ary)
3571 rb_ary_push(ary, key);
3572 return ST_CONTINUE;
3576 * call-seq:
3577 * hash.keys -> new_array
3579 * Returns a new Array containing all keys in +self+:
3580 * h = {foo: 0, bar: 1, baz: 2}
3581 * h.keys # => [:foo, :bar, :baz]
3584 VALUE
3585 rb_hash_keys(VALUE hash)
3587 st_index_t size = RHASH_SIZE(hash);
3588 VALUE keys = rb_ary_new_capa(size);
3590 if (size == 0) return keys;
3592 if (ST_DATA_COMPATIBLE_P(VALUE)) {
3593 RARRAY_PTR_USE(keys, ptr, {
3594 if (RHASH_AR_TABLE_P(hash)) {
3595 size = ar_keys(hash, ptr, size);
3597 else {
3598 st_table *table = RHASH_ST_TABLE(hash);
3599 size = st_keys(table, ptr, size);
3602 rb_gc_writebarrier_remember(keys);
3603 rb_ary_set_len(keys, size);
3605 else {
3606 rb_hash_foreach(hash, keys_i, keys);
3609 return keys;
3612 static int
3613 values_i(VALUE key, VALUE value, VALUE ary)
3615 rb_ary_push(ary, value);
3616 return ST_CONTINUE;
3620 * call-seq:
3621 * hash.values -> new_array
3623 * Returns a new Array containing all values in +self+:
3624 * h = {foo: 0, bar: 1, baz: 2}
3625 * h.values # => [0, 1, 2]
3628 VALUE
3629 rb_hash_values(VALUE hash)
3631 VALUE values;
3632 st_index_t size = RHASH_SIZE(hash);
3634 values = rb_ary_new_capa(size);
3635 if (size == 0) return values;
3637 if (ST_DATA_COMPATIBLE_P(VALUE)) {
3638 if (RHASH_AR_TABLE_P(hash)) {
3639 rb_gc_writebarrier_remember(values);
3640 RARRAY_PTR_USE(values, ptr, {
3641 size = ar_values(hash, ptr, size);
3644 else if (RHASH_ST_TABLE_P(hash)) {
3645 st_table *table = RHASH_ST_TABLE(hash);
3646 rb_gc_writebarrier_remember(values);
3647 RARRAY_PTR_USE(values, ptr, {
3648 size = st_values(table, ptr, size);
3651 rb_ary_set_len(values, size);
3654 else {
3655 rb_hash_foreach(hash, values_i, values);
3658 return values;
3662 * call-seq:
3663 * hash.include?(key) -> true or false
3664 * hash.has_key?(key) -> true or false
3665 * hash.key?(key) -> true or false
3666 * hash.member?(key) -> true or false
3668 * Returns +true+ if +key+ is a key in +self+, otherwise +false+.
3671 VALUE
3672 rb_hash_has_key(VALUE hash, VALUE key)
3674 return RBOOL(hash_stlike_lookup(hash, key, NULL));
3677 static int
3678 rb_hash_search_value(VALUE key, VALUE value, VALUE arg)
3680 VALUE *data = (VALUE *)arg;
3682 if (rb_equal(value, data[1])) {
3683 data[0] = Qtrue;
3684 return ST_STOP;
3686 return ST_CONTINUE;
3690 * call-seq:
3691 * hash.has_value?(value) -> true or false
3692 * hash.value?(value) -> true or false
3694 * Returns +true+ if +value+ is a value in +self+, otherwise +false+.
3697 static VALUE
3698 rb_hash_has_value(VALUE hash, VALUE val)
3700 VALUE data[2];
3702 data[0] = Qfalse;
3703 data[1] = val;
3704 rb_hash_foreach(hash, rb_hash_search_value, (VALUE)data);
3705 return data[0];
3708 struct equal_data {
3709 VALUE result;
3710 VALUE hash;
3711 int eql;
3714 static int
3715 eql_i(VALUE key, VALUE val1, VALUE arg)
3717 struct equal_data *data = (struct equal_data *)arg;
3718 st_data_t val2;
3720 if (!hash_stlike_lookup(data->hash, key, &val2)) {
3721 data->result = Qfalse;
3722 return ST_STOP;
3724 else {
3725 if (!(data->eql ? rb_eql(val1, (VALUE)val2) : (int)rb_equal(val1, (VALUE)val2))) {
3726 data->result = Qfalse;
3727 return ST_STOP;
3729 return ST_CONTINUE;
3733 static VALUE
3734 recursive_eql(VALUE hash, VALUE dt, int recur)
3736 struct equal_data *data;
3738 if (recur) return Qtrue; /* Subtle! */
3739 data = (struct equal_data*)dt;
3740 data->result = Qtrue;
3741 rb_hash_foreach(hash, eql_i, dt);
3743 return data->result;
3746 static VALUE
3747 hash_equal(VALUE hash1, VALUE hash2, int eql)
3749 struct equal_data data;
3751 if (hash1 == hash2) return Qtrue;
3752 if (!RB_TYPE_P(hash2, T_HASH)) {
3753 if (!rb_respond_to(hash2, idTo_hash)) {
3754 return Qfalse;
3756 if (eql) {
3757 if (rb_eql(hash2, hash1)) {
3758 return Qtrue;
3760 else {
3761 return Qfalse;
3764 else {
3765 return rb_equal(hash2, hash1);
3768 if (RHASH_SIZE(hash1) != RHASH_SIZE(hash2))
3769 return Qfalse;
3770 if (!RHASH_TABLE_EMPTY_P(hash1) && !RHASH_TABLE_EMPTY_P(hash2)) {
3771 if (RHASH_TYPE(hash1) != RHASH_TYPE(hash2)) {
3772 return Qfalse;
3774 else {
3775 data.hash = hash2;
3776 data.eql = eql;
3777 return rb_exec_recursive_paired(recursive_eql, hash1, hash2, (VALUE)&data);
3781 #if 0
3782 if (!(rb_equal(RHASH_IFNONE(hash1), RHASH_IFNONE(hash2)) &&
3783 FL_TEST(hash1, RHASH_PROC_DEFAULT) == FL_TEST(hash2, RHASH_PROC_DEFAULT)))
3784 return Qfalse;
3785 #endif
3786 return Qtrue;
3790 * call-seq:
3791 * hash == object -> true or false
3793 * Returns +true+ if all of the following are true:
3794 * * +object+ is a +Hash+ object.
3795 * * +hash+ and +object+ have the same keys (regardless of order).
3796 * * For each key +key+, <tt>hash[key] == object[key]</tt>.
3798 * Otherwise, returns +false+.
3800 * Equal:
3801 * h1 = {foo: 0, bar: 1, baz: 2}
3802 * h2 = {foo: 0, bar: 1, baz: 2}
3803 * h1 == h2 # => true
3804 * h3 = {baz: 2, bar: 1, foo: 0}
3805 * h1 == h3 # => true
3808 static VALUE
3809 rb_hash_equal(VALUE hash1, VALUE hash2)
3811 return hash_equal(hash1, hash2, FALSE);
3815 * call-seq:
3816 * hash.eql?(object) -> true or false
3818 * Returns +true+ if all of the following are true:
3819 * * +object+ is a +Hash+ object.
3820 * * +hash+ and +object+ have the same keys (regardless of order).
3821 * * For each key +key+, <tt>h[key].eql?(object[key])</tt>.
3823 * Otherwise, returns +false+.
3825 * h1 = {foo: 0, bar: 1, baz: 2}
3826 * h2 = {foo: 0, bar: 1, baz: 2}
3827 * h1.eql? h2 # => true
3828 * h3 = {baz: 2, bar: 1, foo: 0}
3829 * h1.eql? h3 # => true
3832 static VALUE
3833 rb_hash_eql(VALUE hash1, VALUE hash2)
3835 return hash_equal(hash1, hash2, TRUE);
3838 static int
3839 hash_i(VALUE key, VALUE val, VALUE arg)
3841 st_index_t *hval = (st_index_t *)arg;
3842 st_index_t hdata[2];
3844 hdata[0] = rb_hash(key);
3845 hdata[1] = rb_hash(val);
3846 *hval ^= st_hash(hdata, sizeof(hdata), 0);
3847 return ST_CONTINUE;
3851 * call-seq:
3852 * hash.hash -> an_integer
3854 * Returns the Integer hash-code for the hash.
3856 * Two +Hash+ objects have the same hash-code if their content is the same
3857 * (regardless of order):
3858 * h1 = {foo: 0, bar: 1, baz: 2}
3859 * h2 = {baz: 2, bar: 1, foo: 0}
3860 * h2.hash == h1.hash # => true
3861 * h2.eql? h1 # => true
3864 static VALUE
3865 rb_hash_hash(VALUE hash)
3867 st_index_t size = RHASH_SIZE(hash);
3868 st_index_t hval = rb_hash_start(size);
3869 hval = rb_hash_uint(hval, (st_index_t)rb_hash_hash);
3870 if (size) {
3871 rb_hash_foreach(hash, hash_i, (VALUE)&hval);
3873 hval = rb_hash_end(hval);
3874 return ST2FIX(hval);
3877 static int
3878 rb_hash_invert_i(VALUE key, VALUE value, VALUE hash)
3880 rb_hash_aset(hash, value, key);
3881 return ST_CONTINUE;
3885 * call-seq:
3886 * hash.invert -> new_hash
3888 * Returns a new +Hash+ object with the each key-value pair inverted:
3889 * h = {foo: 0, bar: 1, baz: 2}
3890 * h1 = h.invert
3891 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3893 * Overwrites any repeated new keys:
3894 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
3895 * h = {foo: 0, bar: 0, baz: 0}
3896 * h.invert # => {0=>:baz}
3899 static VALUE
3900 rb_hash_invert(VALUE hash)
3902 VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
3904 rb_hash_foreach(hash, rb_hash_invert_i, h);
3905 return h;
3908 static int
3909 rb_hash_update_i(VALUE key, VALUE value, VALUE hash)
3911 rb_hash_aset(hash, key, value);
3912 return ST_CONTINUE;
3915 static int
3916 rb_hash_update_block_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
3918 st_data_t newvalue = arg->arg;
3920 if (existing) {
3921 newvalue = (st_data_t)rb_yield_values(3, (VALUE)*key, (VALUE)*value, (VALUE)newvalue);
3923 else if (RHASH_STRING_KEY_P(arg->hash, *key) && !RB_OBJ_FROZEN(*key)) {
3924 *key = rb_hash_key_str(*key);
3926 *value = newvalue;
3927 return ST_CONTINUE;
3930 NOINSERT_UPDATE_CALLBACK(rb_hash_update_block_callback)
3932 static int
3933 rb_hash_update_block_i(VALUE key, VALUE value, VALUE hash)
3935 RHASH_UPDATE(hash, key, rb_hash_update_block_callback, value);
3936 return ST_CONTINUE;
3940 * call-seq:
3941 * hash.merge! -> self
3942 * hash.merge!(*other_hashes) -> self
3943 * hash.merge!(*other_hashes) { |key, old_value, new_value| ... } -> self
3945 * Merges each of +other_hashes+ into +self+; returns +self+.
3947 * Each argument in +other_hashes+ must be a +Hash+.
3949 * With arguments and no block:
3950 * * Returns +self+, after the given hashes are merged into it.
3951 * * The given hashes are merged left to right.
3952 * * Each new entry is added at the end.
3953 * * Each duplicate-key entry's value overwrites the previous value.
3955 * Example:
3956 * h = {foo: 0, bar: 1, baz: 2}
3957 * h1 = {bat: 3, bar: 4}
3958 * h2 = {bam: 5, bat:6}
3959 * h.merge!(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
3961 * With arguments and a block:
3962 * * Returns +self+, after the given hashes are merged.
3963 * * The given hashes are merged left to right.
3964 * * Each new-key entry is added at the end.
3965 * * For each duplicate key:
3966 * * Calls the block with the key and the old and new values.
3967 * * The block's return value becomes the new value for the entry.
3969 * Example:
3970 * h = {foo: 0, bar: 1, baz: 2}
3971 * h1 = {bat: 3, bar: 4}
3972 * h2 = {bam: 5, bat:6}
3973 * h3 = h.merge!(h1, h2) { |key, old_value, new_value| old_value + new_value }
3974 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
3976 * With no arguments:
3977 * * Returns +self+, unmodified.
3978 * * The block, if given, is ignored.
3980 * Example:
3981 * h = {foo: 0, bar: 1, baz: 2}
3982 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
3983 * h1 = h.merge! { |key, old_value, new_value| raise 'Cannot happen' }
3984 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3987 static VALUE
3988 rb_hash_update(int argc, VALUE *argv, VALUE self)
3990 int i;
3991 bool block_given = rb_block_given_p();
3993 rb_hash_modify(self);
3994 for (i = 0; i < argc; i++){
3995 VALUE hash = to_hash(argv[i]);
3996 if (block_given) {
3997 rb_hash_foreach(hash, rb_hash_update_block_i, self);
3999 else {
4000 rb_hash_foreach(hash, rb_hash_update_i, self);
4003 return self;
4006 struct update_func_arg {
4007 VALUE hash;
4008 VALUE value;
4009 rb_hash_update_func *func;
4012 static int
4013 rb_hash_update_func_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
4015 struct update_func_arg *uf_arg = (struct update_func_arg *)arg->arg;
4016 VALUE newvalue = uf_arg->value;
4018 if (existing) {
4019 newvalue = (*uf_arg->func)((VALUE)*key, (VALUE)*value, newvalue);
4021 *value = newvalue;
4022 return ST_CONTINUE;
4025 NOINSERT_UPDATE_CALLBACK(rb_hash_update_func_callback)
4027 static int
4028 rb_hash_update_func_i(VALUE key, VALUE value, VALUE arg0)
4030 struct update_func_arg *arg = (struct update_func_arg *)arg0;
4031 VALUE hash = arg->hash;
4033 arg->value = value;
4034 RHASH_UPDATE(hash, key, rb_hash_update_func_callback, (VALUE)arg);
4035 return ST_CONTINUE;
4038 VALUE
4039 rb_hash_update_by(VALUE hash1, VALUE hash2, rb_hash_update_func *func)
4041 rb_hash_modify(hash1);
4042 hash2 = to_hash(hash2);
4043 if (func) {
4044 struct update_func_arg arg;
4045 arg.hash = hash1;
4046 arg.func = func;
4047 rb_hash_foreach(hash2, rb_hash_update_func_i, (VALUE)&arg);
4049 else {
4050 rb_hash_foreach(hash2, rb_hash_update_i, hash1);
4052 return hash1;
4056 * call-seq:
4057 * hash.merge -> copy_of_self
4058 * hash.merge(*other_hashes) -> new_hash
4059 * hash.merge(*other_hashes) { |key, old_value, new_value| ... } -> new_hash
4061 * Returns the new +Hash+ formed by merging each of +other_hashes+
4062 * into a copy of +self+.
4064 * Each argument in +other_hashes+ must be a +Hash+.
4066 * ---
4068 * With arguments and no block:
4069 * * Returns the new +Hash+ object formed by merging each successive
4070 * +Hash+ in +other_hashes+ into +self+.
4071 * * Each new-key entry is added at the end.
4072 * * Each duplicate-key entry's value overwrites the previous value.
4074 * Example:
4075 * h = {foo: 0, bar: 1, baz: 2}
4076 * h1 = {bat: 3, bar: 4}
4077 * h2 = {bam: 5, bat:6}
4078 * h.merge(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
4080 * With arguments and a block:
4081 * * Returns a new +Hash+ object that is the merge of +self+ and each given hash.
4082 * * The given hashes are merged left to right.
4083 * * Each new-key entry is added at the end.
4084 * * For each duplicate key:
4085 * * Calls the block with the key and the old and new values.
4086 * * The block's return value becomes the new value for the entry.
4088 * Example:
4089 * h = {foo: 0, bar: 1, baz: 2}
4090 * h1 = {bat: 3, bar: 4}
4091 * h2 = {bam: 5, bat:6}
4092 * h3 = h.merge(h1, h2) { |key, old_value, new_value| old_value + new_value }
4093 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
4095 * With no arguments:
4096 * * Returns a copy of +self+.
4097 * * The block, if given, is ignored.
4099 * Example:
4100 * h = {foo: 0, bar: 1, baz: 2}
4101 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
4102 * h1 = h.merge { |key, old_value, new_value| raise 'Cannot happen' }
4103 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
4106 static VALUE
4107 rb_hash_merge(int argc, VALUE *argv, VALUE self)
4109 return rb_hash_update(argc, argv, copy_compare_by_id(rb_hash_dup(self), self));
4112 static int
4113 assoc_cmp(VALUE a, VALUE b)
4115 return !RTEST(rb_equal(a, b));
4118 struct assoc_arg {
4119 st_table *tbl;
4120 st_data_t key;
4123 static VALUE
4124 assoc_lookup(VALUE arg)
4126 struct assoc_arg *p = (struct assoc_arg*)arg;
4127 st_data_t data;
4128 if (st_lookup(p->tbl, p->key, &data)) return (VALUE)data;
4129 return Qundef;
4132 static int
4133 assoc_i(VALUE key, VALUE val, VALUE arg)
4135 VALUE *args = (VALUE *)arg;
4137 if (RTEST(rb_equal(args[0], key))) {
4138 args[1] = rb_assoc_new(key, val);
4139 return ST_STOP;
4141 return ST_CONTINUE;
4145 * call-seq:
4146 * hash.assoc(key) -> new_array or nil
4148 * If the given +key+ is found, returns a 2-element Array containing that key and its value:
4149 * h = {foo: 0, bar: 1, baz: 2}
4150 * h.assoc(:bar) # => [:bar, 1]
4152 * Returns +nil+ if key +key+ is not found.
4155 static VALUE
4156 rb_hash_assoc(VALUE hash, VALUE key)
4158 VALUE args[2];
4160 if (RHASH_EMPTY_P(hash)) return Qnil;
4162 if (RHASH_ST_TABLE_P(hash) && !RHASH_IDENTHASH_P(hash)) {
4163 VALUE value = Qundef;
4164 st_table assoctable = *RHASH_ST_TABLE(hash);
4165 assoctable.type = &(struct st_hash_type){
4166 .compare = assoc_cmp,
4167 .hash = assoctable.type->hash,
4169 VALUE arg = (VALUE)&(struct assoc_arg){
4170 .tbl = &assoctable,
4171 .key = (st_data_t)key,
4174 if (RB_OBJ_FROZEN(hash)) {
4175 value = assoc_lookup(arg);
4177 else {
4178 hash_iter_lev_inc(hash);
4179 value = rb_ensure(assoc_lookup, arg, hash_foreach_ensure, hash);
4181 hash_verify(hash);
4182 if (!UNDEF_P(value)) return rb_assoc_new(key, value);
4185 args[0] = key;
4186 args[1] = Qnil;
4187 rb_hash_foreach(hash, assoc_i, (VALUE)args);
4188 return args[1];
4191 static int
4192 rassoc_i(VALUE key, VALUE val, VALUE arg)
4194 VALUE *args = (VALUE *)arg;
4196 if (RTEST(rb_equal(args[0], val))) {
4197 args[1] = rb_assoc_new(key, val);
4198 return ST_STOP;
4200 return ST_CONTINUE;
4204 * call-seq:
4205 * hash.rassoc(value) -> new_array or nil
4207 * Returns a new 2-element Array consisting of the key and value
4208 * of the first-found entry whose value is <tt>==</tt> to value
4209 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
4210 * h = {foo: 0, bar: 1, baz: 1}
4211 * h.rassoc(1) # => [:bar, 1]
4213 * Returns +nil+ if no such value found.
4216 static VALUE
4217 rb_hash_rassoc(VALUE hash, VALUE obj)
4219 VALUE args[2];
4221 args[0] = obj;
4222 args[1] = Qnil;
4223 rb_hash_foreach(hash, rassoc_i, (VALUE)args);
4224 return args[1];
4227 static int
4228 flatten_i(VALUE key, VALUE val, VALUE ary)
4230 VALUE pair[2];
4232 pair[0] = key;
4233 pair[1] = val;
4234 rb_ary_cat(ary, pair, 2);
4236 return ST_CONTINUE;
4240 * call-seq:
4241 * hash.flatten -> new_array
4242 * hash.flatten(level) -> new_array
4244 * Returns a new Array object that is a 1-dimensional flattening of +self+.
4246 * ---
4248 * By default, nested Arrays are not flattened:
4249 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4250 * h.flatten # => [:foo, 0, :bar, [:bat, 3], :baz, 2]
4252 * Takes the depth of recursive flattening from Integer argument +level+:
4253 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4254 * h.flatten(1) # => [:foo, 0, :bar, [:bat, [:baz, [:bat]]]]
4255 * h.flatten(2) # => [:foo, 0, :bar, :bat, [:baz, [:bat]]]
4256 * h.flatten(3) # => [:foo, 0, :bar, :bat, :baz, [:bat]]
4257 * h.flatten(4) # => [:foo, 0, :bar, :bat, :baz, :bat]
4259 * When +level+ is negative, flattens all nested Arrays:
4260 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4261 * h.flatten(-1) # => [:foo, 0, :bar, :bat, :baz, :bat]
4262 * h.flatten(-2) # => [:foo, 0, :bar, :bat, :baz, :bat]
4264 * When +level+ is zero, returns the equivalent of #to_a :
4265 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4266 * h.flatten(0) # => [[:foo, 0], [:bar, [:bat, 3]], [:baz, 2]]
4267 * h.flatten(0) == h.to_a # => true
4270 static VALUE
4271 rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
4273 VALUE ary;
4275 rb_check_arity(argc, 0, 1);
4277 if (argc) {
4278 int level = NUM2INT(argv[0]);
4280 if (level == 0) return rb_hash_to_a(hash);
4282 ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4283 rb_hash_foreach(hash, flatten_i, ary);
4284 level--;
4286 if (level > 0) {
4287 VALUE ary_flatten_level = INT2FIX(level);
4288 rb_funcallv(ary, id_flatten_bang, 1, &ary_flatten_level);
4290 else if (level < 0) {
4291 /* flatten recursively */
4292 rb_funcallv(ary, id_flatten_bang, 0, 0);
4295 else {
4296 ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4297 rb_hash_foreach(hash, flatten_i, ary);
4300 return ary;
4303 static int
4304 delete_if_nil(VALUE key, VALUE value, VALUE hash)
4306 if (NIL_P(value)) {
4307 return ST_DELETE;
4309 return ST_CONTINUE;
4313 * call-seq:
4314 * hash.compact -> new_hash
4316 * Returns a copy of +self+ with all +nil+-valued entries removed:
4317 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4318 * h1 = h.compact
4319 * h1 # => {:foo=>0, :baz=>2}
4322 static VALUE
4323 rb_hash_compact(VALUE hash)
4325 VALUE result = rb_hash_dup(hash);
4326 if (!RHASH_EMPTY_P(hash)) {
4327 rb_hash_foreach(result, delete_if_nil, result);
4328 compact_after_delete(result);
4330 else if (rb_hash_compare_by_id_p(hash)) {
4331 result = rb_hash_compare_by_id(result);
4333 return result;
4337 * call-seq:
4338 * hash.compact! -> self or nil
4340 * Returns +self+ with all its +nil+-valued entries removed (in place):
4341 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4342 * h.compact! # => {:foo=>0, :baz=>2}
4344 * Returns +nil+ if no entries were removed.
4347 static VALUE
4348 rb_hash_compact_bang(VALUE hash)
4350 st_index_t n;
4351 rb_hash_modify_check(hash);
4352 n = RHASH_SIZE(hash);
4353 if (n) {
4354 rb_hash_foreach(hash, delete_if_nil, hash);
4355 if (n != RHASH_SIZE(hash))
4356 return hash;
4358 return Qnil;
4362 * call-seq:
4363 * hash.compare_by_identity -> self
4365 * Sets +self+ to consider only identity in comparing keys;
4366 * two keys are considered the same only if they are the same object;
4367 * returns +self+.
4369 * By default, these two object are considered to be the same key,
4370 * so +s1+ will overwrite +s0+:
4371 * s0 = 'x'
4372 * s1 = 'x'
4373 * h = {}
4374 * h.compare_by_identity? # => false
4375 * h[s0] = 0
4376 * h[s1] = 1
4377 * h # => {"x"=>1}
4379 * After calling \#compare_by_identity, the keys are considered to be different,
4380 * and therefore do not overwrite each other:
4381 * h = {}
4382 * h.compare_by_identity # => {}
4383 * h.compare_by_identity? # => true
4384 * h[s0] = 0
4385 * h[s1] = 1
4386 * h # => {"x"=>0, "x"=>1}
4389 VALUE
4390 rb_hash_compare_by_id(VALUE hash)
4392 VALUE tmp;
4393 st_table *identtable;
4395 if (rb_hash_compare_by_id_p(hash)) return hash;
4397 rb_hash_modify_check(hash);
4398 if (hash_iterating_p(hash)) {
4399 rb_raise(rb_eRuntimeError, "compare_by_identity during iteration");
4402 if (RHASH_TABLE_EMPTY_P(hash)) {
4403 // Fast path: There's nothing to rehash, so we don't need a `tmp` table.
4404 // We're most likely an AR table, so this will need an allocation.
4405 ar_force_convert_table(hash, __FILE__, __LINE__);
4406 HASH_ASSERT(RHASH_ST_TABLE_P(hash));
4408 RHASH_ST_TABLE(hash)->type = &identhash;
4410 else {
4411 // Slow path: Need to rehash the members of `self` into a new
4412 // `tmp` table using the new `identhash` compare/hash functions.
4413 tmp = hash_alloc(0);
4414 hash_st_table_init(tmp, &identhash, RHASH_SIZE(hash));
4415 identtable = RHASH_ST_TABLE(tmp);
4417 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
4418 rb_hash_free(hash);
4420 // We know for sure `identtable` is an st table,
4421 // so we can skip `ar_force_convert_table` here.
4422 RHASH_ST_TABLE_SET(hash, identtable);
4423 RHASH_ST_CLEAR(tmp);
4426 return hash;
4430 * call-seq:
4431 * hash.compare_by_identity? -> true or false
4433 * Returns +true+ if #compare_by_identity has been called, +false+ otherwise.
4436 VALUE
4437 rb_hash_compare_by_id_p(VALUE hash)
4439 return RBOOL(RHASH_IDENTHASH_P(hash));
4442 VALUE
4443 rb_ident_hash_new(void)
4445 VALUE hash = rb_hash_new();
4446 hash_st_table_init(hash, &identhash, 0);
4447 return hash;
4450 VALUE
4451 rb_ident_hash_new_with_size(st_index_t size)
4453 VALUE hash = rb_hash_new();
4454 hash_st_table_init(hash, &identhash, size);
4455 return hash;
4458 st_table *
4459 rb_init_identtable(void)
4461 return st_init_table(&identhash);
4464 static int
4465 any_p_i(VALUE key, VALUE value, VALUE arg)
4467 VALUE ret = rb_yield(rb_assoc_new(key, value));
4468 if (RTEST(ret)) {
4469 *(VALUE *)arg = Qtrue;
4470 return ST_STOP;
4472 return ST_CONTINUE;
4475 static int
4476 any_p_i_fast(VALUE key, VALUE value, VALUE arg)
4478 VALUE ret = rb_yield_values(2, key, value);
4479 if (RTEST(ret)) {
4480 *(VALUE *)arg = Qtrue;
4481 return ST_STOP;
4483 return ST_CONTINUE;
4486 static int
4487 any_p_i_pattern(VALUE key, VALUE value, VALUE arg)
4489 VALUE ret = rb_funcall(((VALUE *)arg)[1], idEqq, 1, rb_assoc_new(key, value));
4490 if (RTEST(ret)) {
4491 *(VALUE *)arg = Qtrue;
4492 return ST_STOP;
4494 return ST_CONTINUE;
4498 * call-seq:
4499 * hash.any? -> true or false
4500 * hash.any?(object) -> true or false
4501 * hash.any? {|key, value| ... } -> true or false
4503 * Returns +true+ if any element satisfies a given criterion;
4504 * +false+ otherwise.
4506 * If +self+ has no element, returns +false+ and argument or block
4507 * are not used.
4509 * With no argument and no block,
4510 * returns +true+ if +self+ is non-empty; +false+ if empty.
4512 * With argument +object+ and no block,
4513 * returns +true+ if for any key +key+
4514 * <tt>h.assoc(key) == object</tt>:
4515 * h = {foo: 0, bar: 1, baz: 2}
4516 * h.any?([:bar, 1]) # => true
4517 * h.any?([:bar, 0]) # => false
4518 * h.any?([:baz, 1]) # => false
4520 * With no argument and a block,
4521 * calls the block with each key-value pair;
4522 * returns +true+ if the block returns any truthy value,
4523 * +false+ otherwise:
4524 * h = {foo: 0, bar: 1, baz: 2}
4525 * h.any? {|key, value| value < 3 } # => true
4526 * h.any? {|key, value| value > 3 } # => false
4528 * Related: Enumerable#any?
4531 static VALUE
4532 rb_hash_any_p(int argc, VALUE *argv, VALUE hash)
4534 VALUE args[2];
4535 args[0] = Qfalse;
4537 rb_check_arity(argc, 0, 1);
4538 if (RHASH_EMPTY_P(hash)) return Qfalse;
4539 if (argc) {
4540 if (rb_block_given_p()) {
4541 rb_warn("given block not used");
4543 args[1] = argv[0];
4545 rb_hash_foreach(hash, any_p_i_pattern, (VALUE)args);
4547 else {
4548 if (!rb_block_given_p()) {
4549 /* yields pairs, never false */
4550 return Qtrue;
4552 if (rb_block_pair_yield_optimizable())
4553 rb_hash_foreach(hash, any_p_i_fast, (VALUE)args);
4554 else
4555 rb_hash_foreach(hash, any_p_i, (VALUE)args);
4557 return args[0];
4561 * call-seq:
4562 * hash.dig(key, *identifiers) -> object
4564 * Finds and returns the object in nested objects
4565 * that is specified by +key+ and +identifiers+.
4566 * The nested objects may be instances of various classes.
4567 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
4569 * Nested Hashes:
4570 * h = {foo: {bar: {baz: 2}}}
4571 * h.dig(:foo) # => {:bar=>{:baz=>2}}
4572 * h.dig(:foo, :bar) # => {:baz=>2}
4573 * h.dig(:foo, :bar, :baz) # => 2
4574 * h.dig(:foo, :bar, :BAZ) # => nil
4576 * Nested Hashes and Arrays:
4577 * h = {foo: {bar: [:a, :b, :c]}}
4578 * h.dig(:foo, :bar, 2) # => :c
4580 * This method will use the {default values}[rdoc-ref:Hash@Default+Values]
4581 * for keys that are not present:
4582 * h = {foo: {bar: [:a, :b, :c]}}
4583 * h.dig(:hello) # => nil
4584 * h.default_proc = -> (hash, _key) { hash }
4585 * h.dig(:hello, :world) # => h
4586 * h.dig(:hello, :world, :foo, :bar, 2) # => :c
4589 static VALUE
4590 rb_hash_dig(int argc, VALUE *argv, VALUE self)
4592 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
4593 self = rb_hash_aref(self, *argv);
4594 if (!--argc) return self;
4595 ++argv;
4596 return rb_obj_dig(argc, argv, self, Qnil);
4599 static int
4600 hash_le_i(VALUE key, VALUE value, VALUE arg)
4602 VALUE *args = (VALUE *)arg;
4603 VALUE v = rb_hash_lookup2(args[0], key, Qundef);
4604 if (!UNDEF_P(v) && rb_equal(value, v)) return ST_CONTINUE;
4605 args[1] = Qfalse;
4606 return ST_STOP;
4609 static VALUE
4610 hash_le(VALUE hash1, VALUE hash2)
4612 VALUE args[2];
4613 args[0] = hash2;
4614 args[1] = Qtrue;
4615 rb_hash_foreach(hash1, hash_le_i, (VALUE)args);
4616 return args[1];
4620 * call-seq:
4621 * hash <= other_hash -> true or false
4623 * Returns +true+ if +hash+ is a subset of +other_hash+, +false+ otherwise:
4624 * h1 = {foo: 0, bar: 1}
4625 * h2 = {foo: 0, bar: 1, baz: 2}
4626 * h1 <= h2 # => true
4627 * h2 <= h1 # => false
4628 * h1 <= h1 # => true
4630 static VALUE
4631 rb_hash_le(VALUE hash, VALUE other)
4633 other = to_hash(other);
4634 if (RHASH_SIZE(hash) > RHASH_SIZE(other)) return Qfalse;
4635 return hash_le(hash, other);
4639 * call-seq:
4640 * hash < other_hash -> true or false
4642 * Returns +true+ if +hash+ is a proper subset of +other_hash+, +false+ otherwise:
4643 * h1 = {foo: 0, bar: 1}
4644 * h2 = {foo: 0, bar: 1, baz: 2}
4645 * h1 < h2 # => true
4646 * h2 < h1 # => false
4647 * h1 < h1 # => false
4649 static VALUE
4650 rb_hash_lt(VALUE hash, VALUE other)
4652 other = to_hash(other);
4653 if (RHASH_SIZE(hash) >= RHASH_SIZE(other)) return Qfalse;
4654 return hash_le(hash, other);
4658 * call-seq:
4659 * hash >= other_hash -> true or false
4661 * Returns +true+ if +hash+ is a superset of +other_hash+, +false+ otherwise:
4662 * h1 = {foo: 0, bar: 1, baz: 2}
4663 * h2 = {foo: 0, bar: 1}
4664 * h1 >= h2 # => true
4665 * h2 >= h1 # => false
4666 * h1 >= h1 # => true
4668 static VALUE
4669 rb_hash_ge(VALUE hash, VALUE other)
4671 other = to_hash(other);
4672 if (RHASH_SIZE(hash) < RHASH_SIZE(other)) return Qfalse;
4673 return hash_le(other, hash);
4677 * call-seq:
4678 * hash > other_hash -> true or false
4680 * Returns +true+ if +hash+ is a proper superset of +other_hash+, +false+ otherwise:
4681 * h1 = {foo: 0, bar: 1, baz: 2}
4682 * h2 = {foo: 0, bar: 1}
4683 * h1 > h2 # => true
4684 * h2 > h1 # => false
4685 * h1 > h1 # => false
4687 static VALUE
4688 rb_hash_gt(VALUE hash, VALUE other)
4690 other = to_hash(other);
4691 if (RHASH_SIZE(hash) <= RHASH_SIZE(other)) return Qfalse;
4692 return hash_le(other, hash);
4695 static VALUE
4696 hash_proc_call(RB_BLOCK_CALL_FUNC_ARGLIST(key, hash))
4698 rb_check_arity(argc, 1, 1);
4699 return rb_hash_aref(hash, *argv);
4703 * call-seq:
4704 * hash.to_proc -> proc
4706 * Returns a Proc object that maps a key to its value:
4707 * h = {foo: 0, bar: 1, baz: 2}
4708 * proc = h.to_proc
4709 * proc.class # => Proc
4710 * proc.call(:foo) # => 0
4711 * proc.call(:bar) # => 1
4712 * proc.call(:nosuch) # => nil
4714 static VALUE
4715 rb_hash_to_proc(VALUE hash)
4717 return rb_func_lambda_new(hash_proc_call, hash, 1, 1);
4720 /* :nodoc: */
4721 static VALUE
4722 rb_hash_deconstruct_keys(VALUE hash, VALUE keys)
4724 return hash;
4727 static int
4728 add_new_i(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
4730 VALUE *args = (VALUE *)arg;
4731 if (existing) return ST_STOP;
4732 RB_OBJ_WRITTEN(args[0], Qundef, (VALUE)*key);
4733 RB_OBJ_WRITE(args[0], (VALUE *)val, args[1]);
4734 return ST_CONTINUE;
4738 * add +key+ to +val+ pair if +hash+ does not contain +key+.
4739 * returns non-zero if +key+ was contained.
4742 rb_hash_add_new_element(VALUE hash, VALUE key, VALUE val)
4744 st_table *tbl;
4745 int ret = 0;
4746 VALUE args[2];
4747 args[0] = hash;
4748 args[1] = val;
4750 if (RHASH_AR_TABLE_P(hash)) {
4751 ret = ar_update(hash, (st_data_t)key, add_new_i, (st_data_t)args);
4752 if (ret != -1) {
4753 return ret;
4755 ar_force_convert_table(hash, __FILE__, __LINE__);
4758 tbl = RHASH_TBL_RAW(hash);
4759 return st_update(tbl, (st_data_t)key, add_new_i, (st_data_t)args);
4763 static st_data_t
4764 key_stringify(VALUE key)
4766 return (rb_obj_class(key) == rb_cString && !RB_OBJ_FROZEN(key)) ?
4767 rb_hash_key_str(key) : key;
4770 static void
4771 ar_bulk_insert(VALUE hash, long argc, const VALUE *argv)
4773 long i;
4774 for (i = 0; i < argc; ) {
4775 st_data_t k = key_stringify(argv[i++]);
4776 st_data_t v = argv[i++];
4777 ar_insert(hash, k, v);
4778 RB_OBJ_WRITTEN(hash, Qundef, k);
4779 RB_OBJ_WRITTEN(hash, Qundef, v);
4783 void
4784 rb_hash_bulk_insert(long argc, const VALUE *argv, VALUE hash)
4786 HASH_ASSERT(argc % 2 == 0);
4787 if (argc > 0) {
4788 st_index_t size = argc / 2;
4790 if (RHASH_AR_TABLE_P(hash) &&
4791 (RHASH_AR_TABLE_SIZE(hash) + size <= RHASH_AR_TABLE_MAX_SIZE)) {
4792 ar_bulk_insert(hash, argc, argv);
4794 else {
4795 rb_hash_bulk_insert_into_st_table(argc, argv, hash);
4800 static char **origenviron;
4801 #ifdef _WIN32
4802 #define GET_ENVIRON(e) ((e) = rb_w32_get_environ())
4803 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
4804 static char **my_environ;
4805 #undef environ
4806 #define environ my_environ
4807 #undef getenv
4808 #define getenv(n) rb_w32_ugetenv(n)
4809 #elif defined(__APPLE__)
4810 #undef environ
4811 #define environ (*_NSGetEnviron())
4812 #define GET_ENVIRON(e) (e)
4813 #define FREE_ENVIRON(e)
4814 #else
4815 extern char **environ;
4816 #define GET_ENVIRON(e) (e)
4817 #define FREE_ENVIRON(e)
4818 #endif
4819 #ifdef ENV_IGNORECASE
4820 #define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
4821 #define ENVNMATCH(s1, s2, n) (STRNCASECMP((s1), (s2), (n)) == 0)
4822 #else
4823 #define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
4824 #define ENVNMATCH(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
4825 #endif
4827 #define ENV_LOCK() RB_VM_LOCK_ENTER()
4828 #define ENV_UNLOCK() RB_VM_LOCK_LEAVE()
4830 static inline rb_encoding *
4831 env_encoding(void)
4833 #ifdef _WIN32
4834 return rb_utf8_encoding();
4835 #else
4836 return rb_locale_encoding();
4837 #endif
4840 static VALUE
4841 env_enc_str_new(const char *ptr, long len, rb_encoding *enc)
4843 VALUE str = rb_external_str_new_with_enc(ptr, len, enc);
4845 rb_obj_freeze(str);
4846 return str;
4849 static VALUE
4850 env_str_new(const char *ptr, long len)
4852 return env_enc_str_new(ptr, len, env_encoding());
4855 static VALUE
4856 env_str_new2(const char *ptr)
4858 if (!ptr) return Qnil;
4859 return env_str_new(ptr, strlen(ptr));
4862 static VALUE
4863 getenv_with_lock(const char *name)
4865 VALUE ret;
4866 ENV_LOCK();
4868 const char *val = getenv(name);
4869 ret = env_str_new2(val);
4871 ENV_UNLOCK();
4872 return ret;
4875 static bool
4876 has_env_with_lock(const char *name)
4878 const char *val;
4880 ENV_LOCK();
4882 val = getenv(name);
4884 ENV_UNLOCK();
4886 return val ? true : false;
4889 static const char TZ_ENV[] = "TZ";
4891 static void *
4892 get_env_cstr(VALUE str, const char *name)
4894 char *var;
4895 rb_encoding *enc = rb_enc_get(str);
4896 if (!rb_enc_asciicompat(enc)) {
4897 rb_raise(rb_eArgError, "bad environment variable %s: ASCII incompatible encoding: %s",
4898 name, rb_enc_name(enc));
4900 var = RSTRING_PTR(str);
4901 if (memchr(var, '\0', RSTRING_LEN(str))) {
4902 rb_raise(rb_eArgError, "bad environment variable %s: contains null byte", name);
4904 return rb_str_fill_terminator(str, 1); /* ASCII compatible */
4907 #define get_env_ptr(var, val) \
4908 (var = get_env_cstr(val, #var))
4910 static inline const char *
4911 env_name(volatile VALUE *s)
4913 const char *name;
4914 StringValue(*s);
4915 get_env_ptr(name, *s);
4916 return name;
4919 #define env_name(s) env_name(&(s))
4921 static VALUE env_aset(VALUE nm, VALUE val);
4923 static void
4924 reset_by_modified_env(const char *nam)
4927 * ENV['TZ'] = nil has a special meaning.
4928 * TZ is no longer considered up-to-date and ruby call tzset() as needed.
4929 * It could be useful if sysadmin change /etc/localtime.
4930 * This hack might works only on Linux glibc.
4932 if (ENVMATCH(nam, TZ_ENV)) {
4933 ruby_reset_timezone();
4937 static VALUE
4938 env_delete(VALUE name)
4940 const char *nam = env_name(name);
4941 reset_by_modified_env(nam);
4942 VALUE val = getenv_with_lock(nam);
4944 if (!NIL_P(val)) {
4945 ruby_setenv(nam, 0);
4947 return val;
4951 * call-seq:
4952 * ENV.delete(name) -> value
4953 * ENV.delete(name) { |name| block } -> value
4954 * ENV.delete(missing_name) -> nil
4955 * ENV.delete(missing_name) { |name| block } -> block_value
4957 * Deletes the environment variable with +name+ if it exists and returns its value:
4958 * ENV['foo'] = '0'
4959 * ENV.delete('foo') # => '0'
4961 * If a block is not given and the named environment variable does not exist, returns +nil+.
4963 * If a block given and the environment variable does not exist,
4964 * yields +name+ to the block and returns the value of the block:
4965 * ENV.delete('foo') { |name| name * 2 } # => "foofoo"
4967 * If a block given and the environment variable exists,
4968 * deletes the environment variable and returns its value (ignoring the block):
4969 * ENV['foo'] = '0'
4970 * ENV.delete('foo') { |name| raise 'ignored' } # => "0"
4972 * Raises an exception if +name+ is invalid.
4973 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
4975 static VALUE
4976 env_delete_m(VALUE obj, VALUE name)
4978 VALUE val;
4980 val = env_delete(name);
4981 if (NIL_P(val) && rb_block_given_p()) val = rb_yield(name);
4982 return val;
4986 * call-seq:
4987 * ENV[name] -> value
4989 * Returns the value for the environment variable +name+ if it exists:
4990 * ENV['foo'] = '0'
4991 * ENV['foo'] # => "0"
4992 * Returns +nil+ if the named variable does not exist.
4994 * Raises an exception if +name+ is invalid.
4995 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
4997 static VALUE
4998 rb_f_getenv(VALUE obj, VALUE name)
5000 const char *nam = env_name(name);
5001 VALUE env = getenv_with_lock(nam);
5002 return env;
5006 * call-seq:
5007 * ENV.fetch(name) -> value
5008 * ENV.fetch(name, default) -> value
5009 * ENV.fetch(name) { |name| block } -> value
5011 * If +name+ is the name of an environment variable, returns its value:
5012 * ENV['foo'] = '0'
5013 * ENV.fetch('foo') # => '0'
5014 * Otherwise if a block is given (but not a default value),
5015 * yields +name+ to the block and returns the block's return value:
5016 * ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string
5017 * Otherwise if a default value is given (but not a block), returns the default value:
5018 * ENV.delete('foo')
5019 * ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string
5020 * If the environment variable does not exist and both default and block are given,
5021 * issues a warning ("warning: block supersedes default value argument"),
5022 * yields +name+ to the block, and returns the block's return value:
5023 * ENV.fetch('foo', :default) { |name| :block_return } # => :block_return
5024 * Raises KeyError if +name+ is valid, but not found,
5025 * and neither default value nor block is given:
5026 * ENV.fetch('foo') # Raises KeyError (key not found: "foo")
5027 * Raises an exception if +name+ is invalid.
5028 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5030 static VALUE
5031 env_fetch(int argc, VALUE *argv, VALUE _)
5033 VALUE key;
5034 long block_given;
5035 const char *nam;
5036 VALUE env;
5038 rb_check_arity(argc, 1, 2);
5039 key = argv[0];
5040 block_given = rb_block_given_p();
5041 if (block_given && argc == 2) {
5042 rb_warn("block supersedes default value argument");
5044 nam = env_name(key);
5045 env = getenv_with_lock(nam);
5047 if (NIL_P(env)) {
5048 if (block_given) return rb_yield(key);
5049 if (argc == 1) {
5050 rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE"\"", key), envtbl, key);
5052 return argv[1];
5054 return env;
5057 #if defined(_WIN32) || (defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
5058 #elif defined __sun
5059 static int
5060 in_origenv(const char *str)
5062 char **env;
5063 for (env = origenviron; *env; ++env) {
5064 if (*env == str) return 1;
5066 return 0;
5068 #else
5069 static int
5070 envix(const char *nam)
5072 // should be locked
5074 register int i, len = strlen(nam);
5075 char **env;
5077 env = GET_ENVIRON(environ);
5078 for (i = 0; env[i]; i++) {
5079 if (ENVNMATCH(env[i],nam,len) && env[i][len] == '=')
5080 break; /* memcmp must come first to avoid */
5081 } /* potential SEGV's */
5082 FREE_ENVIRON(environ);
5083 return i;
5085 #endif
5087 #if defined(_WIN32)
5088 static size_t
5089 getenvsize(const WCHAR* p)
5091 const WCHAR* porg = p;
5092 while (*p++) p += lstrlenW(p) + 1;
5093 return p - porg + 1;
5096 static size_t
5097 getenvblocksize(void)
5099 #ifdef _MAX_ENV
5100 return _MAX_ENV;
5101 #else
5102 return 32767;
5103 #endif
5106 static int
5107 check_envsize(size_t n)
5109 if (_WIN32_WINNT < 0x0600 && rb_w32_osver() < 6) {
5110 /* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653(v=vs.85).aspx */
5111 /* Windows Server 2003 and Windows XP: The maximum size of the
5112 * environment block for the process is 32,767 characters. */
5113 WCHAR* p = GetEnvironmentStringsW();
5114 if (!p) return -1; /* never happen */
5115 n += getenvsize(p);
5116 FreeEnvironmentStringsW(p);
5117 if (n >= getenvblocksize()) {
5118 return -1;
5121 return 0;
5123 #endif
5125 #if defined(_WIN32) || \
5126 (defined(__sun) && !(defined(HAVE_SETENV) && defined(HAVE_UNSETENV)))
5128 NORETURN(static void invalid_envname(const char *name));
5130 static void
5131 invalid_envname(const char *name)
5133 rb_syserr_fail_str(EINVAL, rb_sprintf("ruby_setenv(%s)", name));
5136 static const char *
5137 check_envname(const char *name)
5139 if (strchr(name, '=')) {
5140 invalid_envname(name);
5142 return name;
5144 #endif
5146 void
5147 ruby_setenv(const char *name, const char *value)
5149 #if defined(_WIN32)
5150 # if defined(MINGW_HAS_SECURE_API) || RUBY_MSVCRT_VERSION >= 80
5151 # define HAVE__WPUTENV_S 1
5152 # endif
5153 VALUE buf;
5154 WCHAR *wname;
5155 WCHAR *wvalue = 0;
5156 int failed = 0;
5157 int len;
5158 check_envname(name);
5159 len = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0);
5160 if (value) {
5161 int len2;
5162 len2 = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0);
5163 if (check_envsize((size_t)len + len2)) { /* len and len2 include '\0' */
5164 goto fail; /* 2 for '=' & '\0' */
5166 wname = ALLOCV_N(WCHAR, buf, len + len2);
5167 wvalue = wname + len;
5168 MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len);
5169 MultiByteToWideChar(CP_UTF8, 0, value, -1, wvalue, len2);
5170 #ifndef HAVE__WPUTENV_S
5171 wname[len-1] = L'=';
5172 #endif
5174 else {
5175 wname = ALLOCV_N(WCHAR, buf, len + 1);
5176 MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len);
5177 wvalue = wname + len;
5178 *wvalue = L'\0';
5179 #ifndef HAVE__WPUTENV_S
5180 wname[len-1] = L'=';
5181 #endif
5184 ENV_LOCK();
5186 #ifndef HAVE__WPUTENV_S
5187 failed = _wputenv(wname);
5188 #else
5189 failed = _wputenv_s(wname, wvalue);
5190 #endif
5192 ENV_UNLOCK();
5194 ALLOCV_END(buf);
5195 /* even if putenv() failed, clean up and try to delete the
5196 * variable from the system area. */
5197 if (!value || !*value) {
5198 /* putenv() doesn't handle empty value */
5199 if (!SetEnvironmentVariable(name, value) &&
5200 GetLastError() != ERROR_ENVVAR_NOT_FOUND) goto fail;
5202 if (failed) {
5203 fail:
5204 invalid_envname(name);
5206 #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
5207 if (value) {
5208 int ret;
5209 ENV_LOCK();
5211 ret = setenv(name, value, 1);
5213 ENV_UNLOCK();
5215 if (ret) rb_sys_fail_sprintf("setenv(%s)", name);
5217 else {
5218 #ifdef VOID_UNSETENV
5219 ENV_LOCK();
5221 unsetenv(name);
5223 ENV_UNLOCK();
5224 #else
5225 int ret;
5226 ENV_LOCK();
5228 ret = unsetenv(name);
5230 ENV_UNLOCK();
5232 if (ret) rb_sys_fail_sprintf("unsetenv(%s)", name);
5233 #endif
5235 #elif defined __sun
5236 /* Solaris 9 (or earlier) does not have setenv(3C) and unsetenv(3C). */
5237 /* The below code was tested on Solaris 10 by:
5238 % ./configure ac_cv_func_setenv=no ac_cv_func_unsetenv=no
5240 size_t len, mem_size;
5241 char **env_ptr, *str, *mem_ptr;
5243 check_envname(name);
5244 len = strlen(name);
5245 if (value) {
5246 mem_size = len + strlen(value) + 2;
5247 mem_ptr = malloc(mem_size);
5248 if (mem_ptr == NULL)
5249 rb_sys_fail_sprintf("malloc(%"PRIuSIZE")", mem_size);
5250 snprintf(mem_ptr, mem_size, "%s=%s", name, value);
5253 ENV_LOCK();
5255 for (env_ptr = GET_ENVIRON(environ); (str = *env_ptr) != 0; ++env_ptr) {
5256 if (!strncmp(str, name, len) && str[len] == '=') {
5257 if (!in_origenv(str)) free(str);
5258 while ((env_ptr[0] = env_ptr[1]) != 0) env_ptr++;
5259 break;
5263 ENV_UNLOCK();
5265 if (value) {
5266 int ret;
5267 ENV_LOCK();
5269 ret = putenv(mem_ptr);
5271 ENV_UNLOCK();
5273 if (ret) {
5274 free(mem_ptr);
5275 rb_sys_fail_sprintf("putenv(%s)", name);
5278 #else /* WIN32 */
5279 size_t len;
5280 int i;
5282 ENV_LOCK();
5284 i = envix(name); /* where does it go? */
5286 if (environ == origenviron) { /* need we copy environment? */
5287 int j;
5288 int max;
5289 char **tmpenv;
5291 for (max = i; environ[max]; max++) ;
5292 tmpenv = ALLOC_N(char*, max+2);
5293 for (j=0; j<max; j++) /* copy environment */
5294 tmpenv[j] = ruby_strdup(environ[j]);
5295 tmpenv[max] = 0;
5296 environ = tmpenv; /* tell exec where it is now */
5299 if (environ[i]) {
5300 char **envp = origenviron;
5301 while (*envp && *envp != environ[i]) envp++;
5302 if (!*envp)
5303 xfree(environ[i]);
5304 if (!value) {
5305 while (environ[i]) {
5306 environ[i] = environ[i+1];
5307 i++;
5309 goto finish;
5312 else { /* does not exist yet */
5313 if (!value) goto finish;
5314 REALLOC_N(environ, char*, i+2); /* just expand it a bit */
5315 environ[i+1] = 0; /* make sure it's null terminated */
5318 len = strlen(name) + strlen(value) + 2;
5319 environ[i] = ALLOC_N(char, len);
5320 snprintf(environ[i],len,"%s=%s",name,value); /* all that work just for this */
5322 finish:;
5324 ENV_UNLOCK();
5325 #endif /* WIN32 */
5328 void
5329 ruby_unsetenv(const char *name)
5331 ruby_setenv(name, 0);
5335 * call-seq:
5336 * ENV[name] = value -> value
5337 * ENV.store(name, value) -> value
5339 * Creates, updates, or deletes the named environment variable, returning the value.
5340 * Both +name+ and +value+ may be instances of String.
5341 * See {Valid Names and Values}[rdoc-ref:ENV@Valid+Names+and+Values].
5343 * - If the named environment variable does not exist:
5344 * - If +value+ is +nil+, does nothing.
5345 * ENV.clear
5346 * ENV['foo'] = nil # => nil
5347 * ENV.include?('foo') # => false
5348 * ENV.store('bar', nil) # => nil
5349 * ENV.include?('bar') # => false
5350 * - If +value+ is not +nil+, creates the environment variable with +name+ and +value+:
5351 * # Create 'foo' using ENV.[]=.
5352 * ENV['foo'] = '0' # => '0'
5353 * ENV['foo'] # => '0'
5354 * # Create 'bar' using ENV.store.
5355 * ENV.store('bar', '1') # => '1'
5356 * ENV['bar'] # => '1'
5357 * - If the named environment variable exists:
5358 * - If +value+ is not +nil+, updates the environment variable with value +value+:
5359 * # Update 'foo' using ENV.[]=.
5360 * ENV['foo'] = '2' # => '2'
5361 * ENV['foo'] # => '2'
5362 * # Update 'bar' using ENV.store.
5363 * ENV.store('bar', '3') # => '3'
5364 * ENV['bar'] # => '3'
5365 * - If +value+ is +nil+, deletes the environment variable:
5366 * # Delete 'foo' using ENV.[]=.
5367 * ENV['foo'] = nil # => nil
5368 * ENV.include?('foo') # => false
5369 * # Delete 'bar' using ENV.store.
5370 * ENV.store('bar', nil) # => nil
5371 * ENV.include?('bar') # => false
5373 * Raises an exception if +name+ or +value+ is invalid.
5374 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5376 static VALUE
5377 env_aset_m(VALUE obj, VALUE nm, VALUE val)
5379 return env_aset(nm, val);
5382 static VALUE
5383 env_aset(VALUE nm, VALUE val)
5385 char *name, *value;
5387 if (NIL_P(val)) {
5388 env_delete(nm);
5389 return Qnil;
5391 StringValue(nm);
5392 StringValue(val);
5393 /* nm can be modified in `val.to_str`, don't get `name` before
5394 * check for `val` */
5395 get_env_ptr(name, nm);
5396 get_env_ptr(value, val);
5398 ruby_setenv(name, value);
5399 reset_by_modified_env(name);
5400 return val;
5403 static VALUE
5404 env_keys(int raw)
5406 rb_encoding *enc = raw ? 0 : rb_locale_encoding();
5407 VALUE ary = rb_ary_new();
5409 ENV_LOCK();
5411 char **env = GET_ENVIRON(environ);
5412 while (*env) {
5413 char *s = strchr(*env, '=');
5414 if (s) {
5415 const char *p = *env;
5416 size_t l = s - p;
5417 VALUE e = raw ? rb_utf8_str_new(p, l) : env_enc_str_new(p, l, enc);
5418 rb_ary_push(ary, e);
5420 env++;
5422 FREE_ENVIRON(environ);
5424 ENV_UNLOCK();
5426 return ary;
5430 * call-seq:
5431 * ENV.keys -> array of names
5433 * Returns all variable names in an Array:
5434 * ENV.replace('foo' => '0', 'bar' => '1')
5435 * ENV.keys # => ['bar', 'foo']
5436 * The order of the names is OS-dependent.
5437 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
5439 * Returns the empty Array if ENV is empty.
5442 static VALUE
5443 env_f_keys(VALUE _)
5445 return env_keys(FALSE);
5448 static VALUE
5449 rb_env_size(VALUE ehash, VALUE args, VALUE eobj)
5451 char **env;
5452 long cnt = 0;
5454 ENV_LOCK();
5456 env = GET_ENVIRON(environ);
5457 for (; *env ; ++env) {
5458 if (strchr(*env, '=')) {
5459 cnt++;
5462 FREE_ENVIRON(environ);
5464 ENV_UNLOCK();
5466 return LONG2FIX(cnt);
5470 * call-seq:
5471 * ENV.each_key { |name| block } -> ENV
5472 * ENV.each_key -> an_enumerator
5474 * Yields each environment variable name:
5475 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5476 * names = []
5477 * ENV.each_key { |name| names.push(name) } # => ENV
5478 * names # => ["bar", "foo"]
5480 * Returns an Enumerator if no block given:
5481 * e = ENV.each_key # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_key>
5482 * names = []
5483 * e.each { |name| names.push(name) } # => ENV
5484 * names # => ["bar", "foo"]
5486 static VALUE
5487 env_each_key(VALUE ehash)
5489 VALUE keys;
5490 long i;
5492 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5493 keys = env_keys(FALSE);
5494 for (i=0; i<RARRAY_LEN(keys); i++) {
5495 rb_yield(RARRAY_AREF(keys, i));
5497 return ehash;
5500 static VALUE
5501 env_values(void)
5503 VALUE ary = rb_ary_new();
5505 ENV_LOCK();
5507 char **env = GET_ENVIRON(environ);
5509 while (*env) {
5510 char *s = strchr(*env, '=');
5511 if (s) {
5512 rb_ary_push(ary, env_str_new2(s+1));
5514 env++;
5516 FREE_ENVIRON(environ);
5518 ENV_UNLOCK();
5520 return ary;
5524 * call-seq:
5525 * ENV.values -> array of values
5527 * Returns all environment variable values in an Array:
5528 * ENV.replace('foo' => '0', 'bar' => '1')
5529 * ENV.values # => ['1', '0']
5530 * The order of the values is OS-dependent.
5531 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
5533 * Returns the empty Array if ENV is empty.
5535 static VALUE
5536 env_f_values(VALUE _)
5538 return env_values();
5542 * call-seq:
5543 * ENV.each_value { |value| block } -> ENV
5544 * ENV.each_value -> an_enumerator
5546 * Yields each environment variable value:
5547 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5548 * values = []
5549 * ENV.each_value { |value| values.push(value) } # => ENV
5550 * values # => ["1", "0"]
5552 * Returns an Enumerator if no block given:
5553 * e = ENV.each_value # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_value>
5554 * values = []
5555 * e.each { |value| values.push(value) } # => ENV
5556 * values # => ["1", "0"]
5558 static VALUE
5559 env_each_value(VALUE ehash)
5561 VALUE values;
5562 long i;
5564 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5565 values = env_values();
5566 for (i=0; i<RARRAY_LEN(values); i++) {
5567 rb_yield(RARRAY_AREF(values, i));
5569 return ehash;
5573 * call-seq:
5574 * ENV.each { |name, value| block } -> ENV
5575 * ENV.each -> an_enumerator
5576 * ENV.each_pair { |name, value| block } -> ENV
5577 * ENV.each_pair -> an_enumerator
5579 * Yields each environment variable name and its value as a 2-element Array:
5580 * h = {}
5581 * ENV.each_pair { |name, value| h[name] = value } # => ENV
5582 * h # => {"bar"=>"1", "foo"=>"0"}
5584 * Returns an Enumerator if no block given:
5585 * h = {}
5586 * e = ENV.each_pair # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_pair>
5587 * e.each { |name, value| h[name] = value } # => ENV
5588 * h # => {"bar"=>"1", "foo"=>"0"}
5590 static VALUE
5591 env_each_pair(VALUE ehash)
5593 long i;
5595 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5597 VALUE ary = rb_ary_new();
5599 ENV_LOCK();
5601 char **env = GET_ENVIRON(environ);
5603 while (*env) {
5604 char *s = strchr(*env, '=');
5605 if (s) {
5606 rb_ary_push(ary, env_str_new(*env, s-*env));
5607 rb_ary_push(ary, env_str_new2(s+1));
5609 env++;
5611 FREE_ENVIRON(environ);
5613 ENV_UNLOCK();
5615 if (rb_block_pair_yield_optimizable()) {
5616 for (i=0; i<RARRAY_LEN(ary); i+=2) {
5617 rb_yield_values(2, RARRAY_AREF(ary, i), RARRAY_AREF(ary, i+1));
5620 else {
5621 for (i=0; i<RARRAY_LEN(ary); i+=2) {
5622 rb_yield(rb_assoc_new(RARRAY_AREF(ary, i), RARRAY_AREF(ary, i+1)));
5626 return ehash;
5630 * call-seq:
5631 * ENV.reject! { |name, value| block } -> ENV or nil
5632 * ENV.reject! -> an_enumerator
5634 * Similar to ENV.delete_if, but returns +nil+ if no changes were made.
5636 * Yields each environment variable name and its value as a 2-element Array,
5637 * deleting each environment variable for which the block returns a truthy value,
5638 * and returning ENV (if any deletions) or +nil+ (if not):
5639 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5640 * ENV.reject! { |name, value| name.start_with?('b') } # => ENV
5641 * ENV # => {"foo"=>"0"}
5642 * ENV.reject! { |name, value| name.start_with?('b') } # => nil
5644 * Returns an Enumerator if no block given:
5645 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5646 * e = ENV.reject! # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:reject!>
5647 * e.each { |name, value| name.start_with?('b') } # => ENV
5648 * ENV # => {"foo"=>"0"}
5649 * e.each { |name, value| name.start_with?('b') } # => nil
5651 static VALUE
5652 env_reject_bang(VALUE ehash)
5654 VALUE keys;
5655 long i;
5656 int del = 0;
5658 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5659 keys = env_keys(FALSE);
5660 RBASIC_CLEAR_CLASS(keys);
5661 for (i=0; i<RARRAY_LEN(keys); i++) {
5662 VALUE val = rb_f_getenv(Qnil, RARRAY_AREF(keys, i));
5663 if (!NIL_P(val)) {
5664 if (RTEST(rb_yield_values(2, RARRAY_AREF(keys, i), val))) {
5665 env_delete(RARRAY_AREF(keys, i));
5666 del++;
5670 RB_GC_GUARD(keys);
5671 if (del == 0) return Qnil;
5672 return envtbl;
5676 * call-seq:
5677 * ENV.delete_if { |name, value| block } -> ENV
5678 * ENV.delete_if -> an_enumerator
5680 * Yields each environment variable name and its value as a 2-element Array,
5681 * deleting each environment variable for which the block returns a truthy value,
5682 * and returning ENV (regardless of whether any deletions):
5683 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5684 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5685 * ENV # => {"foo"=>"0"}
5686 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5688 * Returns an Enumerator if no block given:
5689 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5690 * e = ENV.delete_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:delete_if!>
5691 * e.each { |name, value| name.start_with?('b') } # => ENV
5692 * ENV # => {"foo"=>"0"}
5693 * e.each { |name, value| name.start_with?('b') } # => ENV
5695 static VALUE
5696 env_delete_if(VALUE ehash)
5698 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5699 env_reject_bang(ehash);
5700 return envtbl;
5704 * call-seq:
5705 * ENV.values_at(*names) -> array of values
5707 * Returns an Array containing the environment variable values associated with
5708 * the given names:
5709 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5710 * ENV.values_at('foo', 'baz') # => ["0", "2"]
5712 * Returns +nil+ in the Array for each name that is not an ENV name:
5713 * ENV.values_at('foo', 'bat', 'bar', 'bam') # => ["0", nil, "1", nil]
5715 * Returns an empty Array if no names given.
5717 * Raises an exception if any name is invalid.
5718 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5720 static VALUE
5721 env_values_at(int argc, VALUE *argv, VALUE _)
5723 VALUE result;
5724 long i;
5726 result = rb_ary_new();
5727 for (i=0; i<argc; i++) {
5728 rb_ary_push(result, rb_f_getenv(Qnil, argv[i]));
5730 return result;
5734 * call-seq:
5735 * ENV.select { |name, value| block } -> hash of name/value pairs
5736 * ENV.select -> an_enumerator
5737 * ENV.filter { |name, value| block } -> hash of name/value pairs
5738 * ENV.filter -> an_enumerator
5740 * Yields each environment variable name and its value as a 2-element Array,
5741 * returning a Hash of the names and values for which the block returns a truthy value:
5742 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5743 * ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5744 * ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5746 * Returns an Enumerator if no block given:
5747 * e = ENV.select # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:select>
5748 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5749 * e = ENV.filter # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:filter>
5750 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5752 static VALUE
5753 env_select(VALUE ehash)
5755 VALUE result;
5756 VALUE keys;
5757 long i;
5759 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5760 result = rb_hash_new();
5761 keys = env_keys(FALSE);
5762 for (i = 0; i < RARRAY_LEN(keys); ++i) {
5763 VALUE key = RARRAY_AREF(keys, i);
5764 VALUE val = rb_f_getenv(Qnil, key);
5765 if (!NIL_P(val)) {
5766 if (RTEST(rb_yield_values(2, key, val))) {
5767 rb_hash_aset(result, key, val);
5771 RB_GC_GUARD(keys);
5773 return result;
5777 * call-seq:
5778 * ENV.select! { |name, value| block } -> ENV or nil
5779 * ENV.select! -> an_enumerator
5780 * ENV.filter! { |name, value| block } -> ENV or nil
5781 * ENV.filter! -> an_enumerator
5783 * Yields each environment variable name and its value as a 2-element Array,
5784 * deleting each entry for which the block returns +false+ or +nil+,
5785 * and returning ENV if any deletions made, or +nil+ otherwise:
5787 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5788 * ENV.select! { |name, value| name.start_with?('b') } # => ENV
5789 * ENV # => {"bar"=>"1", "baz"=>"2"}
5790 * ENV.select! { |name, value| true } # => nil
5792 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5793 * ENV.filter! { |name, value| name.start_with?('b') } # => ENV
5794 * ENV # => {"bar"=>"1", "baz"=>"2"}
5795 * ENV.filter! { |name, value| true } # => nil
5797 * Returns an Enumerator if no block given:
5799 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5800 * e = ENV.select! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:select!>
5801 * e.each { |name, value| name.start_with?('b') } # => ENV
5802 * ENV # => {"bar"=>"1", "baz"=>"2"}
5803 * e.each { |name, value| true } # => nil
5805 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5806 * e = ENV.filter! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:filter!>
5807 * e.each { |name, value| name.start_with?('b') } # => ENV
5808 * ENV # => {"bar"=>"1", "baz"=>"2"}
5809 * e.each { |name, value| true } # => nil
5811 static VALUE
5812 env_select_bang(VALUE ehash)
5814 VALUE keys;
5815 long i;
5816 int del = 0;
5818 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5819 keys = env_keys(FALSE);
5820 RBASIC_CLEAR_CLASS(keys);
5821 for (i=0; i<RARRAY_LEN(keys); i++) {
5822 VALUE val = rb_f_getenv(Qnil, RARRAY_AREF(keys, i));
5823 if (!NIL_P(val)) {
5824 if (!RTEST(rb_yield_values(2, RARRAY_AREF(keys, i), val))) {
5825 env_delete(RARRAY_AREF(keys, i));
5826 del++;
5830 RB_GC_GUARD(keys);
5831 if (del == 0) return Qnil;
5832 return envtbl;
5836 * call-seq:
5837 * ENV.keep_if { |name, value| block } -> ENV
5838 * ENV.keep_if -> an_enumerator
5840 * Yields each environment variable name and its value as a 2-element Array,
5841 * deleting each environment variable for which the block returns +false+ or +nil+,
5842 * and returning ENV:
5843 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5844 * ENV.keep_if { |name, value| name.start_with?('b') } # => ENV
5845 * ENV # => {"bar"=>"1", "baz"=>"2"}
5847 * Returns an Enumerator if no block given:
5848 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5849 * e = ENV.keep_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:keep_if>
5850 * e.each { |name, value| name.start_with?('b') } # => ENV
5851 * ENV # => {"bar"=>"1", "baz"=>"2"}
5853 static VALUE
5854 env_keep_if(VALUE ehash)
5856 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5857 env_select_bang(ehash);
5858 return envtbl;
5862 * call-seq:
5863 * ENV.slice(*names) -> hash of name/value pairs
5865 * Returns a Hash of the given ENV names and their corresponding values:
5866 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2', 'bat' => '3')
5867 * ENV.slice('foo', 'baz') # => {"foo"=>"0", "baz"=>"2"}
5868 * ENV.slice('baz', 'foo') # => {"baz"=>"2", "foo"=>"0"}
5869 * Raises an exception if any of the +names+ is invalid
5870 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
5871 * ENV.slice('foo', 'bar', :bat) # Raises TypeError (no implicit conversion of Symbol into String)
5873 static VALUE
5874 env_slice(int argc, VALUE *argv, VALUE _)
5876 int i;
5877 VALUE key, value, result;
5879 if (argc == 0) {
5880 return rb_hash_new();
5882 result = rb_hash_new_with_size(argc);
5884 for (i = 0; i < argc; i++) {
5885 key = argv[i];
5886 value = rb_f_getenv(Qnil, key);
5887 if (value != Qnil)
5888 rb_hash_aset(result, key, value);
5891 return result;
5894 VALUE
5895 rb_env_clear(void)
5897 VALUE keys;
5898 long i;
5900 keys = env_keys(TRUE);
5901 for (i=0; i<RARRAY_LEN(keys); i++) {
5902 VALUE key = RARRAY_AREF(keys, i);
5903 const char *nam = RSTRING_PTR(key);
5904 ruby_setenv(nam, 0);
5906 RB_GC_GUARD(keys);
5907 return envtbl;
5911 * call-seq:
5912 * ENV.clear -> ENV
5914 * Removes every environment variable; returns ENV:
5915 * ENV.replace('foo' => '0', 'bar' => '1')
5916 * ENV.size # => 2
5917 * ENV.clear # => ENV
5918 * ENV.size # => 0
5920 static VALUE
5921 env_clear(VALUE _)
5923 return rb_env_clear();
5927 * call-seq:
5928 * ENV.to_s -> "ENV"
5930 * Returns String 'ENV':
5931 * ENV.to_s # => "ENV"
5933 static VALUE
5934 env_to_s(VALUE _)
5936 return rb_usascii_str_new2("ENV");
5940 * call-seq:
5941 * ENV.inspect -> a_string
5943 * Returns the contents of the environment as a String:
5944 * ENV.replace('foo' => '0', 'bar' => '1')
5945 * ENV.inspect # => "{\"bar\"=>\"1\", \"foo\"=>\"0\"}"
5947 static VALUE
5948 env_inspect(VALUE _)
5950 VALUE i;
5951 VALUE str = rb_str_buf_new2("{");
5953 ENV_LOCK();
5955 char **env = GET_ENVIRON(environ);
5956 while (*env) {
5957 char *s = strchr(*env, '=');
5959 if (env != environ) {
5960 rb_str_buf_cat2(str, ", ");
5962 if (s) {
5963 rb_str_buf_cat2(str, "\"");
5964 rb_str_buf_cat(str, *env, s-*env);
5965 rb_str_buf_cat2(str, "\"=>");
5966 i = rb_inspect(rb_str_new2(s+1));
5967 rb_str_buf_append(str, i);
5969 env++;
5971 FREE_ENVIRON(environ);
5973 ENV_UNLOCK();
5975 rb_str_buf_cat2(str, "}");
5977 return str;
5981 * call-seq:
5982 * ENV.to_a -> array of 2-element arrays
5984 * Returns the contents of ENV as an Array of 2-element Arrays,
5985 * each of which is a name/value pair:
5986 * ENV.replace('foo' => '0', 'bar' => '1')
5987 * ENV.to_a # => [["bar", "1"], ["foo", "0"]]
5989 static VALUE
5990 env_to_a(VALUE _)
5992 VALUE ary = rb_ary_new();
5994 ENV_LOCK();
5996 char **env = GET_ENVIRON(environ);
5997 while (*env) {
5998 char *s = strchr(*env, '=');
5999 if (s) {
6000 rb_ary_push(ary, rb_assoc_new(env_str_new(*env, s-*env),
6001 env_str_new2(s+1)));
6003 env++;
6005 FREE_ENVIRON(environ);
6007 ENV_UNLOCK();
6009 return ary;
6013 * call-seq:
6014 * ENV.rehash -> nil
6016 * (Provided for compatibility with Hash.)
6018 * Does not modify ENV; returns +nil+.
6020 static VALUE
6021 env_none(VALUE _)
6023 return Qnil;
6026 static int
6027 env_size_with_lock(void)
6029 int i = 0;
6031 ENV_LOCK();
6033 char **env = GET_ENVIRON(environ);
6034 while (env[i]) i++;
6035 FREE_ENVIRON(environ);
6037 ENV_UNLOCK();
6039 return i;
6043 * call-seq:
6044 * ENV.length -> an_integer
6045 * ENV.size -> an_integer
6047 * Returns the count of environment variables:
6048 * ENV.replace('foo' => '0', 'bar' => '1')
6049 * ENV.length # => 2
6050 * ENV.size # => 2
6052 static VALUE
6053 env_size(VALUE _)
6055 return INT2FIX(env_size_with_lock());
6059 * call-seq:
6060 * ENV.empty? -> true or false
6062 * Returns +true+ when there are no environment variables, +false+ otherwise:
6063 * ENV.clear
6064 * ENV.empty? # => true
6065 * ENV['foo'] = '0'
6066 * ENV.empty? # => false
6068 static VALUE
6069 env_empty_p(VALUE _)
6071 bool empty = true;
6073 ENV_LOCK();
6075 char **env = GET_ENVIRON(environ);
6076 if (env[0] != 0) {
6077 empty = false;
6079 FREE_ENVIRON(environ);
6081 ENV_UNLOCK();
6083 return RBOOL(empty);
6087 * call-seq:
6088 * ENV.include?(name) -> true or false
6089 * ENV.has_key?(name) -> true or false
6090 * ENV.member?(name) -> true or false
6091 * ENV.key?(name) -> true or false
6093 * Returns +true+ if there is an environment variable with the given +name+:
6094 * ENV.replace('foo' => '0', 'bar' => '1')
6095 * ENV.include?('foo') # => true
6096 * Returns +false+ if +name+ is a valid String and there is no such environment variable:
6097 * ENV.include?('baz') # => false
6098 * Returns +false+ if +name+ is the empty String or is a String containing character <code>'='</code>:
6099 * ENV.include?('') # => false
6100 * ENV.include?('=') # => false
6101 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6102 * ENV.include?("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6103 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6104 * ENV.include?("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6105 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6106 * Raises an exception if +name+ is not a String:
6107 * ENV.include?(Object.new) # TypeError (no implicit conversion of Object into String)
6109 static VALUE
6110 env_has_key(VALUE env, VALUE key)
6112 const char *s = env_name(key);
6113 return RBOOL(has_env_with_lock(s));
6117 * call-seq:
6118 * ENV.assoc(name) -> [name, value] or nil
6120 * Returns a 2-element Array containing the name and value of the environment variable
6121 * for +name+ if it exists:
6122 * ENV.replace('foo' => '0', 'bar' => '1')
6123 * ENV.assoc('foo') # => ['foo', '0']
6124 * Returns +nil+ if +name+ is a valid String and there is no such environment variable.
6126 * Returns +nil+ if +name+ is the empty String or is a String containing character <code>'='</code>.
6128 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6129 * ENV.assoc("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6130 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6131 * ENV.assoc("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6132 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6133 * Raises an exception if +name+ is not a String:
6134 * ENV.assoc(Object.new) # TypeError (no implicit conversion of Object into String)
6136 static VALUE
6137 env_assoc(VALUE env, VALUE key)
6139 const char *s = env_name(key);
6140 VALUE e = getenv_with_lock(s);
6142 if (!NIL_P(e)) {
6143 return rb_assoc_new(key, e);
6145 else {
6146 return Qnil;
6151 * call-seq:
6152 * ENV.value?(value) -> true or false
6153 * ENV.has_value?(value) -> true or false
6155 * Returns +true+ if +value+ is the value for some environment variable name, +false+ otherwise:
6156 * ENV.replace('foo' => '0', 'bar' => '1')
6157 * ENV.value?('0') # => true
6158 * ENV.has_value?('0') # => true
6159 * ENV.value?('2') # => false
6160 * ENV.has_value?('2') # => false
6162 static VALUE
6163 env_has_value(VALUE dmy, VALUE obj)
6165 obj = rb_check_string_type(obj);
6166 if (NIL_P(obj)) return Qnil;
6168 VALUE ret = Qfalse;
6170 ENV_LOCK();
6172 char **env = GET_ENVIRON(environ);
6173 while (*env) {
6174 char *s = strchr(*env, '=');
6175 if (s++) {
6176 long len = strlen(s);
6177 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
6178 ret = Qtrue;
6179 break;
6182 env++;
6184 FREE_ENVIRON(environ);
6186 ENV_UNLOCK();
6188 return ret;
6192 * call-seq:
6193 * ENV.rassoc(value) -> [name, value] or nil
6195 * Returns a 2-element Array containing the name and value of the
6196 * *first* *found* environment variable that has value +value+, if one
6197 * exists:
6198 * ENV.replace('foo' => '0', 'bar' => '0')
6199 * ENV.rassoc('0') # => ["bar", "0"]
6200 * The order in which environment variables are examined is OS-dependent.
6201 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6203 * Returns +nil+ if there is no such environment variable.
6205 static VALUE
6206 env_rassoc(VALUE dmy, VALUE obj)
6208 obj = rb_check_string_type(obj);
6209 if (NIL_P(obj)) return Qnil;
6211 VALUE result = Qnil;
6213 ENV_LOCK();
6215 char **env = GET_ENVIRON(environ);
6217 while (*env) {
6218 const char *p = *env;
6219 char *s = strchr(p, '=');
6220 if (s++) {
6221 long len = strlen(s);
6222 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
6223 result = rb_assoc_new(rb_str_new(p, s-p-1), obj);
6224 break;
6227 env++;
6229 FREE_ENVIRON(environ);
6231 ENV_UNLOCK();
6233 return result;
6237 * call-seq:
6238 * ENV.key(value) -> name or nil
6240 * Returns the name of the first environment variable with +value+, if it exists:
6241 * ENV.replace('foo' => '0', 'bar' => '0')
6242 * ENV.key('0') # => "foo"
6243 * The order in which environment variables are examined is OS-dependent.
6244 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6246 * Returns +nil+ if there is no such value.
6248 * Raises an exception if +value+ is invalid:
6249 * ENV.key(Object.new) # raises TypeError (no implicit conversion of Object into String)
6250 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
6252 static VALUE
6253 env_key(VALUE dmy, VALUE value)
6255 StringValue(value);
6256 VALUE str = Qnil;
6258 ENV_LOCK();
6260 char **env = GET_ENVIRON(environ);
6261 while (*env) {
6262 char *s = strchr(*env, '=');
6263 if (s++) {
6264 long len = strlen(s);
6265 if (RSTRING_LEN(value) == len && strncmp(s, RSTRING_PTR(value), len) == 0) {
6266 str = env_str_new(*env, s-*env-1);
6267 break;
6270 env++;
6272 FREE_ENVIRON(environ);
6274 ENV_UNLOCK();
6276 return str;
6279 static VALUE
6280 env_to_hash(void)
6282 VALUE hash = rb_hash_new();
6284 ENV_LOCK();
6286 char **env = GET_ENVIRON(environ);
6287 while (*env) {
6288 char *s = strchr(*env, '=');
6289 if (s) {
6290 rb_hash_aset(hash, env_str_new(*env, s-*env),
6291 env_str_new2(s+1));
6293 env++;
6295 FREE_ENVIRON(environ);
6297 ENV_UNLOCK();
6299 return hash;
6302 VALUE
6303 rb_envtbl(void)
6305 return envtbl;
6308 VALUE
6309 rb_env_to_hash(void)
6311 return env_to_hash();
6315 * call-seq:
6316 * ENV.to_hash -> hash of name/value pairs
6318 * Returns a Hash containing all name/value pairs from ENV:
6319 * ENV.replace('foo' => '0', 'bar' => '1')
6320 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6323 static VALUE
6324 env_f_to_hash(VALUE _)
6326 return env_to_hash();
6330 * call-seq:
6331 * ENV.to_h -> hash of name/value pairs
6332 * ENV.to_h {|name, value| block } -> hash of name/value pairs
6334 * With no block, returns a Hash containing all name/value pairs from ENV:
6335 * ENV.replace('foo' => '0', 'bar' => '1')
6336 * ENV.to_h # => {"bar"=>"1", "foo"=>"0"}
6337 * With a block, returns a Hash whose items are determined by the block.
6338 * Each name/value pair in ENV is yielded to the block.
6339 * The block must return a 2-element Array (name/value pair)
6340 * that is added to the return Hash as a key and value:
6341 * ENV.to_h { |name, value| [name.to_sym, value.to_i] } # => {:bar=>1, :foo=>0}
6342 * Raises an exception if the block does not return an Array:
6343 * ENV.to_h { |name, value| name } # Raises TypeError (wrong element type String (expected array))
6344 * Raises an exception if the block returns an Array of the wrong size:
6345 * ENV.to_h { |name, value| [name] } # Raises ArgumentError (element has wrong array length (expected 2, was 1))
6347 static VALUE
6348 env_to_h(VALUE _)
6350 VALUE hash = env_to_hash();
6351 if (rb_block_given_p()) {
6352 hash = rb_hash_to_h_block(hash);
6354 return hash;
6358 * call-seq:
6359 * ENV.except(*keys) -> a_hash
6361 * Returns a hash except the given keys from ENV and their values.
6363 * ENV #=> {"LANG"=>"en_US.UTF-8", "TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"}
6364 * ENV.except("TERM","HOME") #=> {"LANG"=>"en_US.UTF-8"}
6366 static VALUE
6367 env_except(int argc, VALUE *argv, VALUE _)
6369 int i;
6370 VALUE key, hash = env_to_hash();
6372 for (i = 0; i < argc; i++) {
6373 key = argv[i];
6374 rb_hash_delete(hash, key);
6377 return hash;
6381 * call-seq:
6382 * ENV.reject { |name, value| block } -> hash of name/value pairs
6383 * ENV.reject -> an_enumerator
6385 * Yields each environment variable name and its value as a 2-element Array.
6386 * Returns a Hash whose items are determined by the block.
6387 * When the block returns a truthy value, the name/value pair is added to the return Hash;
6388 * otherwise the pair is ignored:
6389 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
6390 * ENV.reject { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6391 * Returns an Enumerator if no block given:
6392 * e = ENV.reject
6393 * e.each { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6395 static VALUE
6396 env_reject(VALUE _)
6398 return rb_hash_delete_if(env_to_hash());
6401 NORETURN(static VALUE env_freeze(VALUE self));
6403 * call-seq:
6404 * ENV.freeze
6406 * Raises an exception:
6407 * ENV.freeze # Raises TypeError (cannot freeze ENV)
6409 static VALUE
6410 env_freeze(VALUE self)
6412 rb_raise(rb_eTypeError, "cannot freeze ENV");
6413 UNREACHABLE_RETURN(self);
6417 * call-seq:
6418 * ENV.shift -> [name, value] or nil
6420 * Removes the first environment variable from ENV and returns
6421 * a 2-element Array containing its name and value:
6422 * ENV.replace('foo' => '0', 'bar' => '1')
6423 * ENV.to_hash # => {'bar' => '1', 'foo' => '0'}
6424 * ENV.shift # => ['bar', '1']
6425 * ENV.to_hash # => {'foo' => '0'}
6426 * Exactly which environment variable is "first" is OS-dependent.
6427 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6429 * Returns +nil+ if the environment is empty.
6431 static VALUE
6432 env_shift(VALUE _)
6434 VALUE result = Qnil;
6435 VALUE key = Qnil;
6437 ENV_LOCK();
6439 char **env = GET_ENVIRON(environ);
6440 if (*env) {
6441 const char *p = *env;
6442 char *s = strchr(p, '=');
6443 if (s) {
6444 key = env_str_new(p, s-p);
6445 VALUE val = env_str_new2(getenv(RSTRING_PTR(key)));
6446 result = rb_assoc_new(key, val);
6449 FREE_ENVIRON(environ);
6451 ENV_UNLOCK();
6453 if (!NIL_P(key)) {
6454 env_delete(key);
6457 return result;
6461 * call-seq:
6462 * ENV.invert -> hash of value/name pairs
6464 * Returns a Hash whose keys are the ENV values,
6465 * and whose values are the corresponding ENV names:
6466 * ENV.replace('foo' => '0', 'bar' => '1')
6467 * ENV.invert # => {"1"=>"bar", "0"=>"foo"}
6468 * For a duplicate ENV value, overwrites the hash entry:
6469 * ENV.replace('foo' => '0', 'bar' => '0')
6470 * ENV.invert # => {"0"=>"foo"}
6471 * Note that the order of the ENV processing is OS-dependent,
6472 * which means that the order of overwriting is also OS-dependent.
6473 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6475 static VALUE
6476 env_invert(VALUE _)
6478 return rb_hash_invert(env_to_hash());
6481 static void
6482 keylist_delete(VALUE keys, VALUE key)
6484 long keylen, elen;
6485 const char *keyptr, *eptr;
6486 RSTRING_GETMEM(key, keyptr, keylen);
6487 /* Don't stop at first key, as it is possible to have
6488 multiple environment values with the same key.
6490 for (long i=0; i<RARRAY_LEN(keys); i++) {
6491 VALUE e = RARRAY_AREF(keys, i);
6492 RSTRING_GETMEM(e, eptr, elen);
6493 if (elen != keylen) continue;
6494 if (!ENVNMATCH(keyptr, eptr, elen)) continue;
6495 rb_ary_delete_at(keys, i);
6496 i--;
6500 static int
6501 env_replace_i(VALUE key, VALUE val, VALUE keys)
6503 env_name(key);
6504 env_aset(key, val);
6506 keylist_delete(keys, key);
6507 return ST_CONTINUE;
6511 * call-seq:
6512 * ENV.replace(hash) -> ENV
6514 * Replaces the entire content of the environment variables
6515 * with the name/value pairs in the given +hash+;
6516 * returns ENV.
6518 * Replaces the content of ENV with the given pairs:
6519 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
6520 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6522 * Raises an exception if a name or value is invalid
6523 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
6524 * ENV.replace('foo' => '0', :bar => '1') # Raises TypeError (no implicit conversion of Symbol into String)
6525 * ENV.replace('foo' => '0', 'bar' => 1) # Raises TypeError (no implicit conversion of Integer into String)
6526 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6528 static VALUE
6529 env_replace(VALUE env, VALUE hash)
6531 VALUE keys;
6532 long i;
6534 keys = env_keys(TRUE);
6535 if (env == hash) return env;
6536 hash = to_hash(hash);
6537 rb_hash_foreach(hash, env_replace_i, keys);
6539 for (i=0; i<RARRAY_LEN(keys); i++) {
6540 env_delete(RARRAY_AREF(keys, i));
6542 RB_GC_GUARD(keys);
6543 return env;
6546 static int
6547 env_update_i(VALUE key, VALUE val, VALUE _)
6549 env_aset(key, val);
6550 return ST_CONTINUE;
6553 static int
6554 env_update_block_i(VALUE key, VALUE val, VALUE _)
6556 VALUE oldval = rb_f_getenv(Qnil, key);
6557 if (!NIL_P(oldval)) {
6558 val = rb_yield_values(3, key, oldval, val);
6560 env_aset(key, val);
6561 return ST_CONTINUE;
6565 * call-seq:
6566 * ENV.update -> ENV
6567 * ENV.update(*hashes) -> ENV
6568 * ENV.update(*hashes) { |name, env_val, hash_val| block } -> ENV
6569 * ENV.merge! -> ENV
6570 * ENV.merge!(*hashes) -> ENV
6571 * ENV.merge!(*hashes) { |name, env_val, hash_val| block } -> ENV
6573 * Adds to ENV each key/value pair in the given +hash+; returns ENV:
6574 * ENV.replace('foo' => '0', 'bar' => '1')
6575 * ENV.merge!('baz' => '2', 'bat' => '3') # => {"bar"=>"1", "bat"=>"3", "baz"=>"2", "foo"=>"0"}
6576 * Deletes the ENV entry for a hash value that is +nil+:
6577 * ENV.merge!('baz' => nil, 'bat' => nil) # => {"bar"=>"1", "foo"=>"0"}
6578 * For an already-existing name, if no block given, overwrites the ENV value:
6579 * ENV.merge!('foo' => '4') # => {"bar"=>"1", "foo"=>"4"}
6580 * For an already-existing name, if block given,
6581 * yields the name, its ENV value, and its hash value;
6582 * the block's return value becomes the new name:
6583 * ENV.merge!('foo' => '5') { |name, env_val, hash_val | env_val + hash_val } # => {"bar"=>"1", "foo"=>"45"}
6584 * Raises an exception if a name or value is invalid
6585 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]);
6586 * ENV.replace('foo' => '0', 'bar' => '1')
6587 * ENV.merge!('foo' => '6', :bar => '7', 'baz' => '9') # Raises TypeError (no implicit conversion of Symbol into String)
6588 * ENV # => {"bar"=>"1", "foo"=>"6"}
6589 * ENV.merge!('foo' => '7', 'bar' => 8, 'baz' => '9') # Raises TypeError (no implicit conversion of Integer into String)
6590 * ENV # => {"bar"=>"1", "foo"=>"7"}
6591 * Raises an exception if the block returns an invalid name:
6592 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
6593 * ENV.merge!('bat' => '8', 'foo' => '9') { |name, env_val, hash_val | 10 } # Raises TypeError (no implicit conversion of Integer into String)
6594 * ENV # => {"bar"=>"1", "bat"=>"8", "foo"=>"7"}
6596 * Note that for the exceptions above,
6597 * hash pairs preceding an invalid name or value are processed normally;
6598 * those following are ignored.
6600 static VALUE
6601 env_update(int argc, VALUE *argv, VALUE env)
6603 rb_foreach_func *func = rb_block_given_p() ?
6604 env_update_block_i : env_update_i;
6605 for (int i = 0; i < argc; ++i) {
6606 VALUE hash = argv[i];
6607 if (env == hash) continue;
6608 hash = to_hash(hash);
6609 rb_hash_foreach(hash, func, 0);
6611 return env;
6614 NORETURN(static VALUE env_clone(int, VALUE *, VALUE));
6616 * call-seq:
6617 * ENV.clone(freeze: nil) # raises TypeError
6619 * Raises TypeError, because ENV is a wrapper for the process-wide
6620 * environment variables and a clone is useless.
6621 * Use #to_h to get a copy of ENV data as a hash.
6623 static VALUE
6624 env_clone(int argc, VALUE *argv, VALUE obj)
6626 if (argc) {
6627 VALUE opt;
6628 if (rb_scan_args(argc, argv, "0:", &opt) < argc) {
6629 rb_get_freeze_opt(1, &opt);
6633 rb_raise(rb_eTypeError, "Cannot clone ENV, use ENV.to_h to get a copy of ENV as a hash");
6636 NORETURN(static VALUE env_dup(VALUE));
6638 * call-seq:
6639 * ENV.dup # raises TypeError
6641 * Raises TypeError, because ENV is a singleton object.
6642 * Use #to_h to get a copy of ENV data as a hash.
6644 static VALUE
6645 env_dup(VALUE obj)
6647 rb_raise(rb_eTypeError, "Cannot dup ENV, use ENV.to_h to get a copy of ENV as a hash");
6650 static const rb_data_type_t env_data_type = {
6651 "ENV",
6653 NULL,
6654 NULL,
6655 NULL,
6656 NULL,
6658 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
6662 * A +Hash+ maps each of its unique keys to a specific value.
6664 * A +Hash+ has certain similarities to an Array, but:
6665 * - An Array index is always an Integer.
6666 * - A +Hash+ key can be (almost) any object.
6668 * === +Hash+ \Data Syntax
6670 * The older syntax for +Hash+ data uses the "hash rocket," <tt>=></tt>:
6672 * h = {:foo => 0, :bar => 1, :baz => 2}
6673 * h # => {:foo=>0, :bar=>1, :baz=>2}
6675 * Alternatively, but only for a +Hash+ key that's a Symbol,
6676 * you can use a newer JSON-style syntax,
6677 * where each bareword becomes a Symbol:
6679 * h = {foo: 0, bar: 1, baz: 2}
6680 * h # => {:foo=>0, :bar=>1, :baz=>2}
6682 * You can also use a String in place of a bareword:
6684 * h = {'foo': 0, 'bar': 1, 'baz': 2}
6685 * h # => {:foo=>0, :bar=>1, :baz=>2}
6687 * And you can mix the styles:
6689 * h = {foo: 0, :bar => 1, 'baz': 2}
6690 * h # => {:foo=>0, :bar=>1, :baz=>2}
6692 * But it's an error to try the JSON-style syntax
6693 * for a key that's not a bareword or a String:
6695 * # Raises SyntaxError (syntax error, unexpected ':', expecting =>):
6696 * h = {0: 'zero'}
6698 * +Hash+ value can be omitted, meaning that value will be fetched from the context
6699 * by the name of the key:
6701 * x = 0
6702 * y = 100
6703 * h = {x:, y:}
6704 * h # => {:x=>0, :y=>100}
6706 * === Common Uses
6708 * You can use a +Hash+ to give names to objects:
6710 * person = {name: 'Matz', language: 'Ruby'}
6711 * person # => {:name=>"Matz", :language=>"Ruby"}
6713 * You can use a +Hash+ to give names to method arguments:
6715 * def some_method(hash)
6716 * p hash
6717 * end
6718 * some_method({foo: 0, bar: 1, baz: 2}) # => {:foo=>0, :bar=>1, :baz=>2}
6720 * Note: when the last argument in a method call is a +Hash+,
6721 * the curly braces may be omitted:
6723 * some_method(foo: 0, bar: 1, baz: 2) # => {:foo=>0, :bar=>1, :baz=>2}
6725 * You can use a +Hash+ to initialize an object:
6727 * class Dev
6728 * attr_accessor :name, :language
6729 * def initialize(hash)
6730 * self.name = hash[:name]
6731 * self.language = hash[:language]
6732 * end
6733 * end
6734 * matz = Dev.new(name: 'Matz', language: 'Ruby')
6735 * matz # => #<Dev: @name="Matz", @language="Ruby">
6737 * === Creating a +Hash+
6739 * You can create a +Hash+ object explicitly with:
6741 * - A {hash literal}[rdoc-ref:syntax/literals.rdoc@Hash+Literals].
6743 * You can convert certain objects to Hashes with:
6745 * - \Method #Hash.
6747 * You can create a +Hash+ by calling method Hash.new.
6749 * Create an empty +Hash+:
6751 * h = Hash.new
6752 * h # => {}
6753 * h.class # => Hash
6755 * You can create a +Hash+ by calling method Hash.[].
6757 * Create an empty +Hash+:
6759 * h = Hash[]
6760 * h # => {}
6762 * Create a +Hash+ with initial entries:
6764 * h = Hash[foo: 0, bar: 1, baz: 2]
6765 * h # => {:foo=>0, :bar=>1, :baz=>2}
6767 * You can create a +Hash+ by using its literal form (curly braces).
6769 * Create an empty +Hash+:
6771 * h = {}
6772 * h # => {}
6774 * Create a +Hash+ with initial entries:
6776 * h = {foo: 0, bar: 1, baz: 2}
6777 * h # => {:foo=>0, :bar=>1, :baz=>2}
6780 * === +Hash+ Value Basics
6782 * The simplest way to retrieve a +Hash+ value (instance method #[]):
6784 * h = {foo: 0, bar: 1, baz: 2}
6785 * h[:foo] # => 0
6787 * The simplest way to create or update a +Hash+ value (instance method #[]=):
6789 * h = {foo: 0, bar: 1, baz: 2}
6790 * h[:bat] = 3 # => 3
6791 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
6792 * h[:foo] = 4 # => 4
6793 * h # => {:foo=>4, :bar=>1, :baz=>2, :bat=>3}
6795 * The simplest way to delete a +Hash+ entry (instance method #delete):
6797 * h = {foo: 0, bar: 1, baz: 2}
6798 * h.delete(:bar) # => 1
6799 * h # => {:foo=>0, :baz=>2}
6801 * === Entry Order
6803 * A +Hash+ object presents its entries in the order of their creation. This is seen in:
6805 * - Iterative methods such as <tt>each</tt>, <tt>each_key</tt>, <tt>each_pair</tt>, <tt>each_value</tt>.
6806 * - Other order-sensitive methods such as <tt>shift</tt>, <tt>keys</tt>, <tt>values</tt>.
6807 * - The String returned by method <tt>inspect</tt>.
6809 * A new +Hash+ has its initial ordering per the given entries:
6811 * h = Hash[foo: 0, bar: 1]
6812 * h # => {:foo=>0, :bar=>1}
6814 * New entries are added at the end:
6816 * h[:baz] = 2
6817 * h # => {:foo=>0, :bar=>1, :baz=>2}
6819 * Updating a value does not affect the order:
6821 * h[:baz] = 3
6822 * h # => {:foo=>0, :bar=>1, :baz=>3}
6824 * But re-creating a deleted entry can affect the order:
6826 * h.delete(:foo)
6827 * h[:foo] = 5
6828 * h # => {:bar=>1, :baz=>3, :foo=>5}
6830 * === +Hash+ Keys
6832 * ==== +Hash+ Key Equivalence
6834 * Two objects are treated as the same \hash key when their <code>hash</code> value
6835 * is identical and the two objects are <code>eql?</code> to each other.
6837 * ==== Modifying an Active +Hash+ Key
6839 * Modifying a +Hash+ key while it is in use damages the hash's index.
6841 * This +Hash+ has keys that are Arrays:
6843 * a0 = [ :foo, :bar ]
6844 * a1 = [ :baz, :bat ]
6845 * h = {a0 => 0, a1 => 1}
6846 * h.include?(a0) # => true
6847 * h[a0] # => 0
6848 * a0.hash # => 110002110
6850 * Modifying array element <tt>a0[0]</tt> changes its hash value:
6852 * a0[0] = :bam
6853 * a0.hash # => 1069447059
6855 * And damages the +Hash+ index:
6857 * h.include?(a0) # => false
6858 * h[a0] # => nil
6860 * You can repair the hash index using method +rehash+:
6862 * h.rehash # => {[:bam, :bar]=>0, [:baz, :bat]=>1}
6863 * h.include?(a0) # => true
6864 * h[a0] # => 0
6866 * A String key is always safe.
6867 * That's because an unfrozen String
6868 * passed as a key will be replaced by a duplicated and frozen String:
6870 * s = 'foo'
6871 * s.frozen? # => false
6872 * h = {s => 0}
6873 * first_key = h.keys.first
6874 * first_key.frozen? # => true
6876 * ==== User-Defined +Hash+ Keys
6878 * To be useable as a +Hash+ key, objects must implement the methods <code>hash</code> and <code>eql?</code>.
6879 * Note: this requirement does not apply if the +Hash+ uses #compare_by_identity since comparison will then
6880 * rely on the keys' object id instead of <code>hash</code> and <code>eql?</code>.
6882 * Object defines basic implementation for <code>hash</code> and <code>eq?</code> that makes each object
6883 * a distinct key. Typically, user-defined classes will want to override these methods to provide meaningful
6884 * behavior, or for example inherit Struct that has useful definitions for these.
6886 * A typical implementation of <code>hash</code> is based on the
6887 * object's data while <code>eql?</code> is usually aliased to the overridden
6888 * <code>==</code> method:
6890 * class Book
6891 * attr_reader :author, :title
6893 * def initialize(author, title)
6894 * @author = author
6895 * @title = title
6896 * end
6898 * def ==(other)
6899 * self.class === other &&
6900 * other.author == @author &&
6901 * other.title == @title
6902 * end
6904 * alias eql? ==
6906 * def hash
6907 * [self.class, @author, @title].hash
6908 * end
6909 * end
6911 * book1 = Book.new 'matz', 'Ruby in a Nutshell'
6912 * book2 = Book.new 'matz', 'Ruby in a Nutshell'
6914 * reviews = {}
6916 * reviews[book1] = 'Great reference!'
6917 * reviews[book2] = 'Nice and compact!'
6919 * reviews.length #=> 1
6921 * === Default Values
6923 * The methods #[], #values_at and #dig need to return the value associated to a certain key.
6924 * When that key is not found, that value will be determined by its default proc (if any)
6925 * or else its default (initially `nil`).
6927 * You can retrieve the default value with method #default:
6929 * h = Hash.new
6930 * h.default # => nil
6932 * You can set the default value by passing an argument to method Hash.new or
6933 * with method #default=
6935 * h = Hash.new(-1)
6936 * h.default # => -1
6937 * h.default = 0
6938 * h.default # => 0
6940 * This default value is returned for #[], #values_at and #dig when a key is
6941 * not found:
6943 * counts = {foo: 42}
6944 * counts.default # => nil (default)
6945 * counts[:foo] = 42
6946 * counts[:bar] # => nil
6947 * counts.default = 0
6948 * counts[:bar] # => 0
6949 * counts.values_at(:foo, :bar, :baz) # => [42, 0, 0]
6950 * counts.dig(:bar) # => 0
6952 * Note that the default value is used without being duplicated. It is not advised to set
6953 * the default value to a mutable object:
6955 * synonyms = Hash.new([])
6956 * synonyms[:hello] # => []
6957 * synonyms[:hello] << :hi # => [:hi], but this mutates the default!
6958 * synonyms.default # => [:hi]
6959 * synonyms[:world] << :universe
6960 * synonyms[:world] # => [:hi, :universe], oops
6961 * synonyms.keys # => [], oops
6963 * To use a mutable object as default, it is recommended to use a default proc
6965 * ==== Default Proc
6967 * When the default proc for a +Hash+ is set (i.e., not +nil+),
6968 * the default value returned by method #[] is determined by the default proc alone.
6970 * You can retrieve the default proc with method #default_proc:
6972 * h = Hash.new
6973 * h.default_proc # => nil
6975 * You can set the default proc by calling Hash.new with a block or
6976 * calling the method #default_proc=
6978 * h = Hash.new { |hash, key| "Default value for #{key}" }
6979 * h.default_proc.class # => Proc
6980 * h.default_proc = proc { |hash, key| "Default value for #{key.inspect}" }
6981 * h.default_proc.class # => Proc
6983 * When the default proc is set (i.e., not +nil+)
6984 * and method #[] is called with with a non-existent key,
6985 * #[] calls the default proc with both the +Hash+ object itself and the missing key,
6986 * then returns the proc's return value:
6988 * h = Hash.new { |hash, key| "Default value for #{key}" }
6989 * h[:nosuch] # => "Default value for nosuch"
6991 * Note that in the example above no entry for key +:nosuch+ is created:
6993 * h.include?(:nosuch) # => false
6995 * However, the proc itself can add a new entry:
6997 * synonyms = Hash.new { |hash, key| hash[key] = [] }
6998 * synonyms.include?(:hello) # => false
6999 * synonyms[:hello] << :hi # => [:hi]
7000 * synonyms[:world] << :universe # => [:universe]
7001 * synonyms.keys # => [:hello, :world]
7003 * Note that setting the default proc will clear the default value and vice versa.
7005 * Be aware that a default proc that modifies the hash is not thread-safe in the
7006 * sense that multiple threads can call into the default proc concurrently for the
7007 * same key.
7009 * === What's Here
7011 * First, what's elsewhere. \Class +Hash+:
7013 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
7014 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
7015 * which provides dozens of additional methods.
7017 * Here, class +Hash+ provides methods that are useful for:
7019 * - {Creating a Hash}[rdoc-ref:Hash@Methods+for+Creating+a+Hash]
7020 * - {Setting Hash State}[rdoc-ref:Hash@Methods+for+Setting+Hash+State]
7021 * - {Querying}[rdoc-ref:Hash@Methods+for+Querying]
7022 * - {Comparing}[rdoc-ref:Hash@Methods+for+Comparing]
7023 * - {Fetching}[rdoc-ref:Hash@Methods+for+Fetching]
7024 * - {Assigning}[rdoc-ref:Hash@Methods+for+Assigning]
7025 * - {Deleting}[rdoc-ref:Hash@Methods+for+Deleting]
7026 * - {Iterating}[rdoc-ref:Hash@Methods+for+Iterating]
7027 * - {Converting}[rdoc-ref:Hash@Methods+for+Converting]
7028 * - {Transforming Keys and Values}[rdoc-ref:Hash@Methods+for+Transforming+Keys+and+Values]
7029 * - {And more....}[rdoc-ref:Hash@Other+Methods]
7031 * \Class +Hash+ also includes methods from module Enumerable.
7033 * ==== Methods for Creating a +Hash+
7035 * - ::[]: Returns a new hash populated with given objects.
7036 * - ::new: Returns a new empty hash.
7037 * - ::try_convert: Returns a new hash created from a given object.
7039 * ==== Methods for Setting +Hash+ State
7041 * - #compare_by_identity: Sets +self+ to consider only identity in comparing keys.
7042 * - #default=: Sets the default to a given value.
7043 * - #default_proc=: Sets the default proc to a given proc.
7044 * - #rehash: Rebuilds the hash table by recomputing the hash index for each key.
7046 * ==== Methods for Querying
7048 * - #any?: Returns whether any element satisfies a given criterion.
7049 * - #compare_by_identity?: Returns whether the hash considers only identity when comparing keys.
7050 * - #default: Returns the default value, or the default value for a given key.
7051 * - #default_proc: Returns the default proc.
7052 * - #empty?: Returns whether there are no entries.
7053 * - #eql?: Returns whether a given object is equal to +self+.
7054 * - #hash: Returns the integer hash code.
7055 * - #has_value?: Returns whether a given object is a value in +self+.
7056 * - #include?, #has_key?, #member?, #key?: Returns whether a given object is a key in +self+.
7057 * - #length, #size: Returns the count of entries.
7058 * - #value?: Returns whether a given object is a value in +self+.
7060 * ==== Methods for Comparing
7062 * - #<: Returns whether +self+ is a proper subset of a given object.
7063 * - #<=: Returns whether +self+ is a subset of a given object.
7064 * - #==: Returns whether a given object is equal to +self+.
7065 * - #>: Returns whether +self+ is a proper superset of a given object
7066 * - #>=: Returns whether +self+ is a superset of a given object.
7068 * ==== Methods for Fetching
7070 * - #[]: Returns the value associated with a given key.
7071 * - #assoc: Returns a 2-element array containing a given key and its value.
7072 * - #dig: Returns the object in nested objects that is specified
7073 * by a given key and additional arguments.
7074 * - #fetch: Returns the value for a given key.
7075 * - #fetch_values: Returns array containing the values associated with given keys.
7076 * - #key: Returns the key for the first-found entry with a given value.
7077 * - #keys: Returns an array containing all keys in +self+.
7078 * - #rassoc: Returns a 2-element array consisting of the key and value
7079 * of the first-found entry having a given value.
7080 * - #values: Returns an array containing all values in +self+/
7081 * - #values_at: Returns an array containing values for given keys.
7083 * ==== Methods for Assigning
7085 * - #[]=, #store: Associates a given key with a given value.
7086 * - #merge: Returns the hash formed by merging each given hash into a copy of +self+.
7087 * - #merge!, #update: Merges each given hash into +self+.
7088 * - #replace: Replaces the entire contents of +self+ with the contents of a given hash.
7090 * ==== Methods for Deleting
7092 * These methods remove entries from +self+:
7094 * - #clear: Removes all entries from +self+.
7095 * - #compact!: Removes all +nil+-valued entries from +self+.
7096 * - #delete: Removes the entry for a given key.
7097 * - #delete_if: Removes entries selected by a given block.
7098 * - #filter!, #select!: Keep only those entries selected by a given block.
7099 * - #keep_if: Keep only those entries selected by a given block.
7100 * - #reject!: Removes entries selected by a given block.
7101 * - #shift: Removes and returns the first entry.
7103 * These methods return a copy of +self+ with some entries removed:
7105 * - #compact: Returns a copy of +self+ with all +nil+-valued entries removed.
7106 * - #except: Returns a copy of +self+ with entries removed for specified keys.
7107 * - #filter, #select: Returns a copy of +self+ with only those entries selected by a given block.
7108 * - #reject: Returns a copy of +self+ with entries removed as specified by a given block.
7109 * - #slice: Returns a hash containing the entries for given keys.
7111 * ==== Methods for Iterating
7112 * - #each, #each_pair: Calls a given block with each key-value pair.
7113 * - #each_key: Calls a given block with each key.
7114 * - #each_value: Calls a given block with each value.
7116 * ==== Methods for Converting
7118 * - #inspect, #to_s: Returns a new String containing the hash entries.
7119 * - #to_a: Returns a new array of 2-element arrays;
7120 * each nested array contains a key-value pair from +self+.
7121 * - #to_h: Returns +self+ if a +Hash+;
7122 * if a subclass of +Hash+, returns a +Hash+ containing the entries from +self+.
7123 * - #to_hash: Returns +self+.
7124 * - #to_proc: Returns a proc that maps a given key to its value.
7126 * ==== Methods for Transforming Keys and Values
7128 * - #transform_keys: Returns a copy of +self+ with modified keys.
7129 * - #transform_keys!: Modifies keys in +self+
7130 * - #transform_values: Returns a copy of +self+ with modified values.
7131 * - #transform_values!: Modifies values in +self+.
7133 * ==== Other Methods
7134 * - #flatten: Returns an array that is a 1-dimensional flattening of +self+.
7135 * - #invert: Returns a hash with the each key-value pair inverted.
7139 void
7140 Init_Hash(void)
7142 id_hash = rb_intern_const("hash");
7143 id_flatten_bang = rb_intern_const("flatten!");
7144 id_hash_iter_lev = rb_make_internal_id();
7146 rb_cHash = rb_define_class("Hash", rb_cObject);
7148 rb_include_module(rb_cHash, rb_mEnumerable);
7150 rb_define_alloc_func(rb_cHash, empty_hash_alloc);
7151 rb_define_singleton_method(rb_cHash, "[]", rb_hash_s_create, -1);
7152 rb_define_singleton_method(rb_cHash, "try_convert", rb_hash_s_try_convert, 1);
7153 rb_define_method(rb_cHash, "initialize", rb_hash_initialize, -1);
7154 rb_define_method(rb_cHash, "initialize_copy", rb_hash_replace, 1);
7155 rb_define_method(rb_cHash, "rehash", rb_hash_rehash, 0);
7157 rb_define_method(rb_cHash, "to_hash", rb_hash_to_hash, 0);
7158 rb_define_method(rb_cHash, "to_h", rb_hash_to_h, 0);
7159 rb_define_method(rb_cHash, "to_a", rb_hash_to_a, 0);
7160 rb_define_method(rb_cHash, "inspect", rb_hash_inspect, 0);
7161 rb_define_alias(rb_cHash, "to_s", "inspect");
7162 rb_define_method(rb_cHash, "to_proc", rb_hash_to_proc, 0);
7164 rb_define_method(rb_cHash, "==", rb_hash_equal, 1);
7165 rb_define_method(rb_cHash, "[]", rb_hash_aref, 1);
7166 rb_define_method(rb_cHash, "hash", rb_hash_hash, 0);
7167 rb_define_method(rb_cHash, "eql?", rb_hash_eql, 1);
7168 rb_define_method(rb_cHash, "fetch", rb_hash_fetch_m, -1);
7169 rb_define_method(rb_cHash, "[]=", rb_hash_aset, 2);
7170 rb_define_method(rb_cHash, "store", rb_hash_aset, 2);
7171 rb_define_method(rb_cHash, "default", rb_hash_default, -1);
7172 rb_define_method(rb_cHash, "default=", rb_hash_set_default, 1);
7173 rb_define_method(rb_cHash, "default_proc", rb_hash_default_proc, 0);
7174 rb_define_method(rb_cHash, "default_proc=", rb_hash_set_default_proc, 1);
7175 rb_define_method(rb_cHash, "key", rb_hash_key, 1);
7176 rb_define_method(rb_cHash, "size", rb_hash_size, 0);
7177 rb_define_method(rb_cHash, "length", rb_hash_size, 0);
7178 rb_define_method(rb_cHash, "empty?", rb_hash_empty_p, 0);
7180 rb_define_method(rb_cHash, "each_value", rb_hash_each_value, 0);
7181 rb_define_method(rb_cHash, "each_key", rb_hash_each_key, 0);
7182 rb_define_method(rb_cHash, "each_pair", rb_hash_each_pair, 0);
7183 rb_define_method(rb_cHash, "each", rb_hash_each_pair, 0);
7185 rb_define_method(rb_cHash, "transform_keys", rb_hash_transform_keys, -1);
7186 rb_define_method(rb_cHash, "transform_keys!", rb_hash_transform_keys_bang, -1);
7187 rb_define_method(rb_cHash, "transform_values", rb_hash_transform_values, 0);
7188 rb_define_method(rb_cHash, "transform_values!", rb_hash_transform_values_bang, 0);
7190 rb_define_method(rb_cHash, "keys", rb_hash_keys, 0);
7191 rb_define_method(rb_cHash, "values", rb_hash_values, 0);
7192 rb_define_method(rb_cHash, "values_at", rb_hash_values_at, -1);
7193 rb_define_method(rb_cHash, "fetch_values", rb_hash_fetch_values, -1);
7195 rb_define_method(rb_cHash, "shift", rb_hash_shift, 0);
7196 rb_define_method(rb_cHash, "delete", rb_hash_delete_m, 1);
7197 rb_define_method(rb_cHash, "delete_if", rb_hash_delete_if, 0);
7198 rb_define_method(rb_cHash, "keep_if", rb_hash_keep_if, 0);
7199 rb_define_method(rb_cHash, "select", rb_hash_select, 0);
7200 rb_define_method(rb_cHash, "select!", rb_hash_select_bang, 0);
7201 rb_define_method(rb_cHash, "filter", rb_hash_select, 0);
7202 rb_define_method(rb_cHash, "filter!", rb_hash_select_bang, 0);
7203 rb_define_method(rb_cHash, "reject", rb_hash_reject, 0);
7204 rb_define_method(rb_cHash, "reject!", rb_hash_reject_bang, 0);
7205 rb_define_method(rb_cHash, "slice", rb_hash_slice, -1);
7206 rb_define_method(rb_cHash, "except", rb_hash_except, -1);
7207 rb_define_method(rb_cHash, "clear", rb_hash_clear, 0);
7208 rb_define_method(rb_cHash, "invert", rb_hash_invert, 0);
7209 rb_define_method(rb_cHash, "update", rb_hash_update, -1);
7210 rb_define_method(rb_cHash, "replace", rb_hash_replace, 1);
7211 rb_define_method(rb_cHash, "merge!", rb_hash_update, -1);
7212 rb_define_method(rb_cHash, "merge", rb_hash_merge, -1);
7213 rb_define_method(rb_cHash, "assoc", rb_hash_assoc, 1);
7214 rb_define_method(rb_cHash, "rassoc", rb_hash_rassoc, 1);
7215 rb_define_method(rb_cHash, "flatten", rb_hash_flatten, -1);
7216 rb_define_method(rb_cHash, "compact", rb_hash_compact, 0);
7217 rb_define_method(rb_cHash, "compact!", rb_hash_compact_bang, 0);
7219 rb_define_method(rb_cHash, "include?", rb_hash_has_key, 1);
7220 rb_define_method(rb_cHash, "member?", rb_hash_has_key, 1);
7221 rb_define_method(rb_cHash, "has_key?", rb_hash_has_key, 1);
7222 rb_define_method(rb_cHash, "has_value?", rb_hash_has_value, 1);
7223 rb_define_method(rb_cHash, "key?", rb_hash_has_key, 1);
7224 rb_define_method(rb_cHash, "value?", rb_hash_has_value, 1);
7226 rb_define_method(rb_cHash, "compare_by_identity", rb_hash_compare_by_id, 0);
7227 rb_define_method(rb_cHash, "compare_by_identity?", rb_hash_compare_by_id_p, 0);
7229 rb_define_method(rb_cHash, "any?", rb_hash_any_p, -1);
7230 rb_define_method(rb_cHash, "dig", rb_hash_dig, -1);
7232 rb_define_method(rb_cHash, "<=", rb_hash_le, 1);
7233 rb_define_method(rb_cHash, "<", rb_hash_lt, 1);
7234 rb_define_method(rb_cHash, ">=", rb_hash_ge, 1);
7235 rb_define_method(rb_cHash, ">", rb_hash_gt, 1);
7237 rb_define_method(rb_cHash, "deconstruct_keys", rb_hash_deconstruct_keys, 1);
7239 rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash?", rb_hash_s_ruby2_keywords_hash_p, 1);
7240 rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash", rb_hash_s_ruby2_keywords_hash, 1);
7242 /* Document-class: ENV
7244 * +ENV+ is a hash-like accessor for environment variables.
7246 * === Interaction with the Operating System
7248 * The +ENV+ object interacts with the operating system's environment variables:
7250 * - When you get the value for a name in +ENV+, the value is retrieved from among the current environment variables.
7251 * - When you create or set a name-value pair in +ENV+, the name and value are immediately set in the environment variables.
7252 * - When you delete a name-value pair in +ENV+, it is immediately deleted from the environment variables.
7254 * === Names and Values
7256 * Generally, a name or value is a String.
7258 * ==== Valid Names and Values
7260 * Each name or value must be one of the following:
7262 * - A String.
7263 * - An object that responds to \#to_str by returning a String, in which case that String will be used as the name or value.
7265 * ==== Invalid Names and Values
7267 * A new name:
7269 * - May not be the empty string:
7270 * ENV[''] = '0'
7271 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv())
7273 * - May not contain character <code>"="</code>:
7274 * ENV['='] = '0'
7275 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv(=))
7277 * A new name or value:
7279 * - May not be a non-String that does not respond to \#to_str:
7281 * ENV['foo'] = Object.new
7282 * # Raises TypeError (no implicit conversion of Object into String)
7283 * ENV[Object.new] = '0'
7284 * # Raises TypeError (no implicit conversion of Object into String)
7286 * - May not contain the NUL character <code>"\0"</code>:
7288 * ENV['foo'] = "\0"
7289 * # Raises ArgumentError (bad environment variable value: contains null byte)
7290 * ENV["\0"] == '0'
7291 * # Raises ArgumentError (bad environment variable name: contains null byte)
7293 * - May not have an ASCII-incompatible encoding such as UTF-16LE or ISO-2022-JP:
7295 * ENV['foo'] = '0'.force_encoding(Encoding::ISO_2022_JP)
7296 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7297 * ENV["foo".force_encoding(Encoding::ISO_2022_JP)] = '0'
7298 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7300 * === About Ordering
7302 * +ENV+ enumerates its name/value pairs in the order found
7303 * in the operating system's environment variables.
7304 * Therefore the ordering of +ENV+ content is OS-dependent, and may be indeterminate.
7306 * This will be seen in:
7307 * - A Hash returned by an +ENV+ method.
7308 * - An Enumerator returned by an +ENV+ method.
7309 * - An Array returned by ENV.keys, ENV.values, or ENV.to_a.
7310 * - The String returned by ENV.inspect.
7311 * - The Array returned by ENV.shift.
7312 * - The name returned by ENV.key.
7314 * === About the Examples
7315 * Some methods in +ENV+ return +ENV+ itself. Typically, there are many environment variables.
7316 * It's not useful to display a large +ENV+ in the examples here,
7317 * so most example snippets begin by resetting the contents of +ENV+:
7318 * - ENV.replace replaces +ENV+ with a new collection of entries.
7319 * - ENV.clear empties +ENV+.
7321 * === What's Here
7323 * First, what's elsewhere. \Class +ENV+:
7325 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
7326 * - Extends {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
7328 * Here, class +ENV+ provides methods that are useful for:
7330 * - {Querying}[rdoc-ref:ENV@Methods+for+Querying]
7331 * - {Assigning}[rdoc-ref:ENV@Methods+for+Assigning]
7332 * - {Deleting}[rdoc-ref:ENV@Methods+for+Deleting]
7333 * - {Iterating}[rdoc-ref:ENV@Methods+for+Iterating]
7334 * - {Converting}[rdoc-ref:ENV@Methods+for+Converting]
7335 * - {And more ....}[rdoc-ref:ENV@More+Methods]
7337 * ==== Methods for Querying
7339 * - ::[]: Returns the value for the given environment variable name if it exists:
7340 * - ::empty?: Returns whether +ENV+ is empty.
7341 * - ::has_value?, ::value?: Returns whether the given value is in +ENV+.
7342 * - ::include?, ::has_key?, ::key?, ::member?: Returns whether the given name
7343 is in +ENV+.
7344 * - ::key: Returns the name of the first entry with the given value.
7345 * - ::size, ::length: Returns the number of entries.
7346 * - ::value?: Returns whether any entry has the given value.
7348 * ==== Methods for Assigning
7350 * - ::[]=, ::store: Creates, updates, or deletes the named environment variable.
7351 * - ::clear: Removes every environment variable; returns +ENV+:
7352 * - ::update, ::merge!: Adds to +ENV+ each key/value pair in the given hash.
7353 * - ::replace: Replaces the entire content of the +ENV+
7354 * with the name/value pairs in the given hash.
7356 * ==== Methods for Deleting
7358 * - ::delete: Deletes the named environment variable name if it exists.
7359 * - ::delete_if: Deletes entries selected by the block.
7360 * - ::keep_if: Deletes entries not selected by the block.
7361 * - ::reject!: Similar to #delete_if, but returns +nil+ if no change was made.
7362 * - ::select!, ::filter!: Deletes entries selected by the block.
7363 * - ::shift: Removes and returns the first entry.
7365 * ==== Methods for Iterating
7367 * - ::each, ::each_pair: Calls the block with each name/value pair.
7368 * - ::each_key: Calls the block with each name.
7369 * - ::each_value: Calls the block with each value.
7371 * ==== Methods for Converting
7373 * - ::assoc: Returns a 2-element array containing the name and value
7374 * of the named environment variable if it exists:
7375 * - ::clone: Returns +ENV+ (and issues a warning).
7376 * - ::except: Returns a hash of all name/value pairs except those given.
7377 * - ::fetch: Returns the value for the given name.
7378 * - ::inspect: Returns the contents of +ENV+ as a string.
7379 * - ::invert: Returns a hash whose keys are the +ENV+ values,
7380 and whose values are the corresponding +ENV+ names.
7381 * - ::keys: Returns an array of all names.
7382 * - ::rassoc: Returns the name and value of the first found entry
7383 * that has the given value.
7384 * - ::reject: Returns a hash of those entries not rejected by the block.
7385 * - ::select, ::filter: Returns a hash of name/value pairs selected by the block.
7386 * - ::slice: Returns a hash of the given names and their corresponding values.
7387 * - ::to_a: Returns the entries as an array of 2-element Arrays.
7388 * - ::to_h: Returns a hash of entries selected by the block.
7389 * - ::to_hash: Returns a hash of all entries.
7390 * - ::to_s: Returns the string <tt>'ENV'</tt>.
7391 * - ::values: Returns all values as an array.
7392 * - ::values_at: Returns an array of the values for the given name.
7394 * ==== More Methods
7396 * - ::dup: Raises an exception.
7397 * - ::freeze: Raises an exception.
7398 * - ::rehash: Returns +nil+, without modifying +ENV+.
7403 * Hack to get RDoc to regard ENV as a class:
7404 * envtbl = rb_define_class("ENV", rb_cObject);
7406 origenviron = environ;
7407 envtbl = TypedData_Wrap_Struct(rb_cObject, &env_data_type, NULL);
7408 rb_extend_object(envtbl, rb_mEnumerable);
7409 FL_SET_RAW(envtbl, RUBY_FL_SHAREABLE);
7412 rb_define_singleton_method(envtbl, "[]", rb_f_getenv, 1);
7413 rb_define_singleton_method(envtbl, "fetch", env_fetch, -1);
7414 rb_define_singleton_method(envtbl, "[]=", env_aset_m, 2);
7415 rb_define_singleton_method(envtbl, "store", env_aset_m, 2);
7416 rb_define_singleton_method(envtbl, "each", env_each_pair, 0);
7417 rb_define_singleton_method(envtbl, "each_pair", env_each_pair, 0);
7418 rb_define_singleton_method(envtbl, "each_key", env_each_key, 0);
7419 rb_define_singleton_method(envtbl, "each_value", env_each_value, 0);
7420 rb_define_singleton_method(envtbl, "delete", env_delete_m, 1);
7421 rb_define_singleton_method(envtbl, "delete_if", env_delete_if, 0);
7422 rb_define_singleton_method(envtbl, "keep_if", env_keep_if, 0);
7423 rb_define_singleton_method(envtbl, "slice", env_slice, -1);
7424 rb_define_singleton_method(envtbl, "except", env_except, -1);
7425 rb_define_singleton_method(envtbl, "clear", env_clear, 0);
7426 rb_define_singleton_method(envtbl, "reject", env_reject, 0);
7427 rb_define_singleton_method(envtbl, "reject!", env_reject_bang, 0);
7428 rb_define_singleton_method(envtbl, "select", env_select, 0);
7429 rb_define_singleton_method(envtbl, "select!", env_select_bang, 0);
7430 rb_define_singleton_method(envtbl, "filter", env_select, 0);
7431 rb_define_singleton_method(envtbl, "filter!", env_select_bang, 0);
7432 rb_define_singleton_method(envtbl, "shift", env_shift, 0);
7433 rb_define_singleton_method(envtbl, "freeze", env_freeze, 0);
7434 rb_define_singleton_method(envtbl, "invert", env_invert, 0);
7435 rb_define_singleton_method(envtbl, "replace", env_replace, 1);
7436 rb_define_singleton_method(envtbl, "update", env_update, -1);
7437 rb_define_singleton_method(envtbl, "merge!", env_update, -1);
7438 rb_define_singleton_method(envtbl, "inspect", env_inspect, 0);
7439 rb_define_singleton_method(envtbl, "rehash", env_none, 0);
7440 rb_define_singleton_method(envtbl, "to_a", env_to_a, 0);
7441 rb_define_singleton_method(envtbl, "to_s", env_to_s, 0);
7442 rb_define_singleton_method(envtbl, "key", env_key, 1);
7443 rb_define_singleton_method(envtbl, "size", env_size, 0);
7444 rb_define_singleton_method(envtbl, "length", env_size, 0);
7445 rb_define_singleton_method(envtbl, "empty?", env_empty_p, 0);
7446 rb_define_singleton_method(envtbl, "keys", env_f_keys, 0);
7447 rb_define_singleton_method(envtbl, "values", env_f_values, 0);
7448 rb_define_singleton_method(envtbl, "values_at", env_values_at, -1);
7449 rb_define_singleton_method(envtbl, "include?", env_has_key, 1);
7450 rb_define_singleton_method(envtbl, "member?", env_has_key, 1);
7451 rb_define_singleton_method(envtbl, "has_key?", env_has_key, 1);
7452 rb_define_singleton_method(envtbl, "has_value?", env_has_value, 1);
7453 rb_define_singleton_method(envtbl, "key?", env_has_key, 1);
7454 rb_define_singleton_method(envtbl, "value?", env_has_value, 1);
7455 rb_define_singleton_method(envtbl, "to_hash", env_f_to_hash, 0);
7456 rb_define_singleton_method(envtbl, "to_h", env_to_h, 0);
7457 rb_define_singleton_method(envtbl, "assoc", env_assoc, 1);
7458 rb_define_singleton_method(envtbl, "rassoc", env_rassoc, 1);
7459 rb_define_singleton_method(envtbl, "clone", env_clone, -1);
7460 rb_define_singleton_method(envtbl, "dup", env_dup, 0);
7462 VALUE envtbl_class = rb_singleton_class(envtbl);
7463 rb_undef_method(envtbl_class, "initialize");
7464 rb_undef_method(envtbl_class, "initialize_clone");
7465 rb_undef_method(envtbl_class, "initialize_copy");
7466 rb_undef_method(envtbl_class, "initialize_dup");
7469 * +ENV+ is a Hash-like accessor for environment variables.
7471 * See ENV (the class) for more details.
7473 rb_define_global_const("ENV", envtbl);
7475 /* for callcc */
7476 ruby_register_rollback_func_for_ensure(hash_foreach_ensure, hash_foreach_ensure_rollback);
7478 HASH_ASSERT(sizeof(ar_hint_t) * RHASH_AR_TABLE_MAX_SIZE == sizeof(VALUE));