1 /**********************************************************************
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"
19 # ifdef HAVE_CRT_EXTERNS_H
20 # include <crt_externs.h>
22 # include "missing/crt_externs.h"
26 #include "debug_counter.h"
29 #include "internal/array.h"
30 #include "internal/bignum.h"
31 #include "internal/class.h"
32 #include "internal/cont.h"
33 #include "internal/error.h"
34 #include "internal/hash.h"
35 #include "internal/object.h"
36 #include "internal/proc.h"
37 #include "internal/symbol.h"
38 #include "internal/time.h"
39 #include "internal/vm.h"
42 #include "ruby/util.h"
43 #include "ruby_assert.h"
45 #include "transient_heap.h"
46 #include "ruby/thread_native.h"
47 #include "ruby/ractor.h"
58 #define SET_DEFAULT(hash, ifnone) ( \
59 FL_UNSET_RAW(hash, RHASH_PROC_DEFAULT), \
60 RHASH_SET_IFNONE(hash, ifnone))
62 #define SET_PROC_DEFAULT(hash, proc) set_proc_default(hash, proc)
64 #define COPY_DEFAULT(hash, hash2) copy_default(RHASH(hash), RHASH(hash2))
67 copy_default(struct RHash
*hash
, const struct RHash
*hash2
)
69 hash
->basic
.flags
&= ~RHASH_PROC_DEFAULT
;
70 hash
->basic
.flags
|= hash2
->basic
.flags
& RHASH_PROC_DEFAULT
;
71 RHASH_SET_IFNONE(hash
, RHASH_IFNONE((VALUE
)hash2
));
74 static VALUE
rb_hash_s_try_convert(VALUE
, VALUE
);
78 * 1. Check mutate st_* functions
87 rb_hash_freeze(VALUE hash
)
89 return rb_obj_freeze(hash
);
95 static ID id_hash
, id_default
, id_flatten_bang
;
96 static ID id_hash_iter_lev
;
99 rb_hash_set_ifnone(VALUE hash
, VALUE ifnone
)
101 RB_OBJ_WRITE(hash
, (&RHASH(hash
)->ifnone
), ifnone
);
106 rb_any_cmp(VALUE a
, VALUE b
)
108 if (a
== b
) return 0;
109 if (RB_TYPE_P(a
, T_STRING
) && RBASIC(a
)->klass
== rb_cString
&&
110 RB_TYPE_P(b
, T_STRING
) && RBASIC(b
)->klass
== rb_cString
) {
111 return rb_str_hash_cmp(a
, b
);
113 if (a
== Qundef
|| b
== Qundef
) return -1;
114 if (SYMBOL_P(a
) && SYMBOL_P(b
)) {
118 return !rb_eql(a
, b
);
122 hash_recursive(VALUE obj
, VALUE arg
, int recurse
)
124 if (recurse
) return INT2FIX(0);
125 return rb_funcallv(obj
, id_hash
, 0, 0);
128 static long rb_objid_hash(st_index_t index
);
131 dbl_to_index(double d
)
133 union {double d
; st_index_t i
;} u
;
139 rb_dbl_long_hash(double d
)
141 /* normalize -0.0 to 0.0 */
142 if (d
== 0.0) d
= 0.0;
143 #if SIZEOF_INT == SIZEOF_VOIDP
144 return rb_memhash(&d
, sizeof(d
));
146 return rb_objid_hash(dbl_to_index(d
));
151 any_hash(VALUE a
, st_index_t (*other_func
)(VALUE
))
158 if (STATIC_SYM_P(a
)) {
159 hnum
= a
>> (RUBY_SPECIAL_SHIFT
+ ID_SCOPE_SHIFT
);
160 hnum
= rb_hash_start(hnum
);
163 hnum
= RSYMBOL(a
)->hashval
;
170 hnum
= rb_objid_hash((st_index_t
)a
);
173 hnum
= rb_str_hash(a
);
176 hval
= rb_big_hash(a
);
177 hnum
= FIX2LONG(hval
);
179 case T_FLOAT
: /* prevent pathological behavior: [Bug #10761] */
180 hnum
= rb_dbl_long_hash(rb_float_value(a
));
183 hnum
= other_func(a
);
185 if ((SIGNED_VALUE
)hnum
> 0)
193 obj_any_hash(VALUE obj
)
195 VALUE hval
= rb_check_funcall_basic_kw(obj
, id_hash
, rb_mKernel
, 0, 0, 0);
197 if (hval
== Qundef
) {
198 hval
= rb_exec_recursive_outer(hash_recursive
, obj
, 0);
201 while (!FIXNUM_P(hval
)) {
202 if (RB_TYPE_P(hval
, T_BIGNUM
)) {
205 sign
= rb_integer_pack(hval
, &ul
, 1, sizeof(ul
), 0,
206 INTEGER_PACK_NATIVE_BYTE_ORDER
);
208 hval
= LONG2FIX(ul
| FIXNUM_MIN
);
211 hval
= LONG2FIX(ul
& FIXNUM_MAX
);
214 hval
= rb_to_int(hval
);
217 return FIX2LONG(hval
);
223 return any_hash(a
, obj_any_hash
);
229 return LONG2FIX(any_hash(obj
, obj_any_hash
));
233 /* Here is a hash function for 64-bit key. It is about 5 times faster
234 (2 times faster when uint128 type is absent) on Haswell than
235 tailored Spooky or City hash function can be. */
237 /* Here we two primes with random bit generation. */
238 static const uint64_t prime1
= ((uint64_t)0x2e0bb864 << 32) | 0xe9ea7df5;
239 static const uint32_t prime2
= 0x830fcab9;
242 static inline uint64_t
243 mult_and_mix(uint64_t m1
, uint64_t m2
)
245 #if defined HAVE_UINT128_T
246 uint128_t r
= (uint128_t
) m1
* (uint128_t
) m2
;
247 return (uint64_t) (r
>> 64) ^ (uint64_t) r
;
249 uint64_t hm1
= m1
>> 32, hm2
= m2
>> 32;
250 uint64_t lm1
= m1
, lm2
= m2
;
251 uint64_t v64_128
= hm1
* hm2
;
252 uint64_t v32_96
= hm1
* lm2
+ lm1
* hm2
;
253 uint64_t v1_32
= lm1
* lm2
;
255 return (v64_128
+ (v32_96
>> 32)) ^ ((v32_96
<< 32) + v1_32
);
259 static inline uint64_t
260 key64_hash(uint64_t key
, uint32_t seed
)
262 return mult_and_mix(key
+ seed
, prime1
);
265 /* Should cast down the result for each purpose */
266 #define st_index_hash(index) key64_hash(rb_hash_start(index), prime2)
269 rb_objid_hash(st_index_t index
)
271 return (long)st_index_hash(index
);
275 objid_hash(VALUE obj
)
277 VALUE object_id
= rb_obj_id(obj
);
278 if (!FIXNUM_P(object_id
))
279 object_id
= rb_big_hash(object_id
);
281 #if SIZEOF_LONG == SIZEOF_VOIDP
282 return (st_index_t
)st_index_hash((st_index_t
)NUM2LONG(object_id
));
283 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
284 return (st_index_t
)st_index_hash((st_index_t
)NUM2LL(object_id
));
290 * obj.hash -> integer
292 * Generates an Integer hash value for this object. This function must have the
293 * property that <code>a.eql?(b)</code> implies <code>a.hash == b.hash</code>.
295 * The hash value is used along with #eql? by the Hash class to determine if
296 * two objects reference the same hash key. Any hash value that exceeds the
297 * capacity of an Integer will be truncated before being used.
299 * The hash value for an object may not be identical across invocations or
300 * implementations of Ruby. If you need a stable identifier across Ruby
301 * invocations and implementations you will need to generate one with a custom
304 * Certain core classes such as Integer use built-in hash calculations and
305 * do not call the #hash method when used as a hash key.
311 rb_obj_hash(VALUE obj
)
313 long hnum
= any_hash(obj
, objid_hash
);
317 static const struct st_hash_type objhash
= {
322 #define rb_ident_cmp st_numcmp
325 rb_ident_hash(st_data_t n
)
327 #ifdef USE_FLONUM /* RUBY */
329 * - flonum (on 64-bit) is pathologically bad, mix the actual
330 * float value in, but do not use the float value as-is since
331 * many integers get interpreted as 2.0 or -2.0 [Bug #10761]
334 n
^= dbl_to_index(rb_float_value(n
));
338 return (st_index_t
)st_index_hash((st_index_t
)n
);
341 #define identhash rb_hashtype_ident
342 const struct st_hash_type rb_hashtype_ident
= {
347 typedef st_index_t st_hash_t
;
350 * RHASH_AR_TABLE_P(h):
352 * as.ar points ar_table.
353 * * as.ar is allocated by transient heap or xmalloc.
355 * !RHASH_AR_TABLE_P(h):
356 * * as.st points st_table.
359 #define RHASH_AR_TABLE_MAX_BOUND RHASH_AR_TABLE_MAX_SIZE
361 #define RHASH_AR_TABLE_REF(hash, n) (&RHASH_AR_TABLE(hash)->pairs[n])
362 #define RHASH_AR_CLEARED_HINT 0xff
364 typedef struct ar_table_pair_struct
{
369 typedef struct ar_table_struct
{
370 /* 64bit CPU: 8B * 2 * 8 = 128B */
371 ar_table_pair pairs
[RHASH_AR_TABLE_MAX_SIZE
];
375 rb_hash_ar_table_size(void)
377 return sizeof(ar_table
);
380 static inline st_hash_t
381 ar_do_hash(st_data_t key
)
383 return (st_hash_t
)rb_any_hash(key
);
386 static inline ar_hint_t
387 ar_do_hash_hint(st_hash_t hash_value
)
389 return (ar_hint_t
)hash_value
;
392 static inline ar_hint_t
393 ar_hint(VALUE hash
, unsigned int index
)
395 return RHASH(hash
)->ar_hint
.ary
[index
];
399 ar_hint_set_hint(VALUE hash
, unsigned int index
, ar_hint_t hint
)
401 RHASH(hash
)->ar_hint
.ary
[index
] = hint
;
405 ar_hint_set(VALUE hash
, unsigned int index
, st_hash_t hash_value
)
407 ar_hint_set_hint(hash
, index
, ar_do_hash_hint(hash_value
));
411 ar_clear_entry(VALUE hash
, unsigned int index
)
413 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, index
);
415 ar_hint_set_hint(hash
, index
, RHASH_AR_CLEARED_HINT
);
419 ar_cleared_entry(VALUE hash
, unsigned int index
)
421 if (ar_hint(hash
, index
) == RHASH_AR_CLEARED_HINT
) {
422 /* RHASH_AR_CLEARED_HINT is only a hint, not mean cleared entry,
423 * so you need to check key == Qundef
425 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, index
);
426 return pair
->key
== Qundef
;
434 ar_set_entry(VALUE hash
, unsigned int index
, st_data_t key
, st_data_t val
, st_hash_t hash_value
)
436 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, index
);
439 ar_hint_set(hash
, index
, hash_value
);
442 #define RHASH_AR_TABLE_SIZE(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
443 RHASH_AR_TABLE_SIZE_RAW(h))
445 #define RHASH_AR_TABLE_BOUND_RAW(h) \
446 ((unsigned int)((RBASIC(h)->flags >> RHASH_AR_TABLE_BOUND_SHIFT) & \
447 (RHASH_AR_TABLE_BOUND_MASK >> RHASH_AR_TABLE_BOUND_SHIFT)))
449 #define RHASH_AR_TABLE_BOUND(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
450 RHASH_AR_TABLE_BOUND_RAW(h))
452 #define RHASH_ST_TABLE_SET(h, s) rb_hash_st_table_set(h, s)
453 #define RHASH_TYPE(hash) (RHASH_AR_TABLE_P(hash) ? &objhash : RHASH_ST_TABLE(hash)->type)
455 #define HASH_ASSERT(expr) RUBY_ASSERT_MESG_WHEN(HASH_DEBUG, expr, #expr)
458 #define hash_verify(hash) hash_verify_(hash, __FILE__, __LINE__)
461 rb_hash_dump(VALUE hash
)
463 rb_obj_info_dump(hash
);
465 if (RHASH_AR_TABLE_P(hash
)) {
466 unsigned i
, n
= 0, bound
= RHASH_AR_TABLE_BOUND(hash
);
468 fprintf(stderr
, " size:%u bound:%u\n",
469 RHASH_AR_TABLE_SIZE(hash
), RHASH_AR_TABLE_BOUND(hash
));
471 for (i
=0; i
<bound
; i
++) {
474 if (!ar_cleared_entry(hash
, i
)) {
475 char b1
[0x100], b2
[0x100];
476 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
479 fprintf(stderr
, " %d key:%s val:%s hint:%02x\n", i
,
480 rb_raw_obj_info(b1
, 0x100, k
),
481 rb_raw_obj_info(b2
, 0x100, v
),
486 fprintf(stderr
, " %d empty\n", i
);
493 hash_verify_(VALUE hash
, const char *file
, int line
)
495 HASH_ASSERT(RB_TYPE_P(hash
, T_HASH
));
497 if (RHASH_AR_TABLE_P(hash
)) {
498 unsigned i
, n
= 0, bound
= RHASH_AR_TABLE_BOUND(hash
);
500 for (i
=0; i
<bound
; i
++) {
502 if (!ar_cleared_entry(hash
, i
)) {
503 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
506 HASH_ASSERT(k
!= Qundef
);
507 HASH_ASSERT(v
!= Qundef
);
511 if (n
!= RHASH_AR_TABLE_SIZE(hash
)) {
512 rb_bug("n:%u, RHASH_AR_TABLE_SIZE:%u", n
, RHASH_AR_TABLE_SIZE(hash
));
516 HASH_ASSERT(RHASH_ST_TABLE(hash
) != NULL
);
517 HASH_ASSERT(RHASH_AR_TABLE_SIZE_RAW(hash
) == 0);
518 HASH_ASSERT(RHASH_AR_TABLE_BOUND_RAW(hash
) == 0);
521 #if USE_TRANSIENT_HEAP
522 if (RHASH_TRANSIENT_P(hash
)) {
523 volatile st_data_t
MAYBE_UNUSED(key
) = RHASH_AR_TABLE_REF(hash
, 0)->key
; /* read */
524 HASH_ASSERT(RHASH_AR_TABLE(hash
) != NULL
);
525 HASH_ASSERT(rb_transient_heap_managed_ptr_p(RHASH_AR_TABLE(hash
)));
532 #define hash_verify(h) ((void)0)
536 RHASH_TABLE_NULL_P(VALUE hash
)
538 if (RHASH(hash
)->as
.ar
== NULL
) {
539 HASH_ASSERT(RHASH_AR_TABLE_P(hash
));
548 RHASH_TABLE_EMPTY_P(VALUE hash
)
550 return RHASH_SIZE(hash
) == 0;
554 rb_hash_ar_table_p(VALUE hash
)
556 if (FL_TEST_RAW((hash
), RHASH_ST_TABLE_FLAG
)) {
557 HASH_ASSERT(RHASH(hash
)->as
.st
!= NULL
);
566 rb_hash_ar_table(VALUE hash
)
568 HASH_ASSERT(RHASH_AR_TABLE_P(hash
));
569 return RHASH(hash
)->as
.ar
;
573 rb_hash_st_table(VALUE hash
)
575 HASH_ASSERT(!RHASH_AR_TABLE_P(hash
));
576 return RHASH(hash
)->as
.st
;
580 rb_hash_st_table_set(VALUE hash
, st_table
*st
)
582 HASH_ASSERT(st
!= NULL
);
583 FL_SET_RAW((hash
), RHASH_ST_TABLE_FLAG
);
584 RHASH(hash
)->as
.st
= st
;
588 hash_ar_table_set(VALUE hash
, ar_table
*ar
)
590 HASH_ASSERT(RHASH_AR_TABLE_P(hash
));
591 HASH_ASSERT((RHASH_TRANSIENT_P(hash
) && ar
== NULL
) ? FALSE
: TRUE
);
592 RHASH(hash
)->as
.ar
= ar
;
596 #define RHASH_SET_ST_FLAG(h) FL_SET_RAW(h, RHASH_ST_TABLE_FLAG)
597 #define RHASH_UNSET_ST_FLAG(h) FL_UNSET_RAW(h, RHASH_ST_TABLE_FLAG)
600 RHASH_AR_TABLE_BOUND_SET(VALUE h
, st_index_t n
)
602 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
603 HASH_ASSERT(n
<= RHASH_AR_TABLE_MAX_BOUND
);
605 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_BOUND_MASK
;
606 RBASIC(h
)->flags
|= n
<< RHASH_AR_TABLE_BOUND_SHIFT
;
610 RHASH_AR_TABLE_SIZE_SET(VALUE h
, st_index_t n
)
612 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
613 HASH_ASSERT(n
<= RHASH_AR_TABLE_MAX_SIZE
);
615 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_SIZE_MASK
;
616 RBASIC(h
)->flags
|= n
<< RHASH_AR_TABLE_SIZE_SHIFT
;
620 HASH_AR_TABLE_SIZE_ADD(VALUE h
, st_index_t n
)
622 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
624 RHASH_AR_TABLE_SIZE_SET(h
, RHASH_AR_TABLE_SIZE(h
) + n
);
629 #define RHASH_AR_TABLE_SIZE_INC(h) HASH_AR_TABLE_SIZE_ADD(h, 1)
632 RHASH_AR_TABLE_SIZE_DEC(VALUE h
)
634 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
635 int new_size
= RHASH_AR_TABLE_SIZE(h
) - 1;
638 RHASH_AR_TABLE_SIZE_SET(h
, new_size
);
641 RHASH_AR_TABLE_SIZE_SET(h
, 0);
642 RHASH_AR_TABLE_BOUND_SET(h
, 0);
648 RHASH_AR_TABLE_CLEAR(VALUE h
)
650 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_SIZE_MASK
;
651 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_BOUND_MASK
;
653 hash_ar_table_set(h
, NULL
);
657 ar_alloc_table(VALUE hash
)
659 ar_table
*tab
= (ar_table
*)rb_transient_heap_alloc(hash
, sizeof(ar_table
));
662 RHASH_SET_TRANSIENT_FLAG(hash
);
665 RHASH_UNSET_TRANSIENT_FLAG(hash
);
666 tab
= (ar_table
*)ruby_xmalloc(sizeof(ar_table
));
669 RHASH_AR_TABLE_SIZE_SET(hash
, 0);
670 RHASH_AR_TABLE_BOUND_SET(hash
, 0);
671 hash_ar_table_set(hash
, tab
);
676 NOINLINE(static int ar_equal(VALUE x
, VALUE y
));
679 ar_equal(VALUE x
, VALUE y
)
681 return rb_any_cmp(x
, y
) == 0;
685 ar_find_entry_hint(VALUE hash
, ar_hint_t hint
, st_data_t key
)
687 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
688 const ar_hint_t
*hints
= RHASH(hash
)->ar_hint
.ary
;
690 /* if table is NULL, then bound also should be 0 */
692 for (i
= 0; i
< bound
; i
++) {
693 if (hints
[i
] == hint
) {
694 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
695 if (ar_equal(key
, pair
->key
)) {
696 RB_DEBUG_COUNTER_INC(artable_hint_hit
);
702 static char fname
[256];
705 if (pid
!= getpid()) {
706 snprintf(fname
, sizeof(fname
), "/tmp/ruby-armiss.%d", pid
= getpid());
707 if ((fp
= fopen(fname
, "w")) == NULL
) rb_bug("fopen");
710 st_hash_t h1
= ar_do_hash(key
);
711 st_hash_t h2
= ar_do_hash(pair
->key
);
713 fprintf(fp
, "miss: hash_eq:%d hints[%d]:%02x hint:%02x\n"
715 " pair->key:%016lx %s\n",
716 h1
== h2
, i
, hints
[i
], hint
,
717 h1
, rb_obj_info(key
), h2
, rb_obj_info(pair
->key
));
719 RB_DEBUG_COUNTER_INC(artable_hint_miss
);
723 RB_DEBUG_COUNTER_INC(artable_hint_notfound
);
724 return RHASH_AR_TABLE_MAX_BOUND
;
728 ar_find_entry(VALUE hash
, st_hash_t hash_value
, st_data_t key
)
730 ar_hint_t hint
= ar_do_hash_hint(hash_value
);
731 return ar_find_entry_hint(hash
, hint
, key
);
735 ar_free_and_clear_table(VALUE hash
)
737 ar_table
*tab
= RHASH_AR_TABLE(hash
);
740 if (RHASH_TRANSIENT_P(hash
)) {
741 RHASH_UNSET_TRANSIENT_FLAG(hash
);
744 ruby_xfree(RHASH_AR_TABLE(hash
));
746 RHASH_AR_TABLE_CLEAR(hash
);
748 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash
) == 0);
749 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash
) == 0);
750 HASH_ASSERT(RHASH_TRANSIENT_P(hash
) == 0);
754 ar_try_convert_table(VALUE hash
)
756 if (!RHASH_AR_TABLE_P(hash
)) return;
758 const unsigned size
= RHASH_AR_TABLE_SIZE(hash
);
763 if (size
< RHASH_AR_TABLE_MAX_SIZE
) {
767 new_tab
= st_init_table_with_size(&objhash
, size
* 2);
769 for (i
= 0; i
< RHASH_AR_TABLE_MAX_BOUND
; i
++) {
770 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
771 st_add_direct(new_tab
, pair
->key
, pair
->val
);
773 ar_free_and_clear_table(hash
);
774 RHASH_ST_TABLE_SET(hash
, new_tab
);
779 ar_force_convert_table(VALUE hash
, const char *file
, int line
)
783 if (RHASH_ST_TABLE_P(hash
)) {
784 return RHASH_ST_TABLE(hash
);
787 if (RHASH_AR_TABLE(hash
)) {
788 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
790 #if defined(RHASH_CONVERT_TABLE_DEBUG) && RHASH_CONVERT_TABLE_DEBUG
791 rb_obj_info_dump(hash
);
792 fprintf(stderr
, "force_convert: %s:%d\n", file
, line
);
793 RB_DEBUG_COUNTER_INC(obj_hash_force_convert
);
796 new_tab
= st_init_table_with_size(&objhash
, RHASH_AR_TABLE_SIZE(hash
));
798 for (i
= 0; i
< bound
; i
++) {
799 if (ar_cleared_entry(hash
, i
)) continue;
801 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
802 st_add_direct(new_tab
, pair
->key
, pair
->val
);
804 ar_free_and_clear_table(hash
);
807 new_tab
= st_init_table(&objhash
);
809 RHASH_ST_TABLE_SET(hash
, new_tab
);
815 hash_ar_table(VALUE hash
)
817 if (RHASH_TABLE_NULL_P(hash
)) {
818 ar_alloc_table(hash
);
820 return RHASH_AR_TABLE(hash
);
824 ar_compact_table(VALUE hash
)
826 const unsigned bound
= RHASH_AR_TABLE_BOUND(hash
);
827 const unsigned size
= RHASH_AR_TABLE_SIZE(hash
);
834 ar_table_pair
*pairs
= RHASH_AR_TABLE(hash
)->pairs
;
836 for (i
=0; i
<bound
; i
++) {
837 if (ar_cleared_entry(hash
, i
)) {
839 for (; j
<bound
; j
++) {
840 if (!ar_cleared_entry(hash
, j
)) {
842 ar_hint_set_hint(hash
, i
, (st_hash_t
)ar_hint(hash
, j
));
843 ar_clear_entry(hash
, j
);
848 /* non-empty is not found */
854 HASH_ASSERT(i
<=bound
);
856 RHASH_AR_TABLE_BOUND_SET(hash
, size
);
863 ar_add_direct_with_hash(VALUE hash
, st_data_t key
, st_data_t val
, st_hash_t hash_value
)
865 unsigned bin
= RHASH_AR_TABLE_BOUND(hash
);
867 if (RHASH_AR_TABLE_SIZE(hash
) >= RHASH_AR_TABLE_MAX_SIZE
) {
871 if (UNLIKELY(bin
>= RHASH_AR_TABLE_MAX_BOUND
)) {
872 bin
= ar_compact_table(hash
);
875 HASH_ASSERT(bin
< RHASH_AR_TABLE_MAX_BOUND
);
877 ar_set_entry(hash
, bin
, key
, val
, hash_value
);
878 RHASH_AR_TABLE_BOUND_SET(hash
, bin
+1);
879 RHASH_AR_TABLE_SIZE_INC(hash
);
885 ar_general_foreach(VALUE hash
, st_foreach_check_callback_func
*func
, st_update_callback_func
*replace
, st_data_t arg
)
887 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
888 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
890 for (i
= 0; i
< bound
; i
++) {
891 if (ar_cleared_entry(hash
, i
)) continue;
893 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
894 enum st_retval retval
= (*func
)(pair
->key
, pair
->val
, arg
, 0);
895 /* pair may be not valid here because of theap */
905 VALUE key
= pair
->key
;
906 VALUE val
= pair
->val
;
907 retval
= (*replace
)(&key
, &val
, arg
, TRUE
);
909 // TODO: pair should be same as pair before.
910 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
916 ar_clear_entry(hash
, i
);
917 RHASH_AR_TABLE_SIZE_DEC(hash
);
926 ar_foreach_with_replace(VALUE hash
, st_foreach_check_callback_func
*func
, st_update_callback_func
*replace
, st_data_t arg
)
928 return ar_general_foreach(hash
, func
, replace
, arg
);
932 st_foreach_callback_func
*func
;
937 apply_functor(st_data_t k
, st_data_t v
, st_data_t d
, int _
)
939 const struct functor
*f
= (void *)d
;
940 return f
->func(k
, v
, f
->arg
);
944 ar_foreach(VALUE hash
, st_foreach_callback_func
*func
, st_data_t arg
)
946 const struct functor f
= { func
, arg
};
947 return ar_general_foreach(hash
, apply_functor
, NULL
, (st_data_t
)&f
);
951 ar_foreach_check(VALUE hash
, st_foreach_check_callback_func
*func
, st_data_t arg
,
954 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
955 unsigned i
, ret
= 0, bound
= RHASH_AR_TABLE_BOUND(hash
);
956 enum st_retval retval
;
961 for (i
= 0; i
< bound
; i
++) {
962 if (ar_cleared_entry(hash
, i
)) continue;
964 pair
= RHASH_AR_TABLE_REF(hash
, i
);
966 hint
= ar_hint(hash
, i
);
968 retval
= (*func
)(key
, pair
->val
, arg
, 0);
973 pair
= RHASH_AR_TABLE_REF(hash
, i
);
974 if (pair
->key
== never
) break;
975 ret
= ar_find_entry_hint(hash
, hint
, key
);
976 if (ret
== RHASH_AR_TABLE_MAX_BOUND
) {
977 retval
= (*func
)(0, 0, arg
, 1);
987 if (!ar_cleared_entry(hash
, i
)) {
988 ar_clear_entry(hash
, i
);
989 RHASH_AR_TABLE_SIZE_DEC(hash
);
1000 ar_update(VALUE hash
, st_data_t key
,
1001 st_update_callback_func
*func
, st_data_t arg
)
1003 int retval
, existing
;
1004 unsigned bin
= RHASH_AR_TABLE_MAX_BOUND
;
1005 st_data_t value
= 0, old_key
;
1006 st_hash_t hash_value
= ar_do_hash(key
);
1008 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1009 // `#hash` changes ar_table -> st_table
1013 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
1014 bin
= ar_find_entry(hash
, hash_value
, key
);
1015 existing
= (bin
!= RHASH_AR_TABLE_MAX_BOUND
) ? TRUE
: FALSE
;
1018 hash_ar_table(hash
); /* allocate ltbl if needed */
1023 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, bin
);
1028 retval
= (*func
)(&key
, &value
, arg
, existing
);
1029 /* pair can be invalid here because of theap */
1034 if (ar_add_direct_with_hash(hash
, key
, value
, hash_value
)) {
1039 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, bin
);
1040 if (old_key
!= key
) {
1048 ar_clear_entry(hash
, bin
);
1049 RHASH_AR_TABLE_SIZE_DEC(hash
);
1057 ar_insert(VALUE hash
, st_data_t key
, st_data_t value
)
1059 unsigned bin
= RHASH_AR_TABLE_BOUND(hash
);
1060 st_hash_t hash_value
= ar_do_hash(key
);
1062 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1063 // `#hash` changes ar_table -> st_table
1067 hash_ar_table(hash
); /* prepare ltbl */
1069 bin
= ar_find_entry(hash
, hash_value
, key
);
1070 if (bin
== RHASH_AR_TABLE_MAX_BOUND
) {
1071 if (RHASH_AR_TABLE_SIZE(hash
) >= RHASH_AR_TABLE_MAX_SIZE
) {
1074 else if (bin
>= RHASH_AR_TABLE_MAX_BOUND
) {
1075 bin
= ar_compact_table(hash
);
1076 hash_ar_table(hash
);
1078 HASH_ASSERT(bin
< RHASH_AR_TABLE_MAX_BOUND
);
1080 ar_set_entry(hash
, bin
, key
, value
, hash_value
);
1081 RHASH_AR_TABLE_BOUND_SET(hash
, bin
+1);
1082 RHASH_AR_TABLE_SIZE_INC(hash
);
1086 RHASH_AR_TABLE_REF(hash
, bin
)->val
= value
;
1092 ar_lookup(VALUE hash
, st_data_t key
, st_data_t
*value
)
1094 if (RHASH_AR_TABLE_SIZE(hash
) == 0) {
1098 st_hash_t hash_value
= ar_do_hash(key
);
1099 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1100 // `#hash` changes ar_table -> st_table
1101 return st_lookup(RHASH_ST_TABLE(hash
), key
, value
);
1103 unsigned bin
= ar_find_entry(hash
, hash_value
, key
);
1105 if (bin
== RHASH_AR_TABLE_MAX_BOUND
) {
1109 HASH_ASSERT(bin
< RHASH_AR_TABLE_MAX_BOUND
);
1110 if (value
!= NULL
) {
1111 *value
= RHASH_AR_TABLE_REF(hash
, bin
)->val
;
1119 ar_delete(VALUE hash
, st_data_t
*key
, st_data_t
*value
)
1122 st_hash_t hash_value
= ar_do_hash(*key
);
1124 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1125 // `#hash` changes ar_table -> st_table
1126 return st_delete(RHASH_ST_TABLE(hash
), key
, value
);
1129 bin
= ar_find_entry(hash
, hash_value
, *key
);
1131 if (bin
== RHASH_AR_TABLE_MAX_BOUND
) {
1132 if (value
!= 0) *value
= 0;
1137 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, bin
);
1140 ar_clear_entry(hash
, bin
);
1141 RHASH_AR_TABLE_SIZE_DEC(hash
);
1147 ar_shift(VALUE hash
, st_data_t
*key
, st_data_t
*value
)
1149 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
1150 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
1152 for (i
= 0; i
< bound
; i
++) {
1153 if (!ar_cleared_entry(hash
, i
)) {
1154 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
1155 if (value
!= 0) *value
= pair
->val
;
1157 ar_clear_entry(hash
, i
);
1158 RHASH_AR_TABLE_SIZE_DEC(hash
);
1163 if (value
!= NULL
) *value
= 0;
1168 ar_keys(VALUE hash
, st_data_t
*keys
, st_index_t size
)
1170 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
1171 st_data_t
*keys_start
= keys
, *keys_end
= keys
+ size
;
1173 for (i
= 0; i
< bound
; i
++) {
1174 if (keys
== keys_end
) {
1178 if (!ar_cleared_entry(hash
, i
)) {
1179 *keys
++ = RHASH_AR_TABLE_REF(hash
, i
)->key
;
1184 return keys
- keys_start
;
1188 ar_values(VALUE hash
, st_data_t
*values
, st_index_t size
)
1190 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
1191 st_data_t
*values_start
= values
, *values_end
= values
+ size
;
1193 for (i
= 0; i
< bound
; i
++) {
1194 if (values
== values_end
) {
1198 if (!ar_cleared_entry(hash
, i
)) {
1199 *values
++ = RHASH_AR_TABLE_REF(hash
, i
)->val
;
1204 return values
- values_start
;
1208 ar_copy(VALUE hash1
, VALUE hash2
)
1210 ar_table
*old_tab
= RHASH_AR_TABLE(hash2
);
1212 if (old_tab
!= NULL
) {
1213 ar_table
*new_tab
= RHASH_AR_TABLE(hash1
);
1214 if (new_tab
== NULL
) {
1215 new_tab
= (ar_table
*) rb_transient_heap_alloc(hash1
, sizeof(ar_table
));
1216 if (new_tab
!= NULL
) {
1217 RHASH_SET_TRANSIENT_FLAG(hash1
);
1220 RHASH_UNSET_TRANSIENT_FLAG(hash1
);
1221 new_tab
= (ar_table
*)ruby_xmalloc(sizeof(ar_table
));
1224 *new_tab
= *old_tab
;
1225 RHASH(hash1
)->ar_hint
.word
= RHASH(hash2
)->ar_hint
.word
;
1226 RHASH_AR_TABLE_BOUND_SET(hash1
, RHASH_AR_TABLE_BOUND(hash2
));
1227 RHASH_AR_TABLE_SIZE_SET(hash1
, RHASH_AR_TABLE_SIZE(hash2
));
1228 hash_ar_table_set(hash1
, new_tab
);
1230 rb_gc_writebarrier_remember(hash1
);
1234 RHASH_AR_TABLE_BOUND_SET(hash1
, RHASH_AR_TABLE_BOUND(hash2
));
1235 RHASH_AR_TABLE_SIZE_SET(hash1
, RHASH_AR_TABLE_SIZE(hash2
));
1237 if (RHASH_TRANSIENT_P(hash1
)) {
1238 RHASH_UNSET_TRANSIENT_FLAG(hash1
);
1240 else if (RHASH_AR_TABLE(hash1
)) {
1241 ruby_xfree(RHASH_AR_TABLE(hash1
));
1244 hash_ar_table_set(hash1
, NULL
);
1246 rb_gc_writebarrier_remember(hash1
);
1252 ar_clear(VALUE hash
)
1254 if (RHASH_AR_TABLE(hash
) != NULL
) {
1255 RHASH_AR_TABLE_SIZE_SET(hash
, 0);
1256 RHASH_AR_TABLE_BOUND_SET(hash
, 0);
1259 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash
) == 0);
1260 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash
) == 0);
1264 #if USE_TRANSIENT_HEAP
1266 rb_hash_transient_heap_evacuate(VALUE hash
, int promote
)
1268 if (RHASH_TRANSIENT_P(hash
)) {
1270 ar_table
*old_tab
= RHASH_AR_TABLE(hash
);
1272 if (UNLIKELY(old_tab
== NULL
)) {
1275 HASH_ASSERT(old_tab
!= NULL
);
1277 new_tab
= rb_transient_heap_alloc(hash
, sizeof(ar_table
));
1278 if (new_tab
== NULL
) promote
= true;
1281 new_tab
= ruby_xmalloc(sizeof(ar_table
));
1282 RHASH_UNSET_TRANSIENT_FLAG(hash
);
1284 *new_tab
= *old_tab
;
1285 hash_ar_table_set(hash
, new_tab
);
1291 typedef int st_foreach_func(st_data_t
, st_data_t
, st_data_t
);
1293 struct foreach_safe_arg
{
1295 st_foreach_func
*func
;
1300 foreach_safe_i(st_data_t key
, st_data_t value
, st_data_t args
, int error
)
1303 struct foreach_safe_arg
*arg
= (void *)args
;
1305 if (error
) return ST_STOP
;
1306 status
= (*arg
->func
)(key
, value
, arg
->arg
);
1307 if (status
== ST_CONTINUE
) {
1314 st_foreach_safe(st_table
*table
, st_foreach_func
*func
, st_data_t a
)
1316 struct foreach_safe_arg arg
;
1319 arg
.func
= (st_foreach_func
*)func
;
1321 if (st_foreach_check(table
, foreach_safe_i
, (st_data_t
)&arg
, 0)) {
1322 rb_raise(rb_eRuntimeError
, "hash modified during iteration");
1326 typedef int rb_foreach_func(VALUE
, VALUE
, VALUE
);
1328 struct hash_foreach_arg
{
1330 rb_foreach_func
*func
;
1335 hash_ar_foreach_iter(st_data_t key
, st_data_t value
, st_data_t argp
, int error
)
1337 struct hash_foreach_arg
*arg
= (struct hash_foreach_arg
*)argp
;
1340 if (error
) return ST_STOP
;
1341 status
= (*arg
->func
)((VALUE
)key
, (VALUE
)value
, arg
->arg
);
1342 /* TODO: rehash check? rb_raise(rb_eRuntimeError, "rehash occurred during iteration"); */
1356 hash_foreach_iter(st_data_t key
, st_data_t value
, st_data_t argp
, int error
)
1358 struct hash_foreach_arg
*arg
= (struct hash_foreach_arg
*)argp
;
1362 if (error
) return ST_STOP
;
1363 tbl
= RHASH_ST_TABLE(arg
->hash
);
1364 status
= (*arg
->func
)((VALUE
)key
, (VALUE
)value
, arg
->arg
);
1365 if (RHASH_ST_TABLE(arg
->hash
) != tbl
) {
1366 rb_raise(rb_eRuntimeError
, "rehash occurred during iteration");
1380 iter_lev_in_ivar(VALUE hash
)
1382 VALUE levval
= rb_ivar_get(hash
, id_hash_iter_lev
);
1383 HASH_ASSERT(FIXNUM_P(levval
));
1384 return FIX2INT(levval
);
1387 void rb_ivar_set_internal(VALUE obj
, ID id
, VALUE val
);
1390 iter_lev_in_ivar_set(VALUE hash
, int lev
)
1392 rb_ivar_set_internal(hash
, id_hash_iter_lev
, INT2FIX(lev
));
1396 iter_lev_in_flags(VALUE hash
)
1398 unsigned int u
= (unsigned int)((RBASIC(hash
)->flags
>> RHASH_LEV_SHIFT
) & RHASH_LEV_MAX
);
1403 RHASH_ITER_LEV(VALUE hash
)
1405 int lev
= iter_lev_in_flags(hash
);
1407 if (lev
== RHASH_LEV_MAX
) {
1408 return iter_lev_in_ivar(hash
);
1416 hash_iter_lev_inc(VALUE hash
)
1418 int lev
= iter_lev_in_flags(hash
);
1419 if (lev
== RHASH_LEV_MAX
) {
1420 lev
= iter_lev_in_ivar(hash
);
1421 iter_lev_in_ivar_set(hash
, lev
+1);
1425 RBASIC(hash
)->flags
= ((RBASIC(hash
)->flags
& ~RHASH_LEV_MASK
) | ((VALUE
)lev
<< RHASH_LEV_SHIFT
));
1426 if (lev
== RHASH_LEV_MAX
) {
1427 iter_lev_in_ivar_set(hash
, lev
);
1433 hash_iter_lev_dec(VALUE hash
)
1435 int lev
= iter_lev_in_flags(hash
);
1436 if (lev
== RHASH_LEV_MAX
) {
1437 lev
= iter_lev_in_ivar(hash
);
1438 HASH_ASSERT(lev
> 0);
1439 iter_lev_in_ivar_set(hash
, lev
-1);
1442 HASH_ASSERT(lev
> 0);
1443 RBASIC(hash
)->flags
= ((RBASIC(hash
)->flags
& ~RHASH_LEV_MASK
) | ((lev
-1) << RHASH_LEV_SHIFT
));
1448 hash_foreach_ensure_rollback(VALUE hash
)
1450 hash_iter_lev_inc(hash
);
1455 hash_foreach_ensure(VALUE hash
)
1457 hash_iter_lev_dec(hash
);
1462 rb_hash_stlike_foreach(VALUE hash
, st_foreach_callback_func
*func
, st_data_t arg
)
1464 if (RHASH_AR_TABLE_P(hash
)) {
1465 return ar_foreach(hash
, func
, arg
);
1468 return st_foreach(RHASH_ST_TABLE(hash
), func
, arg
);
1473 rb_hash_stlike_foreach_with_replace(VALUE hash
, st_foreach_check_callback_func
*func
, st_update_callback_func
*replace
, st_data_t arg
)
1475 if (RHASH_AR_TABLE_P(hash
)) {
1476 return ar_foreach_with_replace(hash
, func
, replace
, arg
);
1479 return st_foreach_with_replace(RHASH_ST_TABLE(hash
), func
, replace
, arg
);
1484 hash_foreach_call(VALUE arg
)
1486 VALUE hash
= ((struct hash_foreach_arg
*)arg
)->hash
;
1488 if (RHASH_AR_TABLE_P(hash
)) {
1489 ret
= ar_foreach_check(hash
, hash_ar_foreach_iter
,
1490 (st_data_t
)arg
, (st_data_t
)Qundef
);
1492 else if (RHASH_ST_TABLE_P(hash
)) {
1493 ret
= st_foreach_check(RHASH_ST_TABLE(hash
), hash_foreach_iter
,
1494 (st_data_t
)arg
, (st_data_t
)Qundef
);
1497 rb_raise(rb_eRuntimeError
, "ret: %d, hash modified during iteration", ret
);
1503 rb_hash_foreach(VALUE hash
, rb_foreach_func
*func
, VALUE farg
)
1505 struct hash_foreach_arg arg
;
1507 if (RHASH_TABLE_EMPTY_P(hash
))
1510 arg
.func
= (rb_foreach_func
*)func
;
1512 if (RB_OBJ_FROZEN(hash
)) {
1513 hash_foreach_call((VALUE
)&arg
);
1516 hash_iter_lev_inc(hash
);
1517 rb_ensure(hash_foreach_call
, (VALUE
)&arg
, hash_foreach_ensure
, hash
);
1523 hash_alloc_flags(VALUE klass
, VALUE flags
, VALUE ifnone
)
1525 const VALUE wb
= (RGENGC_WB_PROTECTED_HASH
? FL_WB_PROTECTED
: 0);
1526 NEWOBJ_OF(hash
, struct RHash
, klass
, T_HASH
| wb
| flags
);
1528 RHASH_SET_IFNONE((VALUE
)hash
, ifnone
);
1534 hash_alloc(VALUE klass
)
1536 return hash_alloc_flags(klass
, 0, Qnil
);
1540 empty_hash_alloc(VALUE klass
)
1542 RUBY_DTRACE_CREATE_HOOK(HASH
, 0);
1544 return hash_alloc(klass
);
1550 return hash_alloc(rb_cHash
);
1554 copy_compare_by_id(VALUE hash
, VALUE basis
)
1556 if (rb_hash_compare_by_id_p(basis
)) {
1557 return rb_hash_compare_by_id(hash
);
1562 MJIT_FUNC_EXPORTED VALUE
1563 rb_hash_new_with_size(st_index_t size
)
1565 VALUE ret
= rb_hash_new();
1569 else if (size
<= RHASH_AR_TABLE_MAX_SIZE
) {
1570 ar_alloc_table(ret
);
1573 RHASH_ST_TABLE_SET(ret
, st_init_table_with_size(&objhash
, size
));
1579 hash_copy(VALUE ret
, VALUE hash
)
1581 if (!RHASH_EMPTY_P(hash
)) {
1582 if (RHASH_AR_TABLE_P(hash
))
1584 else if (RHASH_ST_TABLE_P(hash
))
1585 RHASH_ST_TABLE_SET(ret
, st_copy(RHASH_ST_TABLE(hash
)));
1591 hash_dup_with_compare_by_id(VALUE hash
)
1593 return hash_copy(copy_compare_by_id(rb_hash_new(), hash
), hash
);
1597 hash_dup(VALUE hash
, VALUE klass
, VALUE flags
)
1599 return hash_copy(hash_alloc_flags(klass
, flags
, RHASH_IFNONE(hash
)),
1604 rb_hash_dup(VALUE hash
)
1606 const VALUE flags
= RBASIC(hash
)->flags
;
1607 VALUE ret
= hash_dup(hash
, rb_obj_class(hash
),
1608 flags
& (FL_EXIVAR
|RHASH_PROC_DEFAULT
));
1609 if (flags
& FL_EXIVAR
)
1610 rb_copy_generic_ivar(ret
, hash
);
1614 MJIT_FUNC_EXPORTED VALUE
1615 rb_hash_resurrect(VALUE hash
)
1617 VALUE ret
= hash_dup(hash
, rb_cHash
, 0);
1622 rb_hash_modify_check(VALUE hash
)
1624 rb_check_frozen(hash
);
1627 MJIT_FUNC_EXPORTED
struct st_table
*
1628 rb_hash_tbl_raw(VALUE hash
, const char *file
, int line
)
1630 return ar_force_convert_table(hash
, file
, line
);
1634 rb_hash_tbl(VALUE hash
, const char *file
, int line
)
1636 OBJ_WB_UNPROTECT(hash
);
1637 return rb_hash_tbl_raw(hash
, file
, line
);
1641 rb_hash_modify(VALUE hash
)
1643 rb_hash_modify_check(hash
);
1646 NORETURN(static void no_new_key(void));
1650 rb_raise(rb_eRuntimeError
, "can't add a new key into hash during iteration");
1653 struct update_callback_arg
{
1658 #define NOINSERT_UPDATE_CALLBACK(func) \
1660 func##_noinsert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1662 if (!existing) no_new_key(); \
1663 return func(key, val, (struct update_arg *)arg, existing); \
1667 func##_insert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1669 return func(key, val, (struct update_arg *)arg, existing); \
1674 st_update_callback_func
*func
;
1678 typedef int (*tbl_update_func
)(st_data_t
*, st_data_t
*, st_data_t
, int);
1681 rb_hash_stlike_update(VALUE hash
, st_data_t key
, st_update_callback_func
*func
, st_data_t arg
)
1683 if (RHASH_AR_TABLE_P(hash
)) {
1684 int result
= ar_update(hash
, key
, func
, arg
);
1686 ar_try_convert_table(hash
);
1693 return st_update(RHASH_ST_TABLE(hash
), key
, func
, arg
);
1697 tbl_update_modify(st_data_t
*key
, st_data_t
*val
, st_data_t arg
, int existing
)
1699 struct update_arg
*p
= (struct update_arg
*)arg
;
1700 st_data_t old_key
= *key
;
1701 st_data_t old_value
= *val
;
1702 VALUE hash
= p
->hash
;
1703 int ret
= (p
->func
)(key
, val
, arg
, existing
);
1708 if (!existing
|| *key
!= old_key
|| *val
!= old_value
)
1709 rb_hash_modify(hash
);
1711 RB_OBJ_WRITTEN(hash
, Qundef
, *key
);
1712 RB_OBJ_WRITTEN(hash
, Qundef
, *val
);
1716 rb_hash_modify(hash
);
1724 tbl_update(VALUE hash
, VALUE key
, tbl_update_func func
, st_data_t optional_arg
)
1726 struct update_arg arg
= {
1727 .arg
= optional_arg
,
1732 return rb_hash_stlike_update(hash
, key
, tbl_update_modify
, (st_data_t
)&arg
);
1735 #define UPDATE_CALLBACK(iter_lev, func) ((iter_lev) > 0 ? func##_noinsert : func##_insert)
1737 #define RHASH_UPDATE_ITER(h, iter_lev, key, func, a) do { \
1738 tbl_update((h), (key), UPDATE_CALLBACK((iter_lev), func), (st_data_t)(a)); \
1741 #define RHASH_UPDATE(hash, key, func, arg) \
1742 RHASH_UPDATE_ITER(hash, RHASH_ITER_LEV(hash), key, func, arg)
1745 set_proc_default(VALUE hash
, VALUE proc
)
1747 if (rb_proc_lambda_p(proc
)) {
1748 int n
= rb_proc_arity(proc
);
1750 if (n
!= 2 && (n
>= 0 || n
< -3)) {
1751 if (n
< 0) n
= -n
-1;
1752 rb_raise(rb_eTypeError
, "default_proc takes two arguments (2 for %d)", n
);
1756 FL_SET_RAW(hash
, RHASH_PROC_DEFAULT
);
1757 RHASH_SET_IFNONE(hash
, proc
);
1762 * Hash.new(default_value = nil) -> new_hash
1763 * Hash.new {|hash, key| ... } -> new_hash
1765 * Returns a new empty \Hash object.
1767 * The initial default value and initial default proc for the new hash
1768 * depend on which form above was used. See {Default Values}[#class-Hash-label-Default+Values].
1770 * If neither an argument nor a block given,
1771 * initializes both the default value and the default proc to <tt>nil</tt>:
1773 * h.default # => nil
1774 * h.default_proc # => nil
1776 * If argument <tt>default_value</tt> given but no block given,
1777 * initializes the default value to the given <tt>default_value</tt>
1778 * and the default proc to <tt>nil</tt>:
1779 * h = Hash.new(false)
1780 * h.default # => false
1781 * h.default_proc # => nil
1783 * If a block given but no argument, stores the block as the default proc
1784 * and sets the default value to <tt>nil</tt>:
1785 * h = Hash.new {|hash, key| "Default value for #{key}" }
1786 * h.default # => nil
1787 * h.default_proc.class # => Proc
1788 * h[:nosuch] # => "Default value for nosuch"
1792 rb_hash_initialize(int argc
, VALUE
*argv
, VALUE hash
)
1796 rb_hash_modify(hash
);
1797 if (rb_block_given_p()) {
1798 rb_check_arity(argc
, 0, 0);
1799 ifnone
= rb_block_proc();
1800 SET_PROC_DEFAULT(hash
, ifnone
);
1803 rb_check_arity(argc
, 0, 1);
1804 ifnone
= argc
== 0 ? Qnil
: argv
[0];
1805 RHASH_SET_IFNONE(hash
, ifnone
);
1813 * Hash[] -> new_empty_hash
1814 * Hash[hash] -> new_hash
1815 * Hash[ [*2_element_arrays] ] -> new_hash
1816 * Hash[*objects] -> new_hash
1818 * Returns a new \Hash object populated with the given objects, if any.
1821 * With no argument, returns a new empty \Hash.
1823 * When the single given argument is a \Hash, returns a new \Hash
1824 * populated with the entries from the given \Hash, excluding the
1825 * default value or proc.
1827 * h = {foo: 0, bar: 1, baz: 2}
1828 * Hash[h] # => {:foo=>0, :bar=>1, :baz=>2}
1830 * When the single given argument is an \Array of 2-element Arrays,
1831 * returns a new \Hash object wherein each 2-element array forms a
1834 * Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {:foo=>0, :bar=>1}
1836 * When the argument count is an even number;
1837 * returns a new \Hash object wherein each successive pair of arguments
1838 * has become a key-value entry:
1840 * Hash[:foo, 0, :bar, 1] # => {:foo=>0, :bar=>1}
1842 * Raises an exception if the argument list does not conform to any
1847 rb_hash_s_create(int argc
, VALUE
*argv
, VALUE klass
)
1852 tmp
= rb_hash_s_try_convert(Qnil
, argv
[0]);
1854 hash
= hash_alloc(klass
);
1855 hash_copy(hash
, tmp
);
1859 tmp
= rb_check_array_type(argv
[0]);
1863 hash
= hash_alloc(klass
);
1864 for (i
= 0; i
< RARRAY_LEN(tmp
); ++i
) {
1865 VALUE e
= RARRAY_AREF(tmp
, i
);
1866 VALUE v
= rb_check_array_type(e
);
1867 VALUE key
, val
= Qnil
;
1870 rb_raise(rb_eArgError
, "wrong element type %s at %ld (expected array)",
1871 rb_builtin_class_name(e
), i
);
1873 switch (RARRAY_LEN(v
)) {
1875 rb_raise(rb_eArgError
, "invalid number of elements (%ld for 1..2)",
1878 val
= RARRAY_AREF(v
, 1);
1880 key
= RARRAY_AREF(v
, 0);
1881 rb_hash_aset(hash
, key
, val
);
1887 if (argc
% 2 != 0) {
1888 rb_raise(rb_eArgError
, "odd number of arguments for Hash");
1891 hash
= hash_alloc(klass
);
1892 rb_hash_bulk_insert(argc
, argv
, hash
);
1897 MJIT_FUNC_EXPORTED VALUE
1898 rb_to_hash_type(VALUE hash
)
1900 return rb_convert_type_with_id(hash
, T_HASH
, "Hash", idTo_hash
);
1902 #define to_hash rb_to_hash_type
1905 rb_check_hash_type(VALUE hash
)
1907 return rb_check_convert_type_with_id(hash
, T_HASH
, "Hash", idTo_hash
);
1912 * Hash.try_convert(obj) -> obj, new_hash, or nil
1914 * If +obj+ is a \Hash object, returns +obj+.
1916 * Otherwise if +obj+ responds to <tt>:to_hash</tt>,
1917 * calls <tt>obj.to_hash</tt> and returns the result.
1919 * Returns +nil+ if +obj+ does not respond to <tt>:to_hash</tt>
1921 * Raises an exception unless <tt>obj.to_hash</tt> returns a \Hash object.
1924 rb_hash_s_try_convert(VALUE dummy
, VALUE hash
)
1926 return rb_check_hash_type(hash
);
1931 * Hash.ruby2_keywords_hash?(hash) -> true or false
1933 * Checks if a given hash is flagged by Module#ruby2_keywords (or
1934 * Proc#ruby2_keywords).
1935 * This method is not for casual use; debugging, researching, and
1936 * some truly necessary cases like serialization of arguments.
1938 * ruby2_keywords def foo(*args)
1939 * Hash.ruby2_keywords_hash?(args.last)
1941 * foo(k: 1) #=> true
1942 * foo({k: 1}) #=> false
1945 rb_hash_s_ruby2_keywords_hash_p(VALUE dummy
, VALUE hash
)
1947 Check_Type(hash
, T_HASH
);
1948 return RBOOL(RHASH(hash
)->basic
.flags
& RHASH_PASS_AS_KEYWORDS
);
1953 * Hash.ruby2_keywords_hash(hash) -> hash
1955 * Duplicates a given hash and adds a ruby2_keywords flag.
1956 * This method is not for casual use; debugging, researching, and
1957 * some truly necessary cases like deserialization of arguments.
1960 * h = Hash.ruby2_keywords_hash(h)
1964 * foo(*[h]) #=> 1 with neither a warning or an error
1967 rb_hash_s_ruby2_keywords_hash(VALUE dummy
, VALUE hash
)
1969 Check_Type(hash
, T_HASH
);
1970 hash
= rb_hash_dup(hash
);
1971 RHASH(hash
)->basic
.flags
|= RHASH_PASS_AS_KEYWORDS
;
1981 rb_hash_rehash_i(VALUE key
, VALUE value
, VALUE arg
)
1983 if (RHASH_AR_TABLE_P(arg
)) {
1984 ar_insert(arg
, (st_data_t
)key
, (st_data_t
)value
);
1987 st_insert(RHASH_ST_TABLE(arg
), (st_data_t
)key
, (st_data_t
)value
);
1994 * hash.rehash -> self
1996 * Rebuilds the hash table by recomputing the hash index for each key;
1997 * returns <tt>self</tt>.
1999 * The hash table becomes invalid if the hash value of a key
2000 * has changed after the entry was created.
2001 * See {Modifying an Active Hash Key}[#class-Hash-label-Modifying+an+Active+Hash+Key].
2005 rb_hash_rehash(VALUE hash
)
2010 if (RHASH_ITER_LEV(hash
) > 0) {
2011 rb_raise(rb_eRuntimeError
, "rehash during iteration");
2013 rb_hash_modify_check(hash
);
2014 if (RHASH_AR_TABLE_P(hash
)) {
2015 tmp
= hash_alloc(0);
2016 ar_alloc_table(tmp
);
2017 rb_hash_foreach(hash
, rb_hash_rehash_i
, (VALUE
)tmp
);
2018 ar_free_and_clear_table(hash
);
2020 ar_free_and_clear_table(tmp
);
2022 else if (RHASH_ST_TABLE_P(hash
)) {
2023 st_table
*old_tab
= RHASH_ST_TABLE(hash
);
2024 tmp
= hash_alloc(0);
2025 tbl
= st_init_table_with_size(old_tab
->type
, old_tab
->num_entries
);
2026 RHASH_ST_TABLE_SET(tmp
, tbl
);
2027 rb_hash_foreach(hash
, rb_hash_rehash_i
, (VALUE
)tmp
);
2028 st_free_table(old_tab
);
2029 RHASH_ST_TABLE_SET(hash
, tbl
);
2030 RHASH_ST_CLEAR(tmp
);
2037 call_default_proc(VALUE proc
, VALUE hash
, VALUE key
)
2039 VALUE args
[2] = {hash
, key
};
2040 return rb_proc_call_with_block(proc
, 2, args
, Qnil
);
2044 rb_hash_default_value(VALUE hash
, VALUE key
)
2046 if (LIKELY(rb_method_basic_definition_p(CLASS_OF(hash
), id_default
))) {
2047 VALUE ifnone
= RHASH_IFNONE(hash
);
2048 if (!FL_TEST(hash
, RHASH_PROC_DEFAULT
)) return ifnone
;
2049 if (key
== Qundef
) return Qnil
;
2050 return call_default_proc(ifnone
, hash
, key
);
2053 return rb_funcall(hash
, id_default
, 1, key
);
2058 hash_stlike_lookup(VALUE hash
, st_data_t key
, st_data_t
*pval
)
2062 if (RHASH_AR_TABLE_P(hash
)) {
2063 return ar_lookup(hash
, key
, pval
);
2066 return st_lookup(RHASH_ST_TABLE(hash
), key
, pval
);
2070 MJIT_FUNC_EXPORTED
int
2071 rb_hash_stlike_lookup(VALUE hash
, st_data_t key
, st_data_t
*pval
)
2073 return hash_stlike_lookup(hash
, key
, pval
);
2078 * hash[key] -> value
2080 * Returns the value associated with the given +key+, if found:
2081 * h = {foo: 0, bar: 1, baz: 2}
2084 * If +key+ is not found, returns a default value
2085 * (see {Default Values}[#class-Hash-label-Default+Values]):
2086 * h = {foo: 0, bar: 1, baz: 2}
2087 * h[:nosuch] # => nil
2091 rb_hash_aref(VALUE hash
, VALUE key
)
2095 if (hash_stlike_lookup(hash
, key
, &val
)) {
2099 return rb_hash_default_value(hash
, key
);
2104 rb_hash_lookup2(VALUE hash
, VALUE key
, VALUE def
)
2108 if (hash_stlike_lookup(hash
, key
, &val
)) {
2112 return def
; /* without Hash#default */
2117 rb_hash_lookup(VALUE hash
, VALUE key
)
2119 return rb_hash_lookup2(hash
, key
, Qnil
);
2124 * hash.fetch(key) -> object
2125 * hash.fetch(key, default_value) -> object
2126 * hash.fetch(key) {|key| ... } -> object
2128 * Returns the value for the given +key+, if found.
2129 * h = {foo: 0, bar: 1, baz: 2}
2130 * h.fetch(:bar) # => 1
2132 * If +key+ is not found and no block was given,
2133 * returns +default_value+:
2134 * {}.fetch(:nosuch, :default) # => :default
2136 * If +key+ is not found and a block was given,
2137 * yields +key+ to the block and returns the block's return value:
2138 * {}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
2140 * Raises KeyError if neither +default_value+ nor a block was given.
2142 * Note that this method does not use the values of either #default or #default_proc.
2146 rb_hash_fetch_m(int argc
, VALUE
*argv
, VALUE hash
)
2152 rb_check_arity(argc
, 1, 2);
2155 block_given
= rb_block_given_p();
2156 if (block_given
&& argc
== 2) {
2157 rb_warn("block supersedes default value argument");
2160 if (hash_stlike_lookup(hash
, key
, &val
)) {
2165 return rb_yield(key
);
2167 else if (argc
== 1) {
2168 VALUE desc
= rb_protect(rb_inspect
, key
, 0);
2170 desc
= rb_any_to_s(key
);
2172 desc
= rb_str_ellipsize(desc
, 65);
2173 rb_key_err_raise(rb_sprintf("key not found: %"PRIsVALUE
, desc
), hash
, key
);
2182 rb_hash_fetch(VALUE hash
, VALUE key
)
2184 return rb_hash_fetch_m(1, &key
, hash
);
2189 * hash.default -> object
2190 * hash.default(key) -> object
2192 * Returns the default value for the given +key+.
2193 * The returned value will be determined either by the default proc or by the default value.
2194 * See {Default Values}[#class-Hash-label-Default+Values].
2196 * With no argument, returns the current default value:
2198 * h.default # => nil
2200 * If +key+ is given, returns the default value for +key+,
2201 * regardless of whether that key exists:
2202 * h = Hash.new { |hash, key| hash[key] = "No key #{key}"}
2204 * h.default(:foo) # => "No key foo"
2208 rb_hash_default(int argc
, VALUE
*argv
, VALUE hash
)
2212 rb_check_arity(argc
, 0, 1);
2213 ifnone
= RHASH_IFNONE(hash
);
2214 if (FL_TEST(hash
, RHASH_PROC_DEFAULT
)) {
2215 if (argc
== 0) return Qnil
;
2216 return call_default_proc(ifnone
, hash
, argv
[0]);
2223 * hash.default = value -> object
2225 * Sets the default value to +value+; returns +value+:
2227 * h.default # => nil
2228 * h.default = false # => false
2229 * h.default # => false
2231 * See {Default Values}[#class-Hash-label-Default+Values].
2235 rb_hash_set_default(VALUE hash
, VALUE ifnone
)
2237 rb_hash_modify_check(hash
);
2238 SET_DEFAULT(hash
, ifnone
);
2244 * hash.default_proc -> proc or nil
2246 * Returns the default proc for +self+
2247 * (see {Default Values}[#class-Hash-label-Default+Values]):
2249 * h.default_proc # => nil
2250 * h.default_proc = proc {|hash, key| "Default value for #{key}" }
2251 * h.default_proc.class # => Proc
2255 rb_hash_default_proc(VALUE hash
)
2257 if (FL_TEST(hash
, RHASH_PROC_DEFAULT
)) {
2258 return RHASH_IFNONE(hash
);
2265 * hash.default_proc = proc -> proc
2267 * Sets the default proc for +self+ to +proc+:
2268 * (see {Default Values}[#class-Hash-label-Default+Values]):
2270 * h.default_proc # => nil
2271 * h.default_proc = proc { |hash, key| "Default value for #{key}" }
2272 * h.default_proc.class # => Proc
2273 * h.default_proc = nil
2274 * h.default_proc # => nil
2278 rb_hash_set_default_proc(VALUE hash
, VALUE proc
)
2282 rb_hash_modify_check(hash
);
2284 SET_DEFAULT(hash
, proc
);
2287 b
= rb_check_convert_type_with_id(proc
, T_DATA
, "Proc", idTo_proc
);
2288 if (NIL_P(b
) || !rb_obj_is_proc(b
)) {
2289 rb_raise(rb_eTypeError
,
2290 "wrong default_proc type %s (expected Proc)",
2291 rb_obj_classname(proc
));
2294 SET_PROC_DEFAULT(hash
, proc
);
2299 key_i(VALUE key
, VALUE value
, VALUE arg
)
2301 VALUE
*args
= (VALUE
*)arg
;
2303 if (rb_equal(value
, args
[0])) {
2312 * hash.key(value) -> key or nil
2314 * Returns the key for the first-found entry with the given +value+
2315 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
2316 * h = {foo: 0, bar: 2, baz: 2}
2317 * h.key(0) # => :foo
2318 * h.key(2) # => :bar
2320 * Returns +nil+ if so such value is found.
2324 rb_hash_key(VALUE hash
, VALUE value
)
2331 rb_hash_foreach(hash
, key_i
, (VALUE
)args
);
2337 rb_hash_stlike_delete(VALUE hash
, st_data_t
*pkey
, st_data_t
*pval
)
2339 if (RHASH_AR_TABLE_P(hash
)) {
2340 return ar_delete(hash
, pkey
, pval
);
2343 return st_delete(RHASH_ST_TABLE(hash
), pkey
, pval
);
2348 * delete a specified entry by a given key.
2349 * if there is the corresponding entry, return a value of the entry.
2350 * if there is no corresponding entry, return Qundef.
2353 rb_hash_delete_entry(VALUE hash
, VALUE key
)
2355 st_data_t ktmp
= (st_data_t
)key
, val
;
2357 if (rb_hash_stlike_delete(hash
, &ktmp
, &val
)) {
2366 * delete a specified entry by a given key.
2367 * if there is the corresponding entry, return a value of the entry.
2368 * if there is no corresponding entry, return Qnil.
2371 rb_hash_delete(VALUE hash
, VALUE key
)
2373 VALUE deleted_value
= rb_hash_delete_entry(hash
, key
);
2375 if (deleted_value
!= Qundef
) { /* likely pass */
2376 return deleted_value
;
2385 * hash.delete(key) -> value or nil
2386 * hash.delete(key) {|key| ... } -> object
2388 * Deletes the entry for the given +key+ and returns its associated value.
2390 * If no block is given and +key+ is found, deletes the entry and returns the associated value:
2391 * h = {foo: 0, bar: 1, baz: 2}
2392 * h.delete(:bar) # => 1
2393 * h # => {:foo=>0, :baz=>2}
2395 * If no block given and +key+ is not found, returns +nil+.
2397 * If a block is given and +key+ is found, ignores the block,
2398 * deletes the entry, and returns the associated value:
2399 * h = {foo: 0, bar: 1, baz: 2}
2400 * h.delete(:baz) { |key| raise 'Will never happen'} # => 2
2401 * h # => {:foo=>0, :bar=>1}
2403 * If a block is given and +key+ is not found,
2404 * calls the block and returns the block's return value:
2405 * h = {foo: 0, bar: 1, baz: 2}
2406 * h.delete(:nosuch) { |key| "Key #{key} not found" } # => "Key nosuch not found"
2407 * h # => {:foo=>0, :bar=>1, :baz=>2}
2411 rb_hash_delete_m(VALUE hash
, VALUE key
)
2415 rb_hash_modify_check(hash
);
2416 val
= rb_hash_delete_entry(hash
, key
);
2418 if (val
!= Qundef
) {
2422 if (rb_block_given_p()) {
2423 return rb_yield(key
);
2437 shift_i_safe(VALUE key
, VALUE value
, VALUE arg
)
2439 struct shift_var
*var
= (struct shift_var
*)arg
;
2448 * hash.shift -> [key, value] or nil
2450 * Removes the first hash entry
2451 * (see {Entry Order}[#class-Hash-label-Entry+Order]);
2452 * returns a 2-element \Array containing the removed key and value:
2453 * h = {foo: 0, bar: 1, baz: 2}
2454 * h.shift # => [:foo, 0]
2455 * h # => {:bar=>1, :baz=>2}
2457 * Returns nil if the hash is empty.
2461 rb_hash_shift(VALUE hash
)
2463 struct shift_var var
;
2465 rb_hash_modify_check(hash
);
2466 if (RHASH_AR_TABLE_P(hash
)) {
2468 if (RHASH_ITER_LEV(hash
) == 0) {
2469 if (ar_shift(hash
, &var
.key
, &var
.val
)) {
2470 return rb_assoc_new(var
.key
, var
.val
);
2474 rb_hash_foreach(hash
, shift_i_safe
, (VALUE
)&var
);
2475 if (var
.key
!= Qundef
) {
2476 rb_hash_delete_entry(hash
, var
.key
);
2477 return rb_assoc_new(var
.key
, var
.val
);
2481 if (RHASH_ST_TABLE_P(hash
)) {
2483 if (RHASH_ITER_LEV(hash
) == 0) {
2484 if (st_shift(RHASH_ST_TABLE(hash
), &var
.key
, &var
.val
)) {
2485 return rb_assoc_new(var
.key
, var
.val
);
2489 rb_hash_foreach(hash
, shift_i_safe
, (VALUE
)&var
);
2490 if (var
.key
!= Qundef
) {
2491 rb_hash_delete_entry(hash
, var
.key
);
2492 return rb_assoc_new(var
.key
, var
.val
);
2500 delete_if_i(VALUE key
, VALUE value
, VALUE hash
)
2502 if (RTEST(rb_yield_values(2, key
, value
))) {
2503 rb_hash_modify(hash
);
2510 hash_enum_size(VALUE hash
, VALUE args
, VALUE eobj
)
2512 return rb_hash_size(hash
);
2517 * hash.delete_if {|key, value| ... } -> self
2518 * hash.delete_if -> new_enumerator
2520 * If a block given, calls the block with each key-value pair;
2521 * deletes each entry for which the block returns a truthy value;
2523 * h = {foo: 0, bar: 1, baz: 2}
2524 * h.delete_if {|key, value| value > 0 } # => {:foo=>0}
2526 * If no block given, returns a new \Enumerator:
2527 * h = {foo: 0, bar: 1, baz: 2}
2528 * e = h.delete_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:delete_if>
2529 * e.each { |key, value| value > 0 } # => {:foo=>0}
2533 rb_hash_delete_if(VALUE hash
)
2535 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2536 rb_hash_modify_check(hash
);
2537 if (!RHASH_TABLE_EMPTY_P(hash
)) {
2538 rb_hash_foreach(hash
, delete_if_i
, hash
);
2545 * hash.reject! {|key, value| ... } -> self or nil
2546 * hash.reject! -> new_enumerator
2548 * Returns +self+, whose remaining entries are those
2549 * for which the block returns +false+ or +nil+:
2550 * h = {foo: 0, bar: 1, baz: 2}
2551 * h.reject! {|key, value| value < 2 } # => {:baz=>2}
2553 * Returns +nil+ if no entries are removed.
2555 * Returns a new \Enumerator if no block given:
2556 * h = {foo: 0, bar: 1, baz: 2}
2557 * e = h.reject! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject!>
2558 * e.each {|key, value| key.start_with?('b') } # => {:foo=>0}
2562 rb_hash_reject_bang(VALUE hash
)
2566 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2567 rb_hash_modify(hash
);
2568 n
= RHASH_SIZE(hash
);
2569 if (!n
) return Qnil
;
2570 rb_hash_foreach(hash
, delete_if_i
, hash
);
2571 if (n
== RHASH_SIZE(hash
)) return Qnil
;
2577 * hash.reject {|key, value| ... } -> new_hash
2578 * hash.reject -> new_enumerator
2580 * Returns a new \Hash object whose entries are all those
2581 * from +self+ for which the block returns +false+ or +nil+:
2582 * h = {foo: 0, bar: 1, baz: 2}
2583 * h1 = h.reject {|key, value| key.start_with?('b') }
2586 * Returns a new \Enumerator if no block given:
2587 * h = {foo: 0, bar: 1, baz: 2}
2588 * e = h.reject # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject>
2589 * h1 = e.each {|key, value| key.start_with?('b') }
2594 rb_hash_reject(VALUE hash
)
2598 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2599 result
= hash_dup_with_compare_by_id(hash
);
2600 if (!RHASH_EMPTY_P(hash
)) {
2601 rb_hash_foreach(result
, delete_if_i
, result
);
2608 * hash.slice(*keys) -> new_hash
2610 * Returns a new \Hash object containing the entries for the given +keys+:
2611 * h = {foo: 0, bar: 1, baz: 2}
2612 * h.slice(:baz, :foo) # => {:baz=>2, :foo=>0}
2614 * Any given +keys+ that are not found are ignored.
2618 rb_hash_slice(int argc
, VALUE
*argv
, VALUE hash
)
2621 VALUE key
, value
, result
;
2623 if (argc
== 0 || RHASH_EMPTY_P(hash
)) {
2624 return copy_compare_by_id(rb_hash_new(), hash
);
2626 result
= copy_compare_by_id(rb_hash_new_with_size(argc
), hash
);
2628 for (i
= 0; i
< argc
; i
++) {
2630 value
= rb_hash_lookup2(hash
, key
, Qundef
);
2631 if (value
!= Qundef
)
2632 rb_hash_aset(result
, key
, value
);
2640 * hsh.except(*keys) -> a_hash
2642 * Returns a new \Hash excluding entries for the given +keys+:
2643 * h = { a: 100, b: 200, c: 300 }
2644 * h.except(:a) #=> {:b=>200, :c=>300}
2646 * Any given +keys+ that are not found are ignored.
2650 rb_hash_except(int argc
, VALUE
*argv
, VALUE hash
)
2655 result
= hash_dup_with_compare_by_id(hash
);
2657 for (i
= 0; i
< argc
; i
++) {
2659 rb_hash_delete(result
, key
);
2667 * hash.values_at(*keys) -> new_array
2669 * Returns a new \Array containing values for the given +keys+:
2670 * h = {foo: 0, bar: 1, baz: 2}
2671 * h.values_at(:baz, :foo) # => [2, 0]
2673 * The {default values}[#class-Hash-label-Default+Values] are returned
2674 * for any keys that are not found:
2675 * h.values_at(:hello, :foo) # => [nil, 0]
2679 rb_hash_values_at(int argc
, VALUE
*argv
, VALUE hash
)
2681 VALUE result
= rb_ary_new2(argc
);
2684 for (i
=0; i
<argc
; i
++) {
2685 rb_ary_push(result
, rb_hash_aref(hash
, argv
[i
]));
2692 * hash.fetch_values(*keys) -> new_array
2693 * hash.fetch_values(*keys) {|key| ... } -> new_array
2695 * Returns a new \Array containing the values associated with the given keys *keys:
2696 * h = {foo: 0, bar: 1, baz: 2}
2697 * h.fetch_values(:baz, :foo) # => [2, 0]
2699 * Returns a new empty \Array if no arguments given.
2701 * When a block is given, calls the block with each missing key,
2702 * treating the block's return value as the value for that key:
2703 * h = {foo: 0, bar: 1, baz: 2}
2704 * values = h.fetch_values(:bar, :foo, :bad, :bam) {|key| key.to_s}
2705 * values # => [1, 0, "bad", "bam"]
2707 * When no block is given, raises an exception if any given key is not found.
2711 rb_hash_fetch_values(int argc
, VALUE
*argv
, VALUE hash
)
2713 VALUE result
= rb_ary_new2(argc
);
2716 for (i
=0; i
<argc
; i
++) {
2717 rb_ary_push(result
, rb_hash_fetch(hash
, argv
[i
]));
2723 keep_if_i(VALUE key
, VALUE value
, VALUE hash
)
2725 if (!RTEST(rb_yield_values(2, key
, value
))) {
2726 rb_hash_modify(hash
);
2734 * hash.select {|key, value| ... } -> new_hash
2735 * hash.select -> new_enumerator
2737 * Hash#filter is an alias for Hash#select.
2739 * Returns a new \Hash object whose entries are those for which the block returns a truthy value:
2740 * h = {foo: 0, bar: 1, baz: 2}
2741 * h.select {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2743 * Returns a new \Enumerator if no block given:
2744 * h = {foo: 0, bar: 1, baz: 2}
2745 * e = h.select # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select>
2746 * e.each {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2750 rb_hash_select(VALUE hash
)
2754 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2755 result
= hash_dup_with_compare_by_id(hash
);
2756 if (!RHASH_EMPTY_P(hash
)) {
2757 rb_hash_foreach(result
, keep_if_i
, result
);
2764 * hash.select! {|key, value| ... } -> self or nil
2765 * hash.select! -> new_enumerator
2767 * Hash#filter! is an alias for Hash#select!.
2769 * Returns +self+, whose entries are those for which the block returns a truthy value:
2770 * h = {foo: 0, bar: 1, baz: 2}
2771 * h.select! {|key, value| value < 2 } => {:foo=>0, :bar=>1}
2773 * Returns +nil+ if no entries were removed.
2775 * Returns a new \Enumerator if no block given:
2776 * h = {foo: 0, bar: 1, baz: 2}
2777 * e = h.select! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select!>
2778 * e.each { |key, value| value < 2 } # => {:foo=>0, :bar=>1}
2782 rb_hash_select_bang(VALUE hash
)
2786 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2787 rb_hash_modify_check(hash
);
2788 n
= RHASH_SIZE(hash
);
2789 if (!n
) return Qnil
;
2790 rb_hash_foreach(hash
, keep_if_i
, hash
);
2791 if (n
== RHASH_SIZE(hash
)) return Qnil
;
2797 * hash.keep_if {|key, value| ... } -> self
2798 * hash.keep_if -> new_enumerator
2800 * Calls the block for each key-value pair;
2801 * retains the entry if the block returns a truthy value;
2802 * otherwise deletes the entry; returns +self+.
2803 * h = {foo: 0, bar: 1, baz: 2}
2804 * h.keep_if { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2806 * Returns a new \Enumerator if no block given:
2807 * h = {foo: 0, bar: 1, baz: 2}
2808 * e = h.keep_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:keep_if>
2809 * e.each { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2813 rb_hash_keep_if(VALUE hash
)
2815 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2816 rb_hash_modify_check(hash
);
2817 if (!RHASH_TABLE_EMPTY_P(hash
)) {
2818 rb_hash_foreach(hash
, keep_if_i
, hash
);
2824 clear_i(VALUE key
, VALUE value
, VALUE dummy
)
2831 * hash.clear -> self
2833 * Removes all hash entries; returns +self+.
2837 rb_hash_clear(VALUE hash
)
2839 rb_hash_modify_check(hash
);
2841 if (RHASH_ITER_LEV(hash
) > 0) {
2842 rb_hash_foreach(hash
, clear_i
, 0);
2844 else if (RHASH_AR_TABLE_P(hash
)) {
2848 st_clear(RHASH_ST_TABLE(hash
));
2855 hash_aset(st_data_t
*key
, st_data_t
*val
, struct update_arg
*arg
, int existing
)
2862 rb_hash_key_str(VALUE key
)
2864 if (!RB_FL_ANY_RAW(key
, FL_EXIVAR
) && RBASIC_CLASS(key
) == rb_cString
) {
2865 return rb_fstring(key
);
2868 return rb_str_new_frozen(key
);
2873 hash_aset_str(st_data_t
*key
, st_data_t
*val
, struct update_arg
*arg
, int existing
)
2875 if (!existing
&& !RB_OBJ_FROZEN(*key
)) {
2876 *key
= rb_hash_key_str(*key
);
2878 return hash_aset(key
, val
, arg
, existing
);
2881 NOINSERT_UPDATE_CALLBACK(hash_aset
)
2882 NOINSERT_UPDATE_CALLBACK(hash_aset_str
)
2886 * hash[key] = value -> value
2887 * hash.store(key, value)
2889 * Hash#store is an alias for Hash#[]=.
2891 * Associates the given +value+ with the given +key+; returns +value+.
2893 * If the given +key+ exists, replaces its value with the given +value+;
2894 * the ordering is not affected
2895 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
2896 * h = {foo: 0, bar: 1}
2897 * h[:foo] = 2 # => 2
2898 * h.store(:bar, 3) # => 3
2899 * h # => {:foo=>2, :bar=>3}
2901 * If +key+ does not exist, adds the +key+ and +value+;
2902 * the new entry is last in the order
2903 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
2904 * h = {foo: 0, bar: 1}
2905 * h[:baz] = 2 # => 2
2906 * h.store(:bat, 3) # => 3
2907 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
2911 rb_hash_aset(VALUE hash
, VALUE key
, VALUE val
)
2913 int iter_lev
= RHASH_ITER_LEV(hash
);
2915 rb_hash_modify(hash
);
2917 if (RHASH_TABLE_NULL_P(hash
)) {
2918 if (iter_lev
> 0) no_new_key();
2919 ar_alloc_table(hash
);
2922 if (RHASH_TYPE(hash
) == &identhash
|| rb_obj_class(key
) != rb_cString
) {
2923 RHASH_UPDATE_ITER(hash
, iter_lev
, key
, hash_aset
, val
);
2926 RHASH_UPDATE_ITER(hash
, iter_lev
, key
, hash_aset_str
, val
);
2933 * hash.replace(other_hash) -> self
2935 * Replaces the entire contents of +self+ with the contents of +other_hash+;
2937 * h = {foo: 0, bar: 1, baz: 2}
2938 * h.replace({bat: 3, bam: 4}) # => {:bat=>3, :bam=>4}
2942 rb_hash_replace(VALUE hash
, VALUE hash2
)
2944 rb_hash_modify_check(hash
);
2945 if (hash
== hash2
) return hash
;
2946 if (RHASH_ITER_LEV(hash
) > 0) {
2947 rb_raise(rb_eRuntimeError
, "can't replace hash during iteration");
2949 hash2
= to_hash(hash2
);
2951 COPY_DEFAULT(hash
, hash2
);
2953 if (RHASH_AR_TABLE_P(hash
)) {
2954 ar_free_and_clear_table(hash
);
2957 st_free_table(RHASH_ST_TABLE(hash
));
2958 RHASH_ST_CLEAR(hash
);
2960 hash_copy(hash
, hash2
);
2961 if (RHASH_EMPTY_P(hash2
) && RHASH_ST_TABLE_P(hash2
)) {
2963 RHASH_ST_TABLE_SET(hash
, st_init_table_with_size(RHASH_TYPE(hash2
), 0));
2966 rb_gc_writebarrier_remember(hash
);
2973 * hash.length -> integer
2974 * hash.size -> integer
2976 * Returns the count of entries in +self+:
2977 * {foo: 0, bar: 1, baz: 2}.length # => 3
2979 * Hash#length is an alias for Hash#size.
2983 rb_hash_size(VALUE hash
)
2985 return INT2FIX(RHASH_SIZE(hash
));
2989 rb_hash_size_num(VALUE hash
)
2991 return (long)RHASH_SIZE(hash
);
2996 * hash.empty? -> true or false
2998 * Returns +true+ if there are no hash entries, +false+ otherwise:
2999 * {}.empty? # => true
3000 * {foo: 0, bar: 1, baz: 2}.empty? # => false
3004 rb_hash_empty_p(VALUE hash
)
3006 return RBOOL(RHASH_EMPTY_P(hash
));
3010 each_value_i(VALUE key
, VALUE value
, VALUE _
)
3018 * hash.each_value {|value| ... } -> self
3019 * hash.each_value -> new_enumerator
3021 * Calls the given block with each value; returns +self+:
3022 * h = {foo: 0, bar: 1, baz: 2}
3023 * h.each_value {|value| puts value } # => {:foo=>0, :bar=>1, :baz=>2}
3029 * Returns a new \Enumerator if no block given:
3030 * h = {foo: 0, bar: 1, baz: 2}
3031 * e = h.each_value # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_value>
3032 * h1 = e.each {|value| puts value }
3033 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3041 rb_hash_each_value(VALUE hash
)
3043 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3044 rb_hash_foreach(hash
, each_value_i
, 0);
3049 each_key_i(VALUE key
, VALUE value
, VALUE _
)
3057 * hash.each_key {|key| ... } -> self
3058 * hash.each_key -> new_enumerator
3060 * Calls the given block with each key; returns +self+:
3061 * h = {foo: 0, bar: 1, baz: 2}
3062 * h.each_key {|key| puts key } # => {:foo=>0, :bar=>1, :baz=>2}
3068 * Returns a new \Enumerator if no block given:
3069 * h = {foo: 0, bar: 1, baz: 2}
3070 * e = h.each_key # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_key>
3071 * h1 = e.each {|key| puts key }
3072 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3079 rb_hash_each_key(VALUE hash
)
3081 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3082 rb_hash_foreach(hash
, each_key_i
, 0);
3087 each_pair_i(VALUE key
, VALUE value
, VALUE _
)
3089 rb_yield(rb_assoc_new(key
, value
));
3094 each_pair_i_fast(VALUE key
, VALUE value
, VALUE _
)
3099 rb_yield_values2(2, argv
);
3105 * hash.each {|key, value| ... } -> self
3106 * hash.each_pair {|key, value| ... } -> self
3107 * hash.each -> new_enumerator
3108 * hash.each_pair -> new_enumerator
3110 * Hash#each is an alias for Hash#each_pair.
3112 * Calls the given block with each key-value pair; returns +self+:
3113 * h = {foo: 0, bar: 1, baz: 2}
3114 * h.each_pair {|key, value| puts "#{key}: #{value}"} # => {:foo=>0, :bar=>1, :baz=>2}
3120 * Returns a new \Enumerator if no block given:
3121 * h = {foo: 0, bar: 1, baz: 2}
3122 * e = h.each_pair # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_pair>
3123 * h1 = e.each {|key, value| puts "#{key}: #{value}"}
3124 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3132 rb_hash_each_pair(VALUE hash
)
3134 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3135 if (rb_block_pair_yield_optimizable())
3136 rb_hash_foreach(hash
, each_pair_i_fast
, 0);
3138 rb_hash_foreach(hash
, each_pair_i
, 0);
3142 struct transform_keys_args
{
3149 transform_keys_hash_i(VALUE key
, VALUE value
, VALUE transarg
)
3151 struct transform_keys_args
*p
= (void *)transarg
;
3152 VALUE trans
= p
->trans
, result
= p
->result
;
3153 VALUE new_key
= rb_hash_lookup2(trans
, key
, Qundef
);
3154 if (new_key
== Qundef
) {
3156 new_key
= rb_yield(key
);
3160 rb_hash_aset(result
, new_key
, value
);
3165 transform_keys_i(VALUE key
, VALUE value
, VALUE result
)
3167 VALUE new_key
= rb_yield(key
);
3168 rb_hash_aset(result
, new_key
, value
);
3174 * hash.transform_keys {|key| ... } -> new_hash
3175 * hash.transform_keys(hash2) -> new_hash
3176 * hash.transform_keys(hash2) {|other_key| ...} -> new_hash
3177 * hash.transform_keys -> new_enumerator
3179 * Returns a new \Hash object; each entry has:
3180 * * A key provided by the block.
3181 * * The value from +self+.
3183 * An optional hash argument can be provided to map keys to new keys.
3184 * Any key not given will be mapped using the provided block,
3185 * or remain the same if no block is given.
3188 * h = {foo: 0, bar: 1, baz: 2}
3189 * h1 = h.transform_keys {|key| key.to_s }
3190 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3192 * h.transform_keys(foo: :bar, bar: :foo)
3193 * #=> {bar: 0, foo: 1, baz: 2}
3195 * h.transform_keys(foo: :hello, &:to_s)
3196 * #=> {:hello=>0, "bar"=>1, "baz"=>2}
3198 * Overwrites values for duplicate keys:
3199 * h = {foo: 0, bar: 1, baz: 2}
3200 * h1 = h.transform_keys {|key| :bat }
3203 * Returns a new \Enumerator if no block given:
3204 * h = {foo: 0, bar: 1, baz: 2}
3205 * e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys>
3206 * h1 = e.each { |key| key.to_s }
3207 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3210 rb_hash_transform_keys(int argc
, VALUE
*argv
, VALUE hash
)
3213 struct transform_keys_args transarg
= {0};
3215 argc
= rb_check_arity(argc
, 0, 1);
3217 transarg
.trans
= to_hash(argv
[0]);
3218 transarg
.block_given
= rb_block_given_p();
3221 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3223 result
= rb_hash_new();
3224 if (!RHASH_EMPTY_P(hash
)) {
3225 if (transarg
.trans
) {
3226 transarg
.result
= result
;
3227 rb_hash_foreach(hash
, transform_keys_hash_i
, (VALUE
)&transarg
);
3230 rb_hash_foreach(hash
, transform_keys_i
, result
);
3237 static int flatten_i(VALUE key
, VALUE val
, VALUE ary
);
3241 * hash.transform_keys! {|key| ... } -> self
3242 * hash.transform_keys!(hash2) -> self
3243 * hash.transform_keys!(hash2) {|other_key| ...} -> self
3244 * hash.transform_keys! -> new_enumerator
3246 * Same as Hash#transform_keys but modifies the receiver in place
3247 * instead of returning a new hash.
3250 rb_hash_transform_keys_bang(int argc
, VALUE
*argv
, VALUE hash
)
3253 int block_given
= 0;
3255 argc
= rb_check_arity(argc
, 0, 1);
3257 trans
= to_hash(argv
[0]);
3258 block_given
= rb_block_given_p();
3261 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3263 rb_hash_modify_check(hash
);
3264 if (!RHASH_TABLE_EMPTY_P(hash
)) {
3266 VALUE new_keys
= hash_alloc(0);
3267 VALUE pairs
= rb_ary_tmp_new(RHASH_SIZE(hash
) * 2);
3268 rb_hash_foreach(hash
, flatten_i
, pairs
);
3269 for (i
= 0; i
< RARRAY_LEN(pairs
); i
+= 2) {
3270 VALUE key
= RARRAY_AREF(pairs
, i
), new_key
, val
;
3273 new_key
= rb_yield(key
);
3275 else if ((new_key
= rb_hash_lookup2(trans
, key
, Qundef
)) != Qundef
) {
3276 /* use the transformed key */
3278 else if (block_given
) {
3279 new_key
= rb_yield(key
);
3284 val
= RARRAY_AREF(pairs
, i
+1);
3285 if (!hash_stlike_lookup(new_keys
, key
, NULL
)) {
3286 rb_hash_stlike_delete(hash
, &key
, NULL
);
3288 rb_hash_aset(hash
, new_key
, val
);
3289 rb_hash_aset(new_keys
, new_key
, Qnil
);
3291 rb_ary_clear(pairs
);
3292 rb_hash_clear(new_keys
);
3298 transform_values_foreach_func(st_data_t key
, st_data_t value
, st_data_t argp
, int error
)
3304 transform_values_foreach_replace(st_data_t
*key
, st_data_t
*value
, st_data_t argp
, int existing
)
3306 VALUE new_value
= rb_yield((VALUE
)*value
);
3307 VALUE hash
= (VALUE
)argp
;
3308 rb_hash_modify(hash
);
3309 RB_OBJ_WRITE(hash
, value
, new_value
);
3315 * hash.transform_values {|value| ... } -> new_hash
3316 * hash.transform_values -> new_enumerator
3318 * Returns a new \Hash object; each entry has:
3319 * * A key from +self+.
3320 * * A value provided by the block.
3323 * h = {foo: 0, bar: 1, baz: 2}
3324 * h1 = h.transform_values {|value| value * 100}
3325 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3327 * Returns a new \Enumerator if no block given:
3328 * h = {foo: 0, bar: 1, baz: 2}
3329 * e = h.transform_values # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_values>
3330 * h1 = e.each { |value| value * 100}
3331 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3334 rb_hash_transform_values(VALUE hash
)
3338 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3339 result
= hash_dup_with_compare_by_id(hash
);
3340 SET_DEFAULT(result
, Qnil
);
3342 if (!RHASH_EMPTY_P(hash
)) {
3343 rb_hash_stlike_foreach_with_replace(result
, transform_values_foreach_func
, transform_values_foreach_replace
, result
);
3351 * hash.transform_values! {|value| ... } -> self
3352 * hash.transform_values! -> new_enumerator
3354 * Returns +self+, whose keys are unchanged, and whose values are determined by the given block.
3355 * h = {foo: 0, bar: 1, baz: 2}
3356 * h.transform_values! {|value| value * 100} # => {:foo=>0, :bar=>100, :baz=>200}
3358 * Returns a new \Enumerator if no block given:
3359 * h = {foo: 0, bar: 1, baz: 2}
3360 * e = h.transform_values! # => #<Enumerator: {:foo=>0, :bar=>100, :baz=>200}:transform_values!>
3361 * h1 = e.each {|value| value * 100}
3362 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3365 rb_hash_transform_values_bang(VALUE hash
)
3367 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3368 rb_hash_modify_check(hash
);
3370 if (!RHASH_TABLE_EMPTY_P(hash
)) {
3371 rb_hash_stlike_foreach_with_replace(hash
, transform_values_foreach_func
, transform_values_foreach_replace
, hash
);
3378 to_a_i(VALUE key
, VALUE value
, VALUE ary
)
3380 rb_ary_push(ary
, rb_assoc_new(key
, value
));
3386 * hash.to_a -> new_array
3388 * Returns a new \Array of 2-element \Array objects;
3389 * each nested \Array contains a key-value pair from +self+:
3390 * h = {foo: 0, bar: 1, baz: 2}
3391 * h.to_a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3395 rb_hash_to_a(VALUE hash
)
3399 ary
= rb_ary_new_capa(RHASH_SIZE(hash
));
3400 rb_hash_foreach(hash
, to_a_i
, ary
);
3406 inspect_i(VALUE key
, VALUE value
, VALUE str
)
3410 str2
= rb_inspect(key
);
3411 if (RSTRING_LEN(str
) > 1) {
3412 rb_str_buf_cat_ascii(str
, ", ");
3415 rb_enc_copy(str
, str2
);
3417 rb_str_buf_append(str
, str2
);
3418 rb_str_buf_cat_ascii(str
, "=>");
3419 str2
= rb_inspect(value
);
3420 rb_str_buf_append(str
, str2
);
3426 inspect_hash(VALUE hash
, VALUE dummy
, int recur
)
3430 if (recur
) return rb_usascii_str_new2("{...}");
3431 str
= rb_str_buf_new2("{");
3432 rb_hash_foreach(hash
, inspect_i
, str
);
3433 rb_str_buf_cat2(str
, "}");
3440 * hash.inspect -> new_string
3442 * Returns a new \String containing the hash entries:
3443 * h = {foo: 0, bar: 1, baz: 2}
3444 * h.inspect # => "{:foo=>0, :bar=>1, :baz=>2}"
3446 * Hash#to_s is an alias for Hash#inspect.
3450 rb_hash_inspect(VALUE hash
)
3452 if (RHASH_EMPTY_P(hash
))
3453 return rb_usascii_str_new2("{}");
3454 return rb_exec_recursive(inspect_hash
, hash
, 0);
3459 * hash.to_hash -> self
3464 rb_hash_to_hash(VALUE hash
)
3470 rb_hash_set_pair(VALUE hash
, VALUE arg
)
3474 pair
= rb_check_array_type(arg
);
3476 rb_raise(rb_eTypeError
, "wrong element type %s (expected array)",
3477 rb_builtin_class_name(arg
));
3479 if (RARRAY_LEN(pair
) != 2) {
3480 rb_raise(rb_eArgError
, "element has wrong array length (expected 2, was %ld)",
3483 rb_hash_aset(hash
, RARRAY_AREF(pair
, 0), RARRAY_AREF(pair
, 1));
3488 to_h_i(VALUE key
, VALUE value
, VALUE hash
)
3490 rb_hash_set_pair(hash
, rb_yield_values(2, key
, value
));
3495 rb_hash_to_h_block(VALUE hash
)
3497 VALUE h
= rb_hash_new_with_size(RHASH_SIZE(hash
));
3498 rb_hash_foreach(hash
, to_h_i
, h
);
3504 * hash.to_h -> self or new_hash
3505 * hash.to_h {|key, value| ... } -> new_hash
3507 * For an instance of \Hash, returns +self+.
3509 * For a subclass of \Hash, returns a new \Hash
3510 * containing the content of +self+.
3512 * When a block is given, returns a new \Hash object
3513 * whose content is based on the block;
3514 * the block should return a 2-element \Array object
3515 * specifying the key-value pair to be included in the returned \Array:
3516 * h = {foo: 0, bar: 1, baz: 2}
3517 * h1 = h.to_h {|key, value| [value, key] }
3518 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3522 rb_hash_to_h(VALUE hash
)
3524 if (rb_block_given_p()) {
3525 return rb_hash_to_h_block(hash
);
3527 if (rb_obj_class(hash
) != rb_cHash
) {
3528 const VALUE flags
= RBASIC(hash
)->flags
;
3529 hash
= hash_dup(hash
, rb_cHash
, flags
& RHASH_PROC_DEFAULT
);
3535 keys_i(VALUE key
, VALUE value
, VALUE ary
)
3537 rb_ary_push(ary
, key
);
3543 * hash.keys -> new_array
3545 * Returns a new \Array containing all keys in +self+:
3546 * h = {foo: 0, bar: 1, baz: 2}
3547 * h.keys # => [:foo, :bar, :baz]
3550 MJIT_FUNC_EXPORTED VALUE
3551 rb_hash_keys(VALUE hash
)
3553 st_index_t size
= RHASH_SIZE(hash
);
3554 VALUE keys
= rb_ary_new_capa(size
);
3556 if (size
== 0) return keys
;
3558 if (ST_DATA_COMPATIBLE_P(VALUE
)) {
3559 RARRAY_PTR_USE_TRANSIENT(keys
, ptr
, {
3560 if (RHASH_AR_TABLE_P(hash
)) {
3561 size
= ar_keys(hash
, ptr
, size
);
3564 st_table
*table
= RHASH_ST_TABLE(hash
);
3565 size
= st_keys(table
, ptr
, size
);
3568 rb_gc_writebarrier_remember(keys
);
3569 rb_ary_set_len(keys
, size
);
3572 rb_hash_foreach(hash
, keys_i
, keys
);
3579 values_i(VALUE key
, VALUE value
, VALUE ary
)
3581 rb_ary_push(ary
, value
);
3587 * hash.values -> new_array
3589 * Returns a new \Array containing all values in +self+:
3590 * h = {foo: 0, bar: 1, baz: 2}
3591 * h.values # => [0, 1, 2]
3595 rb_hash_values(VALUE hash
)
3598 st_index_t size
= RHASH_SIZE(hash
);
3600 values
= rb_ary_new_capa(size
);
3601 if (size
== 0) return values
;
3603 if (ST_DATA_COMPATIBLE_P(VALUE
)) {
3604 if (RHASH_AR_TABLE_P(hash
)) {
3605 rb_gc_writebarrier_remember(values
);
3606 RARRAY_PTR_USE_TRANSIENT(values
, ptr
, {
3607 size
= ar_values(hash
, ptr
, size
);
3610 else if (RHASH_ST_TABLE_P(hash
)) {
3611 st_table
*table
= RHASH_ST_TABLE(hash
);
3612 rb_gc_writebarrier_remember(values
);
3613 RARRAY_PTR_USE_TRANSIENT(values
, ptr
, {
3614 size
= st_values(table
, ptr
, size
);
3617 rb_ary_set_len(values
, size
);
3621 rb_hash_foreach(hash
, values_i
, values
);
3629 * hash.include?(key) -> true or false
3630 * hash.has_key?(key) -> true or false
3631 * hash.key?(key) -> true or false
3632 * hash.member?(key) -> true or false
3634 * Methods #has_key?, #key?, and #member? are aliases for \#include?.
3636 * Returns +true+ if +key+ is a key in +self+, otherwise +false+.
3639 MJIT_FUNC_EXPORTED VALUE
3640 rb_hash_has_key(VALUE hash
, VALUE key
)
3642 return RBOOL(hash_stlike_lookup(hash
, key
, NULL
));
3646 rb_hash_search_value(VALUE key
, VALUE value
, VALUE arg
)
3648 VALUE
*data
= (VALUE
*)arg
;
3650 if (rb_equal(value
, data
[1])) {
3659 * hash.has_value?(value) -> true or false
3660 * hash.value?(value) -> true or false
3662 * Method #value? is an alias for \#has_value?.
3664 * Returns +true+ if +value+ is a value in +self+, otherwise +false+.
3668 rb_hash_has_value(VALUE hash
, VALUE val
)
3674 rb_hash_foreach(hash
, rb_hash_search_value
, (VALUE
)data
);
3685 eql_i(VALUE key
, VALUE val1
, VALUE arg
)
3687 struct equal_data
*data
= (struct equal_data
*)arg
;
3690 if (!hash_stlike_lookup(data
->hash
, key
, &val2
)) {
3691 data
->result
= Qfalse
;
3695 if (!(data
->eql
? rb_eql(val1
, (VALUE
)val2
) : (int)rb_equal(val1
, (VALUE
)val2
))) {
3696 data
->result
= Qfalse
;
3704 recursive_eql(VALUE hash
, VALUE dt
, int recur
)
3706 struct equal_data
*data
;
3708 if (recur
) return Qtrue
; /* Subtle! */
3709 data
= (struct equal_data
*)dt
;
3710 data
->result
= Qtrue
;
3711 rb_hash_foreach(hash
, eql_i
, dt
);
3713 return data
->result
;
3717 hash_equal(VALUE hash1
, VALUE hash2
, int eql
)
3719 struct equal_data data
;
3721 if (hash1
== hash2
) return Qtrue
;
3722 if (!RB_TYPE_P(hash2
, T_HASH
)) {
3723 if (!rb_respond_to(hash2
, idTo_hash
)) {
3727 if (rb_eql(hash2
, hash1
)) {
3735 return rb_equal(hash2
, hash1
);
3738 if (RHASH_SIZE(hash1
) != RHASH_SIZE(hash2
))
3740 if (!RHASH_TABLE_EMPTY_P(hash1
) && !RHASH_TABLE_EMPTY_P(hash2
)) {
3741 if (RHASH_TYPE(hash1
) != RHASH_TYPE(hash2
)) {
3747 return rb_exec_recursive_paired(recursive_eql
, hash1
, hash2
, (VALUE
)&data
);
3752 if (!(rb_equal(RHASH_IFNONE(hash1
), RHASH_IFNONE(hash2
)) &&
3753 FL_TEST(hash1
, RHASH_PROC_DEFAULT
) == FL_TEST(hash2
, RHASH_PROC_DEFAULT
)))
3761 * hash == object -> true or false
3763 * Returns +true+ if all of the following are true:
3764 * * +object+ is a \Hash object.
3765 * * +hash+ and +object+ have the same keys (regardless of order).
3766 * * For each key +key+, <tt>hash[key] == object[key]</tt>.
3768 * Otherwise, returns +false+.
3771 * h1 = {foo: 0, bar: 1, baz: 2}
3772 * h2 = {foo: 0, bar: 1, baz: 2}
3773 * h1 == h2 # => true
3774 * h3 = {baz: 2, bar: 1, foo: 0}
3775 * h1 == h3 # => true
3779 rb_hash_equal(VALUE hash1
, VALUE hash2
)
3781 return hash_equal(hash1
, hash2
, FALSE
);
3786 * hash.eql? object -> true or false
3788 * Returns +true+ if all of the following are true:
3789 * * +object+ is a \Hash object.
3790 * * +hash+ and +object+ have the same keys (regardless of order).
3791 * * For each key +key+, <tt>h[key] eql? object[key]</tt>.
3793 * Otherwise, returns +false+.
3796 * h1 = {foo: 0, bar: 1, baz: 2}
3797 * h2 = {foo: 0, bar: 1, baz: 2}
3798 * h1.eql? h2 # => true
3799 * h3 = {baz: 2, bar: 1, foo: 0}
3800 * h1.eql? h3 # => true
3804 rb_hash_eql(VALUE hash1
, VALUE hash2
)
3806 return hash_equal(hash1
, hash2
, TRUE
);
3810 hash_i(VALUE key
, VALUE val
, VALUE arg
)
3812 st_index_t
*hval
= (st_index_t
*)arg
;
3813 st_index_t hdata
[2];
3815 hdata
[0] = rb_hash(key
);
3816 hdata
[1] = rb_hash(val
);
3817 *hval
^= st_hash(hdata
, sizeof(hdata
), 0);
3823 * hash.hash -> an_integer
3825 * Returns the \Integer hash-code for the hash.
3827 * Two \Hash objects have the same hash-code if their content is the same
3828 * (regardless or order):
3829 * h1 = {foo: 0, bar: 1, baz: 2}
3830 * h2 = {baz: 2, bar: 1, foo: 0}
3831 * h2.hash == h1.hash # => true
3832 * h2.eql? h1 # => true
3836 rb_hash_hash(VALUE hash
)
3838 st_index_t size
= RHASH_SIZE(hash
);
3839 st_index_t hval
= rb_hash_start(size
);
3840 hval
= rb_hash_uint(hval
, (st_index_t
)rb_hash_hash
);
3842 rb_hash_foreach(hash
, hash_i
, (VALUE
)&hval
);
3844 hval
= rb_hash_end(hval
);
3845 return ST2FIX(hval
);
3849 rb_hash_invert_i(VALUE key
, VALUE value
, VALUE hash
)
3851 rb_hash_aset(hash
, value
, key
);
3857 * hash.invert -> new_hash
3859 * Returns a new \Hash object with the each key-value pair inverted:
3860 * h = {foo: 0, bar: 1, baz: 2}
3862 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3864 * Overwrites any repeated new keys:
3865 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
3866 * h = {foo: 0, bar: 0, baz: 0}
3867 * h.invert # => {0=>:baz}
3871 rb_hash_invert(VALUE hash
)
3873 VALUE h
= rb_hash_new_with_size(RHASH_SIZE(hash
));
3875 rb_hash_foreach(hash
, rb_hash_invert_i
, h
);
3880 rb_hash_update_callback(st_data_t
*key
, st_data_t
*value
, struct update_arg
*arg
, int existing
)
3886 NOINSERT_UPDATE_CALLBACK(rb_hash_update_callback
)
3889 rb_hash_update_i(VALUE key
, VALUE value
, VALUE hash
)
3891 RHASH_UPDATE(hash
, key
, rb_hash_update_callback
, value
);
3896 rb_hash_update_block_callback(st_data_t
*key
, st_data_t
*value
, struct update_arg
*arg
, int existing
)
3898 st_data_t newvalue
= arg
->arg
;
3901 newvalue
= (st_data_t
)rb_yield_values(3, (VALUE
)*key
, (VALUE
)*value
, (VALUE
)newvalue
);
3907 NOINSERT_UPDATE_CALLBACK(rb_hash_update_block_callback
)
3910 rb_hash_update_block_i(VALUE key
, VALUE value
, VALUE hash
)
3912 RHASH_UPDATE(hash
, key
, rb_hash_update_block_callback
, value
);
3918 * hash.merge! -> self
3919 * hash.merge!(*other_hashes) -> self
3920 * hash.merge!(*other_hashes) { |key, old_value, new_value| ... } -> self
3922 * Merges each of +other_hashes+ into +self+; returns +self+.
3924 * Each argument in +other_hashes+ must be a \Hash.
3926 * \Method #update is an alias for \#merge!.
3928 * With arguments and no block:
3929 * * Returns +self+, after the given hashes are merged into it.
3930 * * The given hashes are merged left to right.
3931 * * Each new entry is added at the end.
3932 * * Each duplicate-key entry's value overwrites the previous value.
3935 * h = {foo: 0, bar: 1, baz: 2}
3936 * h1 = {bat: 3, bar: 4}
3937 * h2 = {bam: 5, bat:6}
3938 * h.merge!(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
3940 * With arguments and a block:
3941 * * Returns +self+, after the given hashes are merged.
3942 * * The given hashes are merged left to right.
3943 * * Each new-key entry is added at the end.
3944 * * For each duplicate key:
3945 * * Calls the block with the key and the old and new values.
3946 * * The block's return value becomes the new value for the entry.
3949 * h = {foo: 0, bar: 1, baz: 2}
3950 * h1 = {bat: 3, bar: 4}
3951 * h2 = {bam: 5, bat:6}
3952 * h3 = h.merge!(h1, h2) { |key, old_value, new_value| old_value + new_value }
3953 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
3955 * With no arguments:
3956 * * Returns +self+, unmodified.
3957 * * The block, if given, is ignored.
3960 * h = {foo: 0, bar: 1, baz: 2}
3961 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
3962 * h1 = h.merge! { |key, old_value, new_value| raise 'Cannot happen' }
3963 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3967 rb_hash_update(int argc
, VALUE
*argv
, VALUE self
)
3970 bool block_given
= rb_block_given_p();
3972 rb_hash_modify(self
);
3973 for (i
= 0; i
< argc
; i
++){
3974 VALUE hash
= to_hash(argv
[i
]);
3976 rb_hash_foreach(hash
, rb_hash_update_block_i
, self
);
3979 rb_hash_foreach(hash
, rb_hash_update_i
, self
);
3985 struct update_func_arg
{
3988 rb_hash_update_func
*func
;
3992 rb_hash_update_func_callback(st_data_t
*key
, st_data_t
*value
, struct update_arg
*arg
, int existing
)
3994 struct update_func_arg
*uf_arg
= (struct update_func_arg
*)arg
->arg
;
3995 VALUE newvalue
= uf_arg
->value
;
3998 newvalue
= (*uf_arg
->func
)((VALUE
)*key
, (VALUE
)*value
, newvalue
);
4004 NOINSERT_UPDATE_CALLBACK(rb_hash_update_func_callback
)
4007 rb_hash_update_func_i(VALUE key
, VALUE value
, VALUE arg0
)
4009 struct update_func_arg
*arg
= (struct update_func_arg
*)arg0
;
4010 VALUE hash
= arg
->hash
;
4013 RHASH_UPDATE(hash
, key
, rb_hash_update_func_callback
, (VALUE
)arg
);
4018 rb_hash_update_by(VALUE hash1
, VALUE hash2
, rb_hash_update_func
*func
)
4020 rb_hash_modify(hash1
);
4021 hash2
= to_hash(hash2
);
4023 struct update_func_arg arg
;
4026 rb_hash_foreach(hash2
, rb_hash_update_func_i
, (VALUE
)&arg
);
4029 rb_hash_foreach(hash2
, rb_hash_update_i
, hash1
);
4036 * hash.merge -> copy_of_self
4037 * hash.merge(*other_hashes) -> new_hash
4038 * hash.merge(*other_hashes) { |key, old_value, new_value| ... } -> new_hash
4040 * Returns the new \Hash formed by merging each of +other_hashes+
4041 * into a copy of +self+.
4043 * Each argument in +other_hashes+ must be a \Hash.
4047 * With arguments and no block:
4048 * * Returns the new \Hash object formed by merging each successive
4049 * \Hash in +other_hashes+ into +self+.
4050 * * Each new-key entry is added at the end.
4051 * * Each duplicate-key entry's value overwrites the previous value.
4054 * h = {foo: 0, bar: 1, baz: 2}
4055 * h1 = {bat: 3, bar: 4}
4056 * h2 = {bam: 5, bat:6}
4057 * h.merge(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
4059 * With arguments and a block:
4060 * * Returns a new \Hash object that is the merge of +self+ and each given hash.
4061 * * The given hashes are merged left to right.
4062 * * Each new-key entry is added at the end.
4063 * * For each duplicate key:
4064 * * Calls the block with the key and the old and new values.
4065 * * The block's return value becomes the new value for the entry.
4068 * h = {foo: 0, bar: 1, baz: 2}
4069 * h1 = {bat: 3, bar: 4}
4070 * h2 = {bam: 5, bat:6}
4071 * h3 = h.merge(h1, h2) { |key, old_value, new_value| old_value + new_value }
4072 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
4074 * With no arguments:
4075 * * Returns a copy of +self+.
4076 * * The block, if given, is ignored.
4079 * h = {foo: 0, bar: 1, baz: 2}
4080 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
4081 * h1 = h.merge { |key, old_value, new_value| raise 'Cannot happen' }
4082 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
4086 rb_hash_merge(int argc
, VALUE
*argv
, VALUE self
)
4088 return rb_hash_update(argc
, argv
, copy_compare_by_id(rb_hash_dup(self
), self
));
4092 assoc_cmp(VALUE a
, VALUE b
)
4094 return !RTEST(rb_equal(a
, b
));
4098 lookup2_call(VALUE arg
)
4100 VALUE
*args
= (VALUE
*)arg
;
4101 return rb_hash_lookup2(args
[0], args
[1], Qundef
);
4104 struct reset_hash_type_arg
{
4106 const struct st_hash_type
*orighash
;
4110 reset_hash_type(VALUE arg
)
4112 struct reset_hash_type_arg
*p
= (struct reset_hash_type_arg
*)arg
;
4113 HASH_ASSERT(RHASH_ST_TABLE_P(p
->hash
));
4114 RHASH_ST_TABLE(p
->hash
)->type
= p
->orighash
;
4119 assoc_i(VALUE key
, VALUE val
, VALUE arg
)
4121 VALUE
*args
= (VALUE
*)arg
;
4123 if (RTEST(rb_equal(args
[0], key
))) {
4124 args
[1] = rb_assoc_new(key
, val
);
4132 * hash.assoc(key) -> new_array or nil
4134 * If the given +key+ is found, returns a 2-element \Array containing that key and its value:
4135 * h = {foo: 0, bar: 1, baz: 2}
4136 * h.assoc(:bar) # => [:bar, 1]
4138 * Returns +nil+ if key +key+ is not found.
4142 rb_hash_assoc(VALUE hash
, VALUE key
)
4145 const struct st_hash_type
*orighash
;
4148 if (RHASH_EMPTY_P(hash
)) return Qnil
;
4150 ar_force_convert_table(hash
, __FILE__
, __LINE__
);
4151 HASH_ASSERT(RHASH_ST_TABLE_P(hash
));
4152 table
= RHASH_ST_TABLE(hash
);
4153 orighash
= table
->type
;
4155 if (orighash
!= &identhash
) {
4157 struct reset_hash_type_arg ensure_arg
;
4158 struct st_hash_type assochash
;
4160 assochash
.compare
= assoc_cmp
;
4161 assochash
.hash
= orighash
->hash
;
4162 table
->type
= &assochash
;
4165 ensure_arg
.hash
= hash
;
4166 ensure_arg
.orighash
= orighash
;
4167 value
= rb_ensure(lookup2_call
, (VALUE
)&args
, reset_hash_type
, (VALUE
)&ensure_arg
);
4168 if (value
!= Qundef
) return rb_assoc_new(key
, value
);
4173 rb_hash_foreach(hash
, assoc_i
, (VALUE
)args
);
4178 rassoc_i(VALUE key
, VALUE val
, VALUE arg
)
4180 VALUE
*args
= (VALUE
*)arg
;
4182 if (RTEST(rb_equal(args
[0], val
))) {
4183 args
[1] = rb_assoc_new(key
, val
);
4191 * hash.rassoc(value) -> new_array or nil
4193 * Returns a new 2-element \Array consisting of the key and value
4194 * of the first-found entry whose value is <tt>==</tt> to value
4195 * (see {Entry Order}[#class-Hash-label-Entry+Order]):
4196 * h = {foo: 0, bar: 1, baz: 1}
4197 * h.rassoc(1) # => [:bar, 1]
4199 * Returns +nil+ if no such value found.
4203 rb_hash_rassoc(VALUE hash
, VALUE obj
)
4209 rb_hash_foreach(hash
, rassoc_i
, (VALUE
)args
);
4214 flatten_i(VALUE key
, VALUE val
, VALUE ary
)
4220 rb_ary_cat(ary
, pair
, 2);
4227 * hash.flatten -> new_array
4228 * hash.flatten(level) -> new_array
4230 * Returns a new \Array object that is a 1-dimensional flattening of +self+.
4234 * By default, nested Arrays are not flattened:
4235 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4236 * h.flatten # => [:foo, 0, :bar, [:bat, 3], :baz, 2]
4238 * Takes the depth of recursive flattening from \Integer argument +level+:
4239 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4240 * h.flatten(1) # => [:foo, 0, :bar, [:bat, [:baz, [:bat]]]]
4241 * h.flatten(2) # => [:foo, 0, :bar, :bat, [:baz, [:bat]]]
4242 * h.flatten(3) # => [:foo, 0, :bar, :bat, :baz, [:bat]]
4243 * h.flatten(4) # => [:foo, 0, :bar, :bat, :baz, :bat]
4245 * When +level+ is negative, flattens all nested Arrays:
4246 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4247 * h.flatten(-1) # => [:foo, 0, :bar, :bat, :baz, :bat]
4248 * h.flatten(-2) # => [:foo, 0, :bar, :bat, :baz, :bat]
4250 * When +level+ is zero, returns the equivalent of #to_a :
4251 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4252 * h.flatten(0) # => [[:foo, 0], [:bar, [:bat, 3]], [:baz, 2]]
4253 * h.flatten(0) == h.to_a # => true
4257 rb_hash_flatten(int argc
, VALUE
*argv
, VALUE hash
)
4261 rb_check_arity(argc
, 0, 1);
4264 int level
= NUM2INT(argv
[0]);
4266 if (level
== 0) return rb_hash_to_a(hash
);
4268 ary
= rb_ary_new_capa(RHASH_SIZE(hash
) * 2);
4269 rb_hash_foreach(hash
, flatten_i
, ary
);
4273 VALUE ary_flatten_level
= INT2FIX(level
);
4274 rb_funcallv(ary
, id_flatten_bang
, 1, &ary_flatten_level
);
4276 else if (level
< 0) {
4277 /* flatten recursively */
4278 rb_funcallv(ary
, id_flatten_bang
, 0, 0);
4282 ary
= rb_ary_new_capa(RHASH_SIZE(hash
) * 2);
4283 rb_hash_foreach(hash
, flatten_i
, ary
);
4290 delete_if_nil(VALUE key
, VALUE value
, VALUE hash
)
4299 set_if_not_nil(VALUE key
, VALUE value
, VALUE hash
)
4301 if (!NIL_P(value
)) {
4302 rb_hash_aset(hash
, key
, value
);
4309 * hash.compact -> new_hash
4311 * Returns a copy of +self+ with all +nil+-valued entries removed:
4312 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4314 * h1 # => {:foo=>0, :baz=>2}
4318 rb_hash_compact(VALUE hash
)
4320 VALUE result
= rb_hash_new();
4321 if (!RHASH_EMPTY_P(hash
)) {
4322 rb_hash_foreach(hash
, set_if_not_nil
, result
);
4329 * hash.compact! -> self or nil
4331 * Returns +self+ with all its +nil+-valued entries removed (in place):
4332 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4333 * h.compact! # => {:foo=>0, :baz=>2}
4335 * Returns +nil+ if no entries were removed.
4339 rb_hash_compact_bang(VALUE hash
)
4342 rb_hash_modify_check(hash
);
4343 n
= RHASH_SIZE(hash
);
4345 rb_hash_foreach(hash
, delete_if_nil
, hash
);
4346 if (n
!= RHASH_SIZE(hash
))
4352 static st_table
*rb_init_identtable_with_size(st_index_t size
);
4356 * hash.compare_by_identity -> self
4358 * Sets +self+ to consider only identity in comparing keys;
4359 * two keys are considered the same only if they are the same object;
4362 * By default, these two object are considered to be the same key,
4363 * so +s1+ will overwrite +s0+:
4367 * h.compare_by_identity? # => false
4372 * After calling \#compare_by_identity, the keys are considered to be different,
4373 * and therefore do not overwrite each other:
4375 * h.compare_by_identity # => {}
4376 * h.compare_by_identity? # => true
4379 * h # => {"x"=>0, "x"=>1}
4383 rb_hash_compare_by_id(VALUE hash
)
4386 st_table
*identtable
;
4388 if (rb_hash_compare_by_id_p(hash
)) return hash
;
4390 rb_hash_modify_check(hash
);
4391 ar_force_convert_table(hash
, __FILE__
, __LINE__
);
4392 HASH_ASSERT(RHASH_ST_TABLE_P(hash
));
4394 tmp
= hash_alloc(0);
4395 identtable
= rb_init_identtable_with_size(RHASH_SIZE(hash
));
4396 RHASH_ST_TABLE_SET(tmp
, identtable
);
4397 rb_hash_foreach(hash
, rb_hash_rehash_i
, (VALUE
)tmp
);
4398 st_free_table(RHASH_ST_TABLE(hash
));
4399 RHASH_ST_TABLE_SET(hash
, identtable
);
4400 RHASH_ST_CLEAR(tmp
);
4407 * hash.compare_by_identity? -> true or false
4409 * Returns +true+ if #compare_by_identity has been called, +false+ otherwise.
4412 MJIT_FUNC_EXPORTED VALUE
4413 rb_hash_compare_by_id_p(VALUE hash
)
4415 return RBOOL(RHASH_ST_TABLE_P(hash
) && RHASH_ST_TABLE(hash
)->type
== &identhash
);
4419 rb_ident_hash_new(void)
4421 VALUE hash
= rb_hash_new();
4422 RHASH_ST_TABLE_SET(hash
, st_init_table(&identhash
));
4427 rb_ident_hash_new_with_size(st_index_t size
)
4429 VALUE hash
= rb_hash_new();
4430 RHASH_ST_TABLE_SET(hash
, st_init_table_with_size(&identhash
, size
));
4435 rb_init_identtable(void)
4437 return st_init_table(&identhash
);
4441 rb_init_identtable_with_size(st_index_t size
)
4443 return st_init_table_with_size(&identhash
, size
);
4447 any_p_i(VALUE key
, VALUE value
, VALUE arg
)
4449 VALUE ret
= rb_yield(rb_assoc_new(key
, value
));
4451 *(VALUE
*)arg
= Qtrue
;
4458 any_p_i_fast(VALUE key
, VALUE value
, VALUE arg
)
4460 VALUE ret
= rb_yield_values(2, key
, value
);
4462 *(VALUE
*)arg
= Qtrue
;
4469 any_p_i_pattern(VALUE key
, VALUE value
, VALUE arg
)
4471 VALUE ret
= rb_funcall(((VALUE
*)arg
)[1], idEqq
, 1, rb_assoc_new(key
, value
));
4473 *(VALUE
*)arg
= Qtrue
;
4481 * hash.any? -> true or false
4482 * hash.any?(object) -> true or false
4483 * hash.any? {|key, value| ... } -> true or false
4485 * Returns +true+ if any element satisfies a given criterion;
4486 * +false+ otherwise.
4488 * With no argument and no block,
4489 * returns +true+ if +self+ is non-empty; +false+ if empty.
4491 * With argument +object+ and no block,
4492 * returns +true+ if for any key +key+
4493 * <tt>h.assoc(key) == object</tt>:
4494 * h = {foo: 0, bar: 1, baz: 2}
4495 * h.any?([:bar, 1]) # => true
4496 * h.any?([:bar, 0]) # => false
4497 * h.any?([:baz, 1]) # => false
4499 * With no argument and a block,
4500 * calls the block with each key-value pair;
4501 * returns +true+ if the block returns any truthy value,
4502 * +false+ otherwise:
4503 * h = {foo: 0, bar: 1, baz: 2}
4504 * h.any? {|key, value| value < 3 } # => true
4505 * h.any? {|key, value| value > 3 } # => false
4509 rb_hash_any_p(int argc
, VALUE
*argv
, VALUE hash
)
4514 rb_check_arity(argc
, 0, 1);
4515 if (RHASH_EMPTY_P(hash
)) return Qfalse
;
4517 if (rb_block_given_p()) {
4518 rb_warn("given block not used");
4522 rb_hash_foreach(hash
, any_p_i_pattern
, (VALUE
)args
);
4525 if (!rb_block_given_p()) {
4526 /* yields pairs, never false */
4529 if (rb_block_pair_yield_optimizable())
4530 rb_hash_foreach(hash
, any_p_i_fast
, (VALUE
)args
);
4532 rb_hash_foreach(hash
, any_p_i
, (VALUE
)args
);
4539 * hash.dig(key, *identifiers) -> object
4541 * Finds and returns the object in nested objects
4542 * that is specified by +key+ and +identifiers+.
4543 * The nested objects may be instances of various classes.
4544 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
4547 * h = {foo: {bar: {baz: 2}}}
4548 * h.dig(:foo) # => {:bar=>{:baz=>2}}
4549 * h.dig(:foo, :bar) # => {:baz=>2}
4550 * h.dig(:foo, :bar, :baz) # => 2
4551 * h.dig(:foo, :bar, :BAZ) # => nil
4553 * Nested Hashes and Arrays:
4554 * h = {foo: {bar: [:a, :b, :c]}}
4555 * h.dig(:foo, :bar, 2) # => :c
4557 * This method will use the {default values}[#class-Hash-label-Default+Values]
4558 * for keys that are not present:
4559 * h = {foo: {bar: [:a, :b, :c]}}
4560 * h.dig(:hello) # => nil
4561 * h.default_proc = -> (hash, _key) { hash }
4562 * h.dig(:hello, :world) # => h
4563 * h.dig(:hello, :world, :foo, :bar, 2) # => :c
4567 rb_hash_dig(int argc
, VALUE
*argv
, VALUE self
)
4569 rb_check_arity(argc
, 1, UNLIMITED_ARGUMENTS
);
4570 self
= rb_hash_aref(self
, *argv
);
4571 if (!--argc
) return self
;
4573 return rb_obj_dig(argc
, argv
, self
, Qnil
);
4577 hash_le_i(VALUE key
, VALUE value
, VALUE arg
)
4579 VALUE
*args
= (VALUE
*)arg
;
4580 VALUE v
= rb_hash_lookup2(args
[0], key
, Qundef
);
4581 if (v
!= Qundef
&& rb_equal(value
, v
)) return ST_CONTINUE
;
4587 hash_le(VALUE hash1
, VALUE hash2
)
4592 rb_hash_foreach(hash1
, hash_le_i
, (VALUE
)args
);
4598 * hash <= other_hash -> true or false
4600 * Returns +true+ if +hash+ is a subset of +other_hash+, +false+ otherwise:
4601 * h1 = {foo: 0, bar: 1}
4602 * h2 = {foo: 0, bar: 1, baz: 2}
4603 * h1 <= h2 # => true
4604 * h2 <= h1 # => false
4605 * h1 <= h1 # => true
4608 rb_hash_le(VALUE hash
, VALUE other
)
4610 other
= to_hash(other
);
4611 if (RHASH_SIZE(hash
) > RHASH_SIZE(other
)) return Qfalse
;
4612 return hash_le(hash
, other
);
4617 * hash < other_hash -> true or false
4619 * Returns +true+ if +hash+ is a proper subset of +other_hash+, +false+ otherwise:
4620 * h1 = {foo: 0, bar: 1}
4621 * h2 = {foo: 0, bar: 1, baz: 2}
4623 * h2 < h1 # => false
4624 * h1 < h1 # => false
4627 rb_hash_lt(VALUE hash
, VALUE other
)
4629 other
= to_hash(other
);
4630 if (RHASH_SIZE(hash
) >= RHASH_SIZE(other
)) return Qfalse
;
4631 return hash_le(hash
, other
);
4636 * hash >= other_hash -> true or false
4638 * Returns +true+ if +hash+ is a superset of +other_hash+, +false+ otherwise:
4639 * h1 = {foo: 0, bar: 1, baz: 2}
4640 * h2 = {foo: 0, bar: 1}
4641 * h1 >= h2 # => true
4642 * h2 >= h1 # => false
4643 * h1 >= h1 # => true
4646 rb_hash_ge(VALUE hash
, VALUE other
)
4648 other
= to_hash(other
);
4649 if (RHASH_SIZE(hash
) < RHASH_SIZE(other
)) return Qfalse
;
4650 return hash_le(other
, hash
);
4655 * hash > other_hash -> true or false
4657 * Returns +true+ if +hash+ is a proper superset of +other_hash+, +false+ otherwise:
4658 * h1 = {foo: 0, bar: 1, baz: 2}
4659 * h2 = {foo: 0, bar: 1}
4661 * h2 > h1 # => false
4662 * h1 > h1 # => false
4665 rb_hash_gt(VALUE hash
, VALUE other
)
4667 other
= to_hash(other
);
4668 if (RHASH_SIZE(hash
) <= RHASH_SIZE(other
)) return Qfalse
;
4669 return hash_le(other
, hash
);
4673 hash_proc_call(RB_BLOCK_CALL_FUNC_ARGLIST(key
, hash
))
4675 rb_check_arity(argc
, 1, 1);
4676 return rb_hash_aref(hash
, *argv
);
4681 * hash.to_proc -> proc
4683 * Returns a \Proc object that maps a key to its value:
4684 * h = {foo: 0, bar: 1, baz: 2}
4686 * proc.class # => Proc
4687 * proc.call(:foo) # => 0
4688 * proc.call(:bar) # => 1
4689 * proc.call(:nosuch) # => nil
4692 rb_hash_to_proc(VALUE hash
)
4694 return rb_func_lambda_new(hash_proc_call
, hash
, 1, 1);
4698 rb_hash_deconstruct_keys(VALUE hash
, VALUE keys
)
4704 add_new_i(st_data_t
*key
, st_data_t
*val
, st_data_t arg
, int existing
)
4706 VALUE
*args
= (VALUE
*)arg
;
4707 if (existing
) return ST_STOP
;
4708 RB_OBJ_WRITTEN(args
[0], Qundef
, (VALUE
)*key
);
4709 RB_OBJ_WRITE(args
[0], (VALUE
*)val
, args
[1]);
4714 * add +key+ to +val+ pair if +hash+ does not contain +key+.
4715 * returns non-zero if +key+ was contained.
4718 rb_hash_add_new_element(VALUE hash
, VALUE key
, VALUE val
)
4726 if (RHASH_AR_TABLE_P(hash
)) {
4727 hash_ar_table(hash
);
4729 ret
= ar_update(hash
, (st_data_t
)key
, add_new_i
, (st_data_t
)args
);
4733 ar_try_convert_table(hash
);
4735 tbl
= RHASH_TBL_RAW(hash
);
4736 return st_update(tbl
, (st_data_t
)key
, add_new_i
, (st_data_t
)args
);
4741 key_stringify(VALUE key
)
4743 return (rb_obj_class(key
) == rb_cString
&& !RB_OBJ_FROZEN(key
)) ?
4744 rb_hash_key_str(key
) : key
;
4748 ar_bulk_insert(VALUE hash
, long argc
, const VALUE
*argv
)
4751 for (i
= 0; i
< argc
; ) {
4752 st_data_t k
= key_stringify(argv
[i
++]);
4753 st_data_t v
= argv
[i
++];
4754 ar_insert(hash
, k
, v
);
4755 RB_OBJ_WRITTEN(hash
, Qundef
, k
);
4756 RB_OBJ_WRITTEN(hash
, Qundef
, v
);
4761 rb_hash_bulk_insert(long argc
, const VALUE
*argv
, VALUE hash
)
4763 HASH_ASSERT(argc
% 2 == 0);
4765 st_index_t size
= argc
/ 2;
4767 if (RHASH_TABLE_NULL_P(hash
)) {
4768 if (size
<= RHASH_AR_TABLE_MAX_SIZE
) {
4769 hash_ar_table(hash
);
4772 RHASH_TBL_RAW(hash
);
4776 if (RHASH_AR_TABLE_P(hash
) &&
4777 (RHASH_AR_TABLE_SIZE(hash
) + size
<= RHASH_AR_TABLE_MAX_SIZE
)) {
4778 ar_bulk_insert(hash
, argc
, argv
);
4781 rb_hash_bulk_insert_into_st_table(argc
, argv
, hash
);
4786 static char **origenviron
;
4788 #define GET_ENVIRON(e) ((e) = rb_w32_get_environ())
4789 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
4790 static char **my_environ
;
4792 #define environ my_environ
4794 #define getenv(n) rb_w32_ugetenv(n)
4795 #elif defined(__APPLE__)
4797 #define environ (*_NSGetEnviron())
4798 #define GET_ENVIRON(e) (e)
4799 #define FREE_ENVIRON(e)
4801 extern char **environ
;
4802 #define GET_ENVIRON(e) (e)
4803 #define FREE_ENVIRON(e)
4805 #ifdef ENV_IGNORECASE
4806 #define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
4807 #define ENVNMATCH(s1, s2, n) (STRNCASECMP((s1), (s2), (n)) == 0)
4809 #define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
4810 #define ENVNMATCH(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
4813 #define ENV_LOCK() RB_VM_LOCK_ENTER()
4814 #define ENV_UNLOCK() RB_VM_LOCK_LEAVE()
4816 static inline rb_encoding
*
4820 return rb_utf8_encoding();
4822 return rb_locale_encoding();
4827 env_enc_str_new(const char *ptr
, long len
, rb_encoding
*enc
)
4829 VALUE str
= rb_external_str_new_with_enc(ptr
, len
, enc
);
4836 env_str_new(const char *ptr
, long len
)
4838 return env_enc_str_new(ptr
, len
, env_encoding());
4842 env_str_new2(const char *ptr
)
4844 if (!ptr
) return Qnil
;
4845 return env_str_new(ptr
, strlen(ptr
));
4849 getenv_with_lock(const char *name
)
4854 const char *val
= getenv(name
);
4855 ret
= env_str_new2(val
);
4862 has_env_with_lock(const char *name
)
4872 return val
? true : false;
4875 static const char TZ_ENV
[] = "TZ";
4883 rb_encoding
*enc
= rb_enc_get(str
);
4884 if (!rb_enc_asciicompat(enc
)) {
4885 rb_raise(rb_eArgError
, "bad environment variable %s: ASCII incompatible encoding: %s",
4886 name
, rb_enc_name(enc
));
4888 var
= RSTRING_PTR(str
);
4889 if (memchr(var
, '\0', RSTRING_LEN(str
))) {
4890 rb_raise(rb_eArgError
, "bad environment variable %s: contains null byte", name
);
4892 return rb_str_fill_terminator(str
, 1); /* ASCII compatible */
4895 #define get_env_ptr(var, val) \
4896 (var = get_env_cstr(val, #var))
4898 static inline const char *
4899 env_name(volatile VALUE
*s
)
4902 SafeStringValue(*s
);
4903 get_env_ptr(name
, *s
);
4907 #define env_name(s) env_name(&(s))
4909 static VALUE
env_aset(VALUE nm
, VALUE val
);
4912 reset_by_modified_env(const char *nam
)
4915 * ENV['TZ'] = nil has a special meaning.
4916 * TZ is no longer considered up-to-date and ruby call tzset() as needed.
4917 * It could be useful if sysadmin change /etc/localtime.
4918 * This hack might works only on Linux glibc.
4920 if (ENVMATCH(nam
, TZ_ENV
)) {
4921 ruby_reset_timezone();
4926 env_delete(VALUE name
)
4928 const char *nam
= env_name(name
);
4929 reset_by_modified_env(nam
);
4930 VALUE val
= getenv_with_lock(nam
);
4933 ruby_setenv(nam
, 0);
4940 * ENV.delete(name) -> value
4941 * ENV.delete(name) { |name| block } -> value
4942 * ENV.delete(missing_name) -> nil
4943 * ENV.delete(missing_name) { |name| block } -> block_value
4945 * Deletes the environment variable with +name+ if it exists and returns its value:
4947 * ENV.delete('foo') # => '0'
4949 * If a block is not given and the named environment variable does not exist, returns +nil+.
4951 * If a block given and the environment variable does not exist,
4952 * yields +name+ to the block and returns the value of the block:
4953 * ENV.delete('foo') { |name| name * 2 } # => "foofoo"
4955 * If a block given and the environment variable exists,
4956 * deletes the environment variable and returns its value (ignoring the block):
4958 * ENV.delete('foo') { |name| raise 'ignored' } # => "0"
4960 * Raises an exception if +name+ is invalid.
4961 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
4964 env_delete_m(VALUE obj
, VALUE name
)
4968 val
= env_delete(name
);
4969 if (NIL_P(val
) && rb_block_given_p()) val
= rb_yield(name
);
4975 * ENV[name] -> value
4977 * Returns the value for the environment variable +name+ if it exists:
4979 * ENV['foo'] # => "0"
4980 * Returns +nil+ if the named variable does not exist.
4982 * Raises an exception if +name+ is invalid.
4983 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
4986 rb_f_getenv(VALUE obj
, VALUE name
)
4988 const char *nam
= env_name(name
);
4989 VALUE env
= getenv_with_lock(nam
);
4995 * ENV.fetch(name) -> value
4996 * ENV.fetch(name, default) -> value
4997 * ENV.fetch(name) { |name| block } -> value
4999 * If +name+ is the name of an environment variable, returns its value:
5001 * ENV.fetch('foo') # => '0'
5002 * Otherwise if a block is given (but not a default value),
5003 * yields +name+ to the block and returns the block's return value:
5004 * ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string
5005 * Otherwise if a default value is given (but not a block), returns the default value:
5007 * ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string
5008 * If the environment variable does not exist and both default and block are given,
5009 * issues a warning ("warning: block supersedes default value argument"),
5010 * yields +name+ to the block, and returns the block's return value:
5011 * ENV.fetch('foo', :default) { |name| :block_return } # => :block_return
5012 * Raises KeyError if +name+ is valid, but not found,
5013 * and neither default value nor block is given:
5014 * ENV.fetch('foo') # Raises KeyError (key not found: "foo")
5015 * Raises an exception if +name+ is invalid.
5016 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
5019 env_fetch(int argc
, VALUE
*argv
, VALUE _
)
5026 rb_check_arity(argc
, 1, 2);
5028 block_given
= rb_block_given_p();
5029 if (block_given
&& argc
== 2) {
5030 rb_warn("block supersedes default value argument");
5032 nam
= env_name(key
);
5033 env
= getenv_with_lock(nam
);
5036 if (block_given
) return rb_yield(key
);
5038 rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE
"\"", key
), envtbl
, key
);
5045 #if defined(_WIN32) || (defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
5048 in_origenv(const char *str
)
5051 for (env
= origenviron
; *env
; ++env
) {
5052 if (*env
== str
) return 1;
5058 envix(const char *nam
)
5062 register int i
, len
= strlen(nam
);
5065 env
= GET_ENVIRON(environ
);
5066 for (i
= 0; env
[i
]; i
++) {
5067 if (ENVNMATCH(env
[i
],nam
,len
) && env
[i
][len
] == '=')
5068 break; /* memcmp must come first to avoid */
5069 } /* potential SEGV's */
5070 FREE_ENVIRON(environ
);
5077 getenvsize(const WCHAR
* p
)
5079 const WCHAR
* porg
= p
;
5080 while (*p
++) p
+= lstrlenW(p
) + 1;
5081 return p
- porg
+ 1;
5085 getenvblocksize(void)
5095 check_envsize(size_t n
)
5097 if (_WIN32_WINNT
< 0x0600 && rb_w32_osver() < 6) {
5098 /* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653(v=vs.85).aspx */
5099 /* Windows Server 2003 and Windows XP: The maximum size of the
5100 * environment block for the process is 32,767 characters. */
5101 WCHAR
* p
= GetEnvironmentStringsW();
5102 if (!p
) return -1; /* never happen */
5104 FreeEnvironmentStringsW(p
);
5105 if (n
>= getenvblocksize()) {
5113 #if defined(_WIN32) || \
5114 (defined(__sun) && !(defined(HAVE_SETENV) && defined(HAVE_UNSETENV)))
5116 NORETURN(static void invalid_envname(const char *name
));
5119 invalid_envname(const char *name
)
5121 rb_syserr_fail_str(EINVAL
, rb_sprintf("ruby_setenv(%s)", name
));
5125 check_envname(const char *name
)
5127 if (strchr(name
, '=')) {
5128 invalid_envname(name
);
5135 ruby_setenv(const char *name
, const char *value
)
5138 # if defined(MINGW_HAS_SECURE_API) || RUBY_MSVCRT_VERSION >= 80
5139 # define HAVE__WPUTENV_S 1
5146 check_envname(name
);
5147 len
= MultiByteToWideChar(CP_UTF8
, 0, name
, -1, NULL
, 0);
5150 len2
= MultiByteToWideChar(CP_UTF8
, 0, value
, -1, NULL
, 0);
5151 if (check_envsize((size_t)len
+ len2
)) { /* len and len2 include '\0' */
5152 goto fail
; /* 2 for '=' & '\0' */
5154 wname
= ALLOCV_N(WCHAR
, buf
, len
+ len2
);
5155 wvalue
= wname
+ len
;
5156 MultiByteToWideChar(CP_UTF8
, 0, name
, -1, wname
, len
);
5157 MultiByteToWideChar(CP_UTF8
, 0, value
, -1, wvalue
, len2
);
5158 #ifndef HAVE__WPUTENV_S
5159 wname
[len
-1] = L
'=';
5163 wname
= ALLOCV_N(WCHAR
, buf
, len
+ 1);
5164 MultiByteToWideChar(CP_UTF8
, 0, name
, -1, wname
, len
);
5165 wvalue
= wname
+ len
;
5167 #ifndef HAVE__WPUTENV_S
5168 wname
[len
-1] = L
'=';
5174 #ifndef HAVE__WPUTENV_S
5175 failed
= _wputenv(wname
);
5177 failed
= _wputenv_s(wname
, wvalue
);
5183 /* even if putenv() failed, clean up and try to delete the
5184 * variable from the system area. */
5185 if (!value
|| !*value
) {
5186 /* putenv() doesn't handle empty value */
5187 if (!SetEnvironmentVariable(name
, value
) &&
5188 GetLastError() != ERROR_ENVVAR_NOT_FOUND
) goto fail
;
5192 invalid_envname(name
);
5194 #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
5199 ret
= setenv(name
, value
, 1);
5203 if (ret
) rb_sys_fail_str(rb_sprintf("setenv(%s)", name
));
5206 #ifdef VOID_UNSETENV
5216 ret
= unsetenv(name
);
5220 if (ret
) rb_sys_fail_str(rb_sprintf("unsetenv(%s)", name
));
5224 /* Solaris 9 (or earlier) does not have setenv(3C) and unsetenv(3C). */
5225 /* The below code was tested on Solaris 10 by:
5226 % ./configure ac_cv_func_setenv=no ac_cv_func_unsetenv=no
5228 size_t len
, mem_size
;
5229 char **env_ptr
, *str
, *mem_ptr
;
5231 check_envname(name
);
5234 mem_size
= len
+ strlen(value
) + 2;
5235 mem_ptr
= malloc(mem_size
);
5236 if (mem_ptr
== NULL
)
5237 rb_sys_fail_str(rb_sprintf("malloc(%"PRIuSIZE
")", mem_size
));
5238 snprintf(mem_ptr
, mem_size
, "%s=%s", name
, value
);
5243 for (env_ptr
= GET_ENVIRON(environ
); (str
= *env_ptr
) != 0; ++env_ptr
) {
5244 if (!strncmp(str
, name
, len
) && str
[len
] == '=') {
5245 if (!in_origenv(str
)) free(str
);
5246 while ((env_ptr
[0] = env_ptr
[1]) != 0) env_ptr
++;
5257 ret
= putenv(mem_ptr
);
5263 rb_sys_fail_str(rb_sprintf("putenv(%s)", name
));
5272 i
= envix(name
); /* where does it go? */
5274 if (environ
== origenviron
) { /* need we copy environment? */
5279 for (max
= i
; environ
[max
]; max
++) ;
5280 tmpenv
= ALLOC_N(char*, max
+2);
5281 for (j
=0; j
<max
; j
++) /* copy environment */
5282 tmpenv
[j
] = ruby_strdup(environ
[j
]);
5284 environ
= tmpenv
; /* tell exec where it is now */
5288 char **envp
= origenviron
;
5289 while (*envp
&& *envp
!= environ
[i
]) envp
++;
5293 while (environ
[i
]) {
5294 environ
[i
] = environ
[i
+1];
5300 else { /* does not exist yet */
5301 if (!value
) goto finish
;
5302 REALLOC_N(environ
, char*, i
+2); /* just expand it a bit */
5303 environ
[i
+1] = 0; /* make sure it's null terminated */
5306 len
= strlen(name
) + strlen(value
) + 2;
5307 environ
[i
] = ALLOC_N(char, len
);
5308 snprintf(environ
[i
],len
,"%s=%s",name
,value
); /* all that work just for this */
5317 ruby_unsetenv(const char *name
)
5319 ruby_setenv(name
, 0);
5324 * ENV[name] = value -> value
5325 * ENV.store(name, value) -> value
5327 * ENV.store is an alias for ENV.[]=.
5329 * Creates, updates, or deletes the named environment variable, returning the value.
5330 * Both +name+ and +value+ may be instances of String.
5331 * See {Valid Names and Values}[#class-ENV-label-Valid+Names+and+Values].
5333 * - If the named environment variable does not exist:
5334 * - If +value+ is +nil+, does nothing.
5336 * ENV['foo'] = nil # => nil
5337 * ENV.include?('foo') # => false
5338 * ENV.store('bar', nil) # => nil
5339 * ENV.include?('bar') # => false
5340 * - If +value+ is not +nil+, creates the environment variable with +name+ and +value+:
5341 * # Create 'foo' using ENV.[]=.
5342 * ENV['foo'] = '0' # => '0'
5343 * ENV['foo'] # => '0'
5344 * # Create 'bar' using ENV.store.
5345 * ENV.store('bar', '1') # => '1'
5346 * ENV['bar'] # => '1'
5347 * - If the named environment variable exists:
5348 * - If +value+ is not +nil+, updates the environment variable with value +value+:
5349 * # Update 'foo' using ENV.[]=.
5350 * ENV['foo'] = '2' # => '2'
5351 * ENV['foo'] # => '2'
5352 * # Update 'bar' using ENV.store.
5353 * ENV.store('bar', '3') # => '3'
5354 * ENV['bar'] # => '3'
5355 * - If +value+ is +nil+, deletes the environment variable:
5356 * # Delete 'foo' using ENV.[]=.
5357 * ENV['foo'] = nil # => nil
5358 * ENV.include?('foo') # => false
5359 * # Delete 'bar' using ENV.store.
5360 * ENV.store('bar', nil) # => nil
5361 * ENV.include?('bar') # => false
5363 * Raises an exception if +name+ or +value+ is invalid.
5364 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
5367 env_aset_m(VALUE obj
, VALUE nm
, VALUE val
)
5369 return env_aset(nm
, val
);
5373 env_aset(VALUE nm
, VALUE val
)
5381 SafeStringValue(nm
);
5382 SafeStringValue(val
);
5383 /* nm can be modified in `val.to_str`, don't get `name` before
5384 * check for `val` */
5385 get_env_ptr(name
, nm
);
5386 get_env_ptr(value
, val
);
5388 ruby_setenv(name
, value
);
5389 reset_by_modified_env(name
);
5396 rb_encoding
*enc
= raw
? 0 : rb_locale_encoding();
5397 VALUE ary
= rb_ary_new();
5401 char **env
= GET_ENVIRON(environ
);
5403 char *s
= strchr(*env
, '=');
5405 const char *p
= *env
;
5407 VALUE e
= raw
? rb_utf8_str_new(p
, l
) : env_enc_str_new(p
, l
, enc
);
5408 rb_ary_push(ary
, e
);
5412 FREE_ENVIRON(environ
);
5421 * ENV.keys -> array of names
5423 * Returns all variable names in an Array:
5424 * ENV.replace('foo' => '0', 'bar' => '1')
5425 * ENV.keys # => ['bar', 'foo']
5426 * The order of the names is OS-dependent.
5427 * See {About Ordering}[#class-ENV-label-About+Ordering].
5429 * Returns the empty Array if ENV is empty.
5435 return env_keys(FALSE
);
5439 rb_env_size(VALUE ehash
, VALUE args
, VALUE eobj
)
5446 env
= GET_ENVIRON(environ
);
5447 for (; *env
; ++env
) {
5448 if (strchr(*env
, '=')) {
5452 FREE_ENVIRON(environ
);
5456 return LONG2FIX(cnt
);
5461 * ENV.each_key { |name| block } -> ENV
5462 * ENV.each_key -> an_enumerator
5464 * Yields each environment variable name:
5465 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5467 * ENV.each_key { |name| names.push(name) } # => ENV
5468 * names # => ["bar", "foo"]
5470 * Returns an Enumerator if no block given:
5471 * e = ENV.each_key # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_key>
5473 * e.each { |name| names.push(name) } # => ENV
5474 * names # => ["bar", "foo"]
5477 env_each_key(VALUE ehash
)
5482 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5483 keys
= env_keys(FALSE
);
5484 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5485 rb_yield(RARRAY_AREF(keys
, i
));
5493 VALUE ary
= rb_ary_new();
5497 char **env
= GET_ENVIRON(environ
);
5500 char *s
= strchr(*env
, '=');
5502 rb_ary_push(ary
, env_str_new2(s
+1));
5506 FREE_ENVIRON(environ
);
5515 * ENV.values -> array of values
5517 * Returns all environment variable values in an Array:
5518 * ENV.replace('foo' => '0', 'bar' => '1')
5519 * ENV.values # => ['1', '0']
5520 * The order of the values is OS-dependent.
5521 * See {About Ordering}[#class-ENV-label-About+Ordering].
5523 * Returns the empty Array if ENV is empty.
5526 env_f_values(VALUE _
)
5528 return env_values();
5533 * ENV.each_value { |value| block } -> ENV
5534 * ENV.each_value -> an_enumerator
5536 * Yields each environment variable value:
5537 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5539 * ENV.each_value { |value| values.push(value) } # => ENV
5540 * values # => ["1", "0"]
5542 * Returns an Enumerator if no block given:
5543 * e = ENV.each_value # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_value>
5545 * e.each { |value| values.push(value) } # => ENV
5546 * values # => ["1", "0"]
5549 env_each_value(VALUE ehash
)
5554 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5555 values
= env_values();
5556 for (i
=0; i
<RARRAY_LEN(values
); i
++) {
5557 rb_yield(RARRAY_AREF(values
, i
));
5564 * ENV.each { |name, value| block } -> ENV
5565 * ENV.each -> an_enumerator
5566 * ENV.each_pair { |name, value| block } -> ENV
5567 * ENV.each_pair -> an_enumerator
5569 * Yields each environment variable name and its value as a 2-element \Array:
5571 * ENV.each_pair { |name, value| h[name] = value } # => ENV
5572 * h # => {"bar"=>"1", "foo"=>"0"}
5574 * Returns an Enumerator if no block given:
5576 * e = ENV.each_pair # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_pair>
5577 * e.each { |name, value| h[name] = value } # => ENV
5578 * h # => {"bar"=>"1", "foo"=>"0"}
5581 env_each_pair(VALUE ehash
)
5585 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5587 VALUE ary
= rb_ary_new();
5591 char **env
= GET_ENVIRON(environ
);
5594 char *s
= strchr(*env
, '=');
5596 rb_ary_push(ary
, env_str_new(*env
, s
-*env
));
5597 rb_ary_push(ary
, env_str_new2(s
+1));
5601 FREE_ENVIRON(environ
);
5605 if (rb_block_pair_yield_optimizable()) {
5606 for (i
=0; i
<RARRAY_LEN(ary
); i
+=2) {
5607 rb_yield_values(2, RARRAY_AREF(ary
, i
), RARRAY_AREF(ary
, i
+1));
5611 for (i
=0; i
<RARRAY_LEN(ary
); i
+=2) {
5612 rb_yield(rb_assoc_new(RARRAY_AREF(ary
, i
), RARRAY_AREF(ary
, i
+1)));
5621 * ENV.reject! { |name, value| block } -> ENV or nil
5622 * ENV.reject! -> an_enumerator
5624 * Similar to ENV.delete_if, but returns +nil+ if no changes were made.
5626 * Yields each environment variable name and its value as a 2-element Array,
5627 * deleting each environment variable for which the block returns a truthy value,
5628 * and returning ENV (if any deletions) or +nil+ (if not):
5629 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5630 * ENV.reject! { |name, value| name.start_with?('b') } # => ENV
5631 * ENV # => {"foo"=>"0"}
5632 * ENV.reject! { |name, value| name.start_with?('b') } # => nil
5634 * Returns an Enumerator if no block given:
5635 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5636 * e = ENV.reject! # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:reject!>
5637 * e.each { |name, value| name.start_with?('b') } # => ENV
5638 * ENV # => {"foo"=>"0"}
5639 * e.each { |name, value| name.start_with?('b') } # => nil
5642 env_reject_bang(VALUE ehash
)
5648 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5649 keys
= env_keys(FALSE
);
5650 RBASIC_CLEAR_CLASS(keys
);
5651 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5652 VALUE val
= rb_f_getenv(Qnil
, RARRAY_AREF(keys
, i
));
5654 if (RTEST(rb_yield_values(2, RARRAY_AREF(keys
, i
), val
))) {
5655 env_delete(RARRAY_AREF(keys
, i
));
5661 if (del
== 0) return Qnil
;
5667 * ENV.delete_if { |name, value| block } -> ENV
5668 * ENV.delete_if -> an_enumerator
5670 * Yields each environment variable name and its value as a 2-element Array,
5671 * deleting each environment variable for which the block returns a truthy value,
5672 * and returning ENV (regardless of whether any deletions):
5673 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5674 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5675 * ENV # => {"foo"=>"0"}
5676 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5678 * Returns an Enumerator if no block given:
5679 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5680 * e = ENV.delete_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:delete_if!>
5681 * e.each { |name, value| name.start_with?('b') } # => ENV
5682 * ENV # => {"foo"=>"0"}
5683 * e.each { |name, value| name.start_with?('b') } # => ENV
5686 env_delete_if(VALUE ehash
)
5688 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5689 env_reject_bang(ehash
);
5695 * ENV.values_at(*names) -> array of values
5697 * Returns an Array containing the environment variable values associated with
5699 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5700 * ENV.values_at('foo', 'baz') # => ["0", "2"]
5702 * Returns +nil+ in the Array for each name that is not an ENV name:
5703 * ENV.values_at('foo', 'bat', 'bar', 'bam') # => ["0", nil, "1", nil]
5705 * Returns an empty \Array if no names given.
5707 * Raises an exception if any name is invalid.
5708 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
5711 env_values_at(int argc
, VALUE
*argv
, VALUE _
)
5716 result
= rb_ary_new();
5717 for (i
=0; i
<argc
; i
++) {
5718 rb_ary_push(result
, rb_f_getenv(Qnil
, argv
[i
]));
5725 * ENV.select { |name, value| block } -> hash of name/value pairs
5726 * ENV.select -> an_enumerator
5727 * ENV.filter { |name, value| block } -> hash of name/value pairs
5728 * ENV.filter -> an_enumerator
5730 * ENV.filter is an alias for ENV.select.
5732 * Yields each environment variable name and its value as a 2-element Array,
5733 * returning a Hash of the names and values for which the block returns a truthy value:
5734 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5735 * ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5736 * ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5738 * Returns an Enumerator if no block given:
5739 * e = ENV.select # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:select>
5740 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5741 * e = ENV.filter # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:filter>
5742 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5745 env_select(VALUE ehash
)
5751 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5752 result
= rb_hash_new();
5753 keys
= env_keys(FALSE
);
5754 for (i
= 0; i
< RARRAY_LEN(keys
); ++i
) {
5755 VALUE key
= RARRAY_AREF(keys
, i
);
5756 VALUE val
= rb_f_getenv(Qnil
, key
);
5758 if (RTEST(rb_yield_values(2, key
, val
))) {
5759 rb_hash_aset(result
, key
, val
);
5770 * ENV.select! { |name, value| block } -> ENV or nil
5771 * ENV.select! -> an_enumerator
5772 * ENV.filter! { |name, value| block } -> ENV or nil
5773 * ENV.filter! -> an_enumerator
5775 * ENV.filter! is an alias for ENV.select!.
5777 * Yields each environment variable name and its value as a 2-element Array,
5778 * deleting each entry for which the block returns +false+ or +nil+,
5779 * and returning ENV if any deletions made, or +nil+ otherwise:
5781 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5782 * ENV.select! { |name, value| name.start_with?('b') } # => ENV
5783 * ENV # => {"bar"=>"1", "baz"=>"2"}
5784 * ENV.select! { |name, value| true } # => nil
5786 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5787 * ENV.filter! { |name, value| name.start_with?('b') } # => ENV
5788 * ENV # => {"bar"=>"1", "baz"=>"2"}
5789 * ENV.filter! { |name, value| true } # => nil
5791 * Returns an Enumerator if no block given:
5793 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5794 * e = ENV.select! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:select!>
5795 * e.each { |name, value| name.start_with?('b') } # => ENV
5796 * ENV # => {"bar"=>"1", "baz"=>"2"}
5797 * e.each { |name, value| true } # => nil
5799 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5800 * e = ENV.filter! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:filter!>
5801 * e.each { |name, value| name.start_with?('b') } # => ENV
5802 * ENV # => {"bar"=>"1", "baz"=>"2"}
5803 * e.each { |name, value| true } # => nil
5806 env_select_bang(VALUE ehash
)
5812 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5813 keys
= env_keys(FALSE
);
5814 RBASIC_CLEAR_CLASS(keys
);
5815 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5816 VALUE val
= rb_f_getenv(Qnil
, RARRAY_AREF(keys
, i
));
5818 if (!RTEST(rb_yield_values(2, RARRAY_AREF(keys
, i
), val
))) {
5819 env_delete(RARRAY_AREF(keys
, i
));
5825 if (del
== 0) return Qnil
;
5831 * ENV.keep_if { |name, value| block } -> ENV
5832 * ENV.keep_if -> an_enumerator
5834 * Yields each environment variable name and its value as a 2-element Array,
5835 * deleting each environment variable for which the block returns +false+ or +nil+,
5836 * and returning ENV:
5837 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5838 * ENV.keep_if { |name, value| name.start_with?('b') } # => ENV
5839 * ENV # => {"bar"=>"1", "baz"=>"2"}
5841 * Returns an Enumerator if no block given:
5842 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5843 * e = ENV.keep_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:keep_if>
5844 * e.each { |name, value| name.start_with?('b') } # => ENV
5845 * ENV # => {"bar"=>"1", "baz"=>"2"}
5848 env_keep_if(VALUE ehash
)
5850 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5851 env_select_bang(ehash
);
5857 * ENV.slice(*names) -> hash of name/value pairs
5859 * Returns a Hash of the given ENV names and their corresponding values:
5860 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2', 'bat' => '3')
5861 * ENV.slice('foo', 'baz') # => {"foo"=>"0", "baz"=>"2"}
5862 * ENV.slice('baz', 'foo') # => {"baz"=>"2", "foo"=>"0"}
5863 * Raises an exception if any of the +names+ is invalid
5864 * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]):
5865 * ENV.slice('foo', 'bar', :bat) # Raises TypeError (no implicit conversion of Symbol into String)
5868 env_slice(int argc
, VALUE
*argv
, VALUE _
)
5871 VALUE key
, value
, result
;
5874 return rb_hash_new();
5876 result
= rb_hash_new_with_size(argc
);
5878 for (i
= 0; i
< argc
; i
++) {
5880 value
= rb_f_getenv(Qnil
, key
);
5882 rb_hash_aset(result
, key
, value
);
5894 keys
= env_keys(TRUE
);
5895 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5896 VALUE key
= RARRAY_AREF(keys
, i
);
5897 const char *nam
= RSTRING_PTR(key
);
5898 ruby_setenv(nam
, 0);
5908 * Removes every environment variable; returns ENV:
5909 * ENV.replace('foo' => '0', 'bar' => '1')
5911 * ENV.clear # => ENV
5917 return rb_env_clear();
5924 * Returns String 'ENV':
5925 * ENV.to_s # => "ENV"
5930 return rb_usascii_str_new2("ENV");
5935 * ENV.inspect -> a_string
5937 * Returns the contents of the environment as a String:
5938 * ENV.replace('foo' => '0', 'bar' => '1')
5939 * ENV.inspect # => "{\"bar\"=>\"1\", \"foo\"=>\"0\"}"
5942 env_inspect(VALUE _
)
5945 VALUE str
= rb_str_buf_new2("{");
5949 char **env
= GET_ENVIRON(environ
);
5951 char *s
= strchr(*env
, '=');
5953 if (env
!= environ
) {
5954 rb_str_buf_cat2(str
, ", ");
5957 rb_str_buf_cat2(str
, "\"");
5958 rb_str_buf_cat(str
, *env
, s
-*env
);
5959 rb_str_buf_cat2(str
, "\"=>");
5960 i
= rb_inspect(rb_str_new2(s
+1));
5961 rb_str_buf_append(str
, i
);
5965 FREE_ENVIRON(environ
);
5969 rb_str_buf_cat2(str
, "}");
5976 * ENV.to_a -> array of 2-element arrays
5978 * Returns the contents of ENV as an Array of 2-element Arrays,
5979 * each of which is a name/value pair:
5980 * ENV.replace('foo' => '0', 'bar' => '1')
5981 * ENV.to_a # => [["bar", "1"], ["foo", "0"]]
5986 VALUE ary
= rb_ary_new();
5990 char **env
= GET_ENVIRON(environ
);
5992 char *s
= strchr(*env
, '=');
5994 rb_ary_push(ary
, rb_assoc_new(env_str_new(*env
, s
-*env
),
5995 env_str_new2(s
+1)));
5999 FREE_ENVIRON(environ
);
6010 * (Provided for compatibility with Hash.)
6012 * Does not modify ENV; returns +nil+.
6021 env_size_with_lock(void)
6027 char **env
= GET_ENVIRON(environ
);
6029 FREE_ENVIRON(environ
);
6038 * ENV.length -> an_integer
6039 * ENV.size -> an_integer
6041 * Returns the count of environment variables:
6042 * ENV.replace('foo' => '0', 'bar' => '1')
6049 return INT2FIX(env_size_with_lock());
6054 * ENV.empty? -> true or false
6056 * Returns +true+ when there are no environment variables, +false+ otherwise:
6058 * ENV.empty? # => true
6060 * ENV.empty? # => false
6063 env_empty_p(VALUE _
)
6069 char **env
= GET_ENVIRON(environ
);
6073 FREE_ENVIRON(environ
);
6077 return RBOOL(empty
);
6082 * ENV.include?(name) -> true or false
6083 * ENV.has_key?(name) -> true or false
6084 * ENV.member?(name) -> true or false
6085 * ENV.key?(name) -> true or false
6087 * ENV.has_key?, ENV.member?, and ENV.key? are aliases for ENV.include?.
6089 * Returns +true+ if there is an environment variable with the given +name+:
6090 * ENV.replace('foo' => '0', 'bar' => '1')
6091 * ENV.include?('foo') # => true
6092 * Returns +false+ if +name+ is a valid String and there is no such environment variable:
6093 * ENV.include?('baz') # => false
6094 * Returns +false+ if +name+ is the empty String or is a String containing character <code>'='</code>:
6095 * ENV.include?('') # => false
6096 * ENV.include?('=') # => false
6097 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6098 * ENV.include?("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6099 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6100 * ENV.include?("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6101 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6102 * Raises an exception if +name+ is not a String:
6103 * ENV.include?(Object.new) # TypeError (no implicit conversion of Object into String)
6106 env_has_key(VALUE env
, VALUE key
)
6108 const char *s
= env_name(key
);
6109 return RBOOL(has_env_with_lock(s
));
6114 * ENV.assoc(name) -> [name, value] or nil
6116 * Returns a 2-element Array containing the name and value of the environment variable
6117 * for +name+ if it exists:
6118 * ENV.replace('foo' => '0', 'bar' => '1')
6119 * ENV.assoc('foo') # => ['foo', '0']
6120 * Returns +nil+ if +name+ is a valid String and there is no such environment variable.
6122 * Returns +nil+ if +name+ is the empty String or is a String containing character <code>'='</code>.
6124 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6125 * ENV.assoc("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6126 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6127 * ENV.assoc("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6128 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6129 * Raises an exception if +name+ is not a String:
6130 * ENV.assoc(Object.new) # TypeError (no implicit conversion of Object into String)
6133 env_assoc(VALUE env
, VALUE key
)
6135 const char *s
= env_name(key
);
6136 VALUE e
= getenv_with_lock(s
);
6139 return rb_assoc_new(key
, e
);
6148 * ENV.value?(value) -> true or false
6149 * ENV.has_value?(value) -> true or false
6151 * Returns +true+ if +value+ is the value for some environment variable name, +false+ otherwise:
6152 * ENV.replace('foo' => '0', 'bar' => '1')
6153 * ENV.value?('0') # => true
6154 * ENV.has_value?('0') # => true
6155 * ENV.value?('2') # => false
6156 * ENV.has_value?('2') # => false
6159 env_has_value(VALUE dmy
, VALUE obj
)
6161 obj
= rb_check_string_type(obj
);
6162 if (NIL_P(obj
)) return Qnil
;
6168 char **env
= GET_ENVIRON(environ
);
6170 char *s
= strchr(*env
, '=');
6172 long len
= strlen(s
);
6173 if (RSTRING_LEN(obj
) == len
&& strncmp(s
, RSTRING_PTR(obj
), len
) == 0) {
6180 FREE_ENVIRON(environ
);
6189 * ENV.rassoc(value) -> [name, value] or nil
6191 * Returns a 2-element Array containing the name and value of the
6192 * *first* *found* environment variable that has value +value+, if one
6194 * ENV.replace('foo' => '0', 'bar' => '0')
6195 * ENV.rassoc('0') # => ["bar", "0"]
6196 * The order in which environment variables are examined is OS-dependent.
6197 * See {About Ordering}[#class-ENV-label-About+Ordering].
6199 * Returns +nil+ if there is no such environment variable.
6202 env_rassoc(VALUE dmy
, VALUE obj
)
6204 obj
= rb_check_string_type(obj
);
6205 if (NIL_P(obj
)) return Qnil
;
6207 VALUE result
= Qnil
;
6211 char **env
= GET_ENVIRON(environ
);
6214 const char *p
= *env
;
6215 char *s
= strchr(p
, '=');
6217 long len
= strlen(s
);
6218 if (RSTRING_LEN(obj
) == len
&& strncmp(s
, RSTRING_PTR(obj
), len
) == 0) {
6219 result
= rb_assoc_new(rb_str_new(p
, s
-p
-1), obj
);
6225 FREE_ENVIRON(environ
);
6234 * ENV.key(value) -> name or nil
6236 * Returns the name of the first environment variable with +value+, if it exists:
6237 * ENV.replace('foo' => '0', 'bar' => '0')
6238 * ENV.key('0') # => "foo"
6239 * The order in which environment variables are examined is OS-dependent.
6240 * See {About Ordering}[#class-ENV-label-About+Ordering].
6242 * Returns +nil+ if there is no such value.
6244 * Raises an exception if +value+ is invalid:
6245 * ENV.key(Object.new) # raises TypeError (no implicit conversion of Object into String)
6246 * See {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values].
6249 env_key(VALUE dmy
, VALUE value
)
6251 SafeStringValue(value
);
6256 char **env
= GET_ENVIRON(environ
);
6258 char *s
= strchr(*env
, '=');
6260 long len
= strlen(s
);
6261 if (RSTRING_LEN(value
) == len
&& strncmp(s
, RSTRING_PTR(value
), len
) == 0) {
6262 str
= env_str_new(*env
, s
-*env
-1);
6268 FREE_ENVIRON(environ
);
6278 VALUE hash
= rb_hash_new();
6282 char **env
= GET_ENVIRON(environ
);
6284 char *s
= strchr(*env
, '=');
6286 rb_hash_aset(hash
, env_str_new(*env
, s
-*env
),
6291 FREE_ENVIRON(environ
);
6305 rb_env_to_hash(void)
6307 return env_to_hash();
6312 * ENV.to_hash -> hash of name/value pairs
6314 * Returns a Hash containing all name/value pairs from ENV:
6315 * ENV.replace('foo' => '0', 'bar' => '1')
6316 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6320 env_f_to_hash(VALUE _
)
6322 return env_to_hash();
6327 * ENV.to_h -> hash of name/value pairs
6328 * ENV.to_h {|name, value| block } -> hash of name/value pairs
6330 * With no block, returns a Hash containing all name/value pairs from ENV:
6331 * ENV.replace('foo' => '0', 'bar' => '1')
6332 * ENV.to_h # => {"bar"=>"1", "foo"=>"0"}
6333 * With a block, returns a Hash whose items are determined by the block.
6334 * Each name/value pair in ENV is yielded to the block.
6335 * The block must return a 2-element Array (name/value pair)
6336 * that is added to the return Hash as a key and value:
6337 * ENV.to_h { |name, value| [name.to_sym, value.to_i] } # => {:bar=>1, :foo=>0}
6338 * Raises an exception if the block does not return an Array:
6339 * ENV.to_h { |name, value| name } # Raises TypeError (wrong element type String (expected array))
6340 * Raises an exception if the block returns an Array of the wrong size:
6341 * ENV.to_h { |name, value| [name] } # Raises ArgumentError (element has wrong array length (expected 2, was 1))
6346 VALUE hash
= env_to_hash();
6347 if (rb_block_given_p()) {
6348 hash
= rb_hash_to_h_block(hash
);
6355 * ENV.except(*keys) -> a_hash
6357 * Returns a hash except the given keys from ENV and their values.
6359 * ENV #=> {"LANG"=>"en_US.UTF-8", "TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"}
6360 * ENV.except("TERM","HOME") #=> {"LANG"=>"en_US.UTF-8"}
6363 env_except(int argc
, VALUE
*argv
, VALUE _
)
6366 VALUE key
, hash
= env_to_hash();
6368 for (i
= 0; i
< argc
; i
++) {
6370 rb_hash_delete(hash
, key
);
6378 * ENV.reject { |name, value| block } -> hash of name/value pairs
6379 * ENV.reject -> an_enumerator
6381 * Yields each environment variable name and its value as a 2-element Array.
6382 * Returns a Hash whose items are determined by the block.
6383 * When the block returns a truthy value, the name/value pair is added to the return Hash;
6384 * otherwise the pair is ignored:
6385 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
6386 * ENV.reject { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6387 * Returns an Enumerator if no block given:
6389 * e.each { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6394 return rb_hash_delete_if(env_to_hash());
6397 NORETURN(static VALUE
env_freeze(VALUE self
));
6402 * Raises an exception:
6403 * ENV.freeze # Raises TypeError (cannot freeze ENV)
6406 env_freeze(VALUE self
)
6408 rb_raise(rb_eTypeError
, "cannot freeze ENV");
6409 UNREACHABLE_RETURN(self
);
6414 * ENV.shift -> [name, value] or nil
6416 * Removes the first environment variable from ENV and returns
6417 * a 2-element Array containing its name and value:
6418 * ENV.replace('foo' => '0', 'bar' => '1')
6419 * ENV.to_hash # => {'bar' => '1', 'foo' => '0'}
6420 * ENV.shift # => ['bar', '1']
6421 * ENV.to_hash # => {'foo' => '0'}
6422 * Exactly which environment variable is "first" is OS-dependent.
6423 * See {About Ordering}[#class-ENV-label-About+Ordering].
6425 * Returns +nil+ if the environment is empty.
6430 VALUE result
= Qnil
;
6435 char **env
= GET_ENVIRON(environ
);
6437 const char *p
= *env
;
6438 char *s
= strchr(p
, '=');
6440 key
= env_str_new(p
, s
-p
);
6441 VALUE val
= env_str_new2(getenv(RSTRING_PTR(key
)));
6442 result
= rb_assoc_new(key
, val
);
6445 FREE_ENVIRON(environ
);
6458 * ENV.invert -> hash of value/name pairs
6460 * Returns a Hash whose keys are the ENV values,
6461 * and whose values are the corresponding ENV names:
6462 * ENV.replace('foo' => '0', 'bar' => '1')
6463 * ENV.invert # => {"1"=>"bar", "0"=>"foo"}
6464 * For a duplicate ENV value, overwrites the hash entry:
6465 * ENV.replace('foo' => '0', 'bar' => '0')
6466 * ENV.invert # => {"0"=>"foo"}
6467 * Note that the order of the ENV processing is OS-dependent,
6468 * which means that the order of overwriting is also OS-dependent.
6469 * See {About Ordering}[#class-ENV-label-About+Ordering].
6474 return rb_hash_invert(env_to_hash());
6478 keylist_delete(VALUE keys
, VALUE key
)
6481 const char *keyptr
, *eptr
;
6482 RSTRING_GETMEM(key
, keyptr
, keylen
);
6483 /* Don't stop at first key, as it is possible to have
6484 multiple environment values with the same key.
6486 for (long i
=0; i
<RARRAY_LEN(keys
); i
++) {
6487 VALUE e
= RARRAY_AREF(keys
, i
);
6488 RSTRING_GETMEM(e
, eptr
, elen
);
6489 if (elen
!= keylen
) continue;
6490 if (!ENVNMATCH(keyptr
, eptr
, elen
)) continue;
6491 rb_ary_delete_at(keys
, i
);
6497 env_replace_i(VALUE key
, VALUE val
, VALUE keys
)
6502 keylist_delete(keys
, key
);
6508 * ENV.replace(hash) -> ENV
6510 * Replaces the entire content of the environment variables
6511 * with the name/value pairs in the given +hash+;
6514 * Replaces the content of ENV with the given pairs:
6515 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
6516 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6518 * Raises an exception if a name or value is invalid
6519 * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]):
6520 * ENV.replace('foo' => '0', :bar => '1') # Raises TypeError (no implicit conversion of Symbol into String)
6521 * ENV.replace('foo' => '0', 'bar' => 1) # Raises TypeError (no implicit conversion of Integer into String)
6522 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6525 env_replace(VALUE env
, VALUE hash
)
6530 keys
= env_keys(TRUE
);
6531 if (env
== hash
) return env
;
6532 hash
= to_hash(hash
);
6533 rb_hash_foreach(hash
, env_replace_i
, keys
);
6535 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
6536 env_delete(RARRAY_AREF(keys
, i
));
6543 env_update_i(VALUE key
, VALUE val
, VALUE _
)
6550 env_update_block_i(VALUE key
, VALUE val
, VALUE _
)
6552 VALUE oldval
= rb_f_getenv(Qnil
, key
);
6553 if (!NIL_P(oldval
)) {
6554 val
= rb_yield_values(3, key
, oldval
, val
);
6562 * ENV.update(hash) -> ENV
6563 * ENV.update(hash) { |name, env_val, hash_val| block } -> ENV
6564 * ENV.merge!(hash) -> ENV
6565 * ENV.merge!(hash) { |name, env_val, hash_val| block } -> ENV
6567 * ENV.update is an alias for ENV.merge!.
6569 * Adds to ENV each key/value pair in the given +hash+; returns ENV:
6570 * ENV.replace('foo' => '0', 'bar' => '1')
6571 * ENV.merge!('baz' => '2', 'bat' => '3') # => {"bar"=>"1", "bat"=>"3", "baz"=>"2", "foo"=>"0"}
6572 * Deletes the ENV entry for a hash value that is +nil+:
6573 * ENV.merge!('baz' => nil, 'bat' => nil) # => {"bar"=>"1", "foo"=>"0"}
6574 * For an already-existing name, if no block given, overwrites the ENV value:
6575 * ENV.merge!('foo' => '4') # => {"bar"=>"1", "foo"=>"4"}
6576 * For an already-existing name, if block given,
6577 * yields the name, its ENV value, and its hash value;
6578 * the block's return value becomes the new name:
6579 * ENV.merge!('foo' => '5') { |name, env_val, hash_val | env_val + hash_val } # => {"bar"=>"1", "foo"=>"45"}
6580 * Raises an exception if a name or value is invalid
6581 * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]);
6582 * ENV.replace('foo' => '0', 'bar' => '1')
6583 * ENV.merge!('foo' => '6', :bar => '7', 'baz' => '9') # Raises TypeError (no implicit conversion of Symbol into String)
6584 * ENV # => {"bar"=>"1", "foo"=>"6"}
6585 * ENV.merge!('foo' => '7', 'bar' => 8, 'baz' => '9') # Raises TypeError (no implicit conversion of Integer into String)
6586 * ENV # => {"bar"=>"1", "foo"=>"7"}
6587 * Raises an exception if the block returns an invalid name:
6588 * (see {Invalid Names and Values}[#class-ENV-label-Invalid+Names+and+Values]):
6589 * ENV.merge!('bat' => '8', 'foo' => '9') { |name, env_val, hash_val | 10 } # Raises TypeError (no implicit conversion of Integer into String)
6590 * ENV # => {"bar"=>"1", "bat"=>"8", "foo"=>"7"}
6592 * Note that for the exceptions above,
6593 * hash pairs preceding an invalid name or value are processed normally;
6594 * those following are ignored.
6597 env_update(VALUE env
, VALUE hash
)
6599 if (env
== hash
) return env
;
6600 hash
= to_hash(hash
);
6601 rb_foreach_func
*func
= rb_block_given_p() ?
6602 env_update_block_i
: env_update_i
;
6603 rb_hash_foreach(hash
, func
, 0);
6609 * ENV.clone(freeze: nil) -> ENV
6611 * Returns ENV itself, and warns because ENV is a wrapper for the
6612 * process-wide environment variables and a clone is useless.
6613 * If +freeze+ keyword is given and not +nil+ or +false+, raises ArgumentError.
6614 * If +freeze+ keyword is given and +true+, raises TypeError, as ENV storage
6618 env_clone(int argc
, VALUE
*argv
, VALUE obj
)
6621 VALUE opt
, kwfreeze
;
6622 if (rb_scan_args(argc
, argv
, "0:", &opt
) < argc
) {
6623 kwfreeze
= rb_get_freeze_opt(1, &opt
);
6624 if (RTEST(kwfreeze
)) {
6625 rb_raise(rb_eTypeError
, "cannot freeze ENV");
6630 rb_warn_deprecated("ENV.clone", "ENV.to_h");
6634 NORETURN(static VALUE
env_dup(VALUE
));
6637 * ENV.dup # raises TypeError
6639 * Raises TypeError, because ENV is a singleton object.
6640 * Use #to_h to get a copy of ENV data as a hash.
6645 rb_raise(rb_eTypeError
, "Cannot dup ENV, use ENV.to_h to get a copy of ENV as a hash");
6648 static const rb_data_type_t env_data_type
= {
6656 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
| RUBY_TYPED_WB_PROTECTED
,
6660 * A \Hash maps each of its unique keys to a specific value.
6662 * A \Hash has certain similarities to an \Array, but:
6663 * - An \Array index is always an \Integer.
6664 * - A \Hash key can be (almost) any object.
6666 * === \Hash \Data Syntax
6668 * The older syntax for \Hash data uses the "hash rocket," <tt>=></tt>:
6670 * h = {:foo => 0, :bar => 1, :baz => 2}
6671 * h # => {:foo=>0, :bar=>1, :baz=>2}
6673 * Alternatively, but only for a \Hash key that's a \Symbol,
6674 * you can use a newer JSON-style syntax,
6675 * where each bareword becomes a \Symbol:
6677 * h = {foo: 0, bar: 1, baz: 2}
6678 * h # => {:foo=>0, :bar=>1, :baz=>2}
6680 * You can also use a \String in place of a bareword:
6682 * h = {'foo': 0, 'bar': 1, 'baz': 2}
6683 * h # => {:foo=>0, :bar=>1, :baz=>2}
6685 * And you can mix the styles:
6687 * h = {foo: 0, :bar => 1, 'baz': 2}
6688 * h # => {:foo=>0, :bar=>1, :baz=>2}
6690 * But it's an error to try the JSON-style syntax
6691 * for a key that's not a bareword or a String:
6693 * # Raises SyntaxError (syntax error, unexpected ':', expecting =>):
6696 * Hash value can be omitted, meaning that value will be fetched from the context
6697 * by the name of the key:
6702 * h # => {:x=>0, :y=>100}
6706 * You can use a \Hash to give names to objects:
6708 * person = {name: 'Matz', language: 'Ruby'}
6709 * person # => {:name=>"Matz", :language=>"Ruby"}
6711 * You can use a \Hash to give names to method arguments:
6713 * def some_method(hash)
6716 * some_method({foo: 0, bar: 1, baz: 2}) # => {:foo=>0, :bar=>1, :baz=>2}
6718 * Note: when the last argument in a method call is a \Hash,
6719 * the curly braces may be omitted:
6721 * some_method(foo: 0, bar: 1, baz: 2) # => {:foo=>0, :bar=>1, :baz=>2}
6723 * You can use a \Hash to initialize an object:
6726 * attr_accessor :name, :language
6727 * def initialize(hash)
6728 * self.name = hash[:name]
6729 * self.language = hash[:language]
6732 * matz = Dev.new(name: 'Matz', language: 'Ruby')
6733 * matz # => #<Dev: @name="Matz", @language="Ruby">
6735 * === Creating a \Hash
6737 * You can create a \Hash object explicitly with:
6739 * - A {hash literal}[doc/syntax/literals_rdoc.html#label-Hash+Literals].
6741 * You can convert certain objects to Hashes with:
6743 * - \Method {Hash}[Kernel.html#method-i-Hash].
6745 * You can create a \Hash by calling method Hash.new.
6747 * Create an empty Hash:
6753 * You can create a \Hash by calling method Hash.[].
6755 * Create an empty Hash:
6760 * Create a \Hash with initial entries:
6762 * h = Hash[foo: 0, bar: 1, baz: 2]
6763 * h # => {:foo=>0, :bar=>1, :baz=>2}
6765 * You can create a \Hash by using its literal form (curly braces).
6767 * Create an empty \Hash:
6772 * Create a \Hash with initial entries:
6774 * h = {foo: 0, bar: 1, baz: 2}
6775 * h # => {:foo=>0, :bar=>1, :baz=>2}
6778 * === \Hash Value Basics
6780 * The simplest way to retrieve a \Hash value (instance method #[]):
6782 * h = {foo: 0, bar: 1, baz: 2}
6785 * The simplest way to create or update a \Hash value (instance method #[]=):
6787 * h = {foo: 0, bar: 1, baz: 2}
6788 * h[:bat] = 3 # => 3
6789 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
6790 * h[:foo] = 4 # => 4
6791 * h # => {:foo=>4, :bar=>1, :baz=>2, :bat=>3}
6793 * The simplest way to delete a \Hash entry (instance method #delete):
6795 * h = {foo: 0, bar: 1, baz: 2}
6796 * h.delete(:bar) # => 1
6797 * h # => {:foo=>0, :baz=>2}
6801 * A \Hash object presents its entries in the order of their creation. This is seen in:
6803 * - Iterative methods such as <tt>each</tt>, <tt>each_key</tt>, <tt>each_pair</tt>, <tt>each_value</tt>.
6804 * - Other order-sensitive methods such as <tt>shift</tt>, <tt>keys</tt>, <tt>values</tt>.
6805 * - The \String returned by method <tt>inspect</tt>.
6807 * A new \Hash has its initial ordering per the given entries:
6809 * h = Hash[foo: 0, bar: 1]
6810 * h # => {:foo=>0, :bar=>1}
6812 * New entries are added at the end:
6815 * h # => {:foo=>0, :bar=>1, :baz=>2}
6817 * Updating a value does not affect the order:
6820 * h # => {:foo=>0, :bar=>1, :baz=>3}
6822 * But re-creating a deleted entry can affect the order:
6826 * h # => {:bar=>1, :baz=>3, :foo=>5}
6830 * ==== \Hash Key Equivalence
6832 * Two objects are treated as the same \hash key when their <code>hash</code> value
6833 * is identical and the two objects are <code>eql?</code> to each other.
6835 * ==== Modifying an Active \Hash Key
6837 * Modifying a \Hash key while it is in use damages the hash's index.
6839 * This \Hash has keys that are Arrays:
6841 * a0 = [ :foo, :bar ]
6842 * a1 = [ :baz, :bat ]
6843 * h = {a0 => 0, a1 => 1}
6844 * h.include?(a0) # => true
6846 * a0.hash # => 110002110
6848 * Modifying array element <tt>a0[0]</tt> changes its hash value:
6851 * a0.hash # => 1069447059
6853 * And damages the \Hash index:
6855 * h.include?(a0) # => false
6858 * You can repair the hash index using method +rehash+:
6860 * h.rehash # => {[:bam, :bar]=>0, [:baz, :bat]=>1}
6861 * h.include?(a0) # => true
6864 * A \String key is always safe.
6865 * That's because an unfrozen \String
6866 * passed as a key will be replaced by a duplicated and frozen \String:
6869 * s.frozen? # => false
6871 * first_key = h.keys.first
6872 * first_key.frozen? # => true
6874 * ==== User-Defined \Hash Keys
6876 * To be useable as a \Hash key, objects must implement the methods <code>hash</code> and <code>eql?</code>.
6877 * Note: this requirement does not apply if the \Hash uses #compare_by_identity since comparison will then
6878 * rely on the keys' object id instead of <code>hash</code> and <code>eql?</code>.
6880 * \Object defines basic implementation for <code>hash</code> and <code>eq?</code> that makes each object
6881 * a distinct key. Typically, user-defined classes will want to override these methods to provide meaningful
6882 * behavior, or for example inherit \Struct that has useful definitions for these.
6884 * A typical implementation of <code>hash</code> is based on the
6885 * object's data while <code>eql?</code> is usually aliased to the overridden
6886 * <code>==</code> method:
6889 * attr_reader :author, :title
6891 * def initialize(author, title)
6897 * self.class === other &&
6898 * other.author == @author &&
6899 * other.title == @title
6905 * @author.hash ^ @title.hash # XOR
6909 * book1 = Book.new 'matz', 'Ruby in a Nutshell'
6910 * book2 = Book.new 'matz', 'Ruby in a Nutshell'
6914 * reviews[book1] = 'Great reference!'
6915 * reviews[book2] = 'Nice and compact!'
6917 * reviews.length #=> 1
6919 * === Default Values
6921 * The methods #[], #values_at and #dig need to return the value associated to a certain key.
6922 * When that key is not found, that value will be determined by its default proc (if any)
6923 * or else its default (initially `nil`).
6925 * You can retrieve the default value with method #default:
6928 * h.default # => nil
6930 * You can set the default value by passing an argument to method Hash.new or
6931 * with method #default=
6938 * This default value is returned for #[], #values_at and #dig when a key is
6941 * counts = {foo: 42}
6942 * counts.default # => nil (default)
6944 * counts[:bar] # => nil
6945 * counts.default = 0
6946 * counts[:bar] # => 0
6947 * counts.values_at(:foo, :bar, :baz) # => [42, 0, 0]
6948 * counts.dig(:bar) # => 0
6950 * Note that the default value is used without being duplicated. It is not advised to set
6951 * the default value to a mutable object:
6953 * synonyms = Hash.new([])
6954 * synonyms[:hello] # => []
6955 * synonyms[:hello] << :hi # => [:hi], but this mutates the default!
6956 * synonyms.default # => [:hi]
6957 * synonyms[:world] << :universe
6958 * synonyms[:world] # => [:hi, :universe], oops
6959 * synonyms.keys # => [], oops
6961 * To use a mutable object as default, it is recommended to use a default proc
6963 * ==== Default \Proc
6965 * When the default proc for a \Hash is set (i.e., not +nil+),
6966 * the default value returned by method #[] is determined by the default proc alone.
6968 * You can retrieve the default proc with method #default_proc:
6971 * h.default_proc # => nil
6973 * You can set the default proc by calling Hash.new with a block or
6974 * calling the method #default_proc=
6976 * h = Hash.new { |hash, key| "Default value for #{key}" }
6977 * h.default_proc.class # => Proc
6978 * h.default_proc = proc { |hash, key| "Default value for #{key.inspect}" }
6979 * h.default_proc.class # => Proc
6981 * When the default proc is set (i.e., not +nil+)
6982 * and method #[] is called with with a non-existent key,
6983 * #[] calls the default proc with both the \Hash object itself and the missing key,
6984 * then returns the proc's return value:
6986 * h = Hash.new { |hash, key| "Default value for #{key}" }
6987 * h[:nosuch] # => "Default value for nosuch"
6989 * Note that in the example above no entry for key +:nosuch+ is created:
6991 * h.include?(:nosuch) # => false
6993 * However, the proc itself can add a new entry:
6995 * synonyms = Hash.new { |hash, key| hash[key] = [] }
6996 * synonyms.include?(:hello) # => false
6997 * synonyms[:hello] << :hi # => [:hi]
6998 * synonyms[:world] << :universe # => [:universe]
6999 * synonyms.keys # => [:hello, :world]
7001 * Note that setting the default proc will clear the default value and vice versa.
7005 * First, what's elsewhere. \Class \Hash:
7007 * - Inherits from {class Object}[Object.html#class-Object-label-What-27s+Here].
7008 * - Includes {module Enumerable}[Enumerable.html#module-Enumerable-label-What-27s+Here],
7009 * which provides dozens of additional methods.
7011 * Here, class \Hash provides methods that are useful for:
7013 * - {Creating a Hash}[#class-Hash-label-Methods+for+Creating+a+Hash]
7014 * - {Setting Hash State}[#class-Hash-label-Methods+for+Setting+Hash+State]
7015 * - {Querying}[#class-Hash-label-Methods+for+Querying]
7016 * - {Comparing}[#class-Hash-label-Methods+for+Comparing]
7017 * - {Fetching}[#class-Hash-label-Methods+for+Fetching]
7018 * - {Assigning}[#class-Hash-label-Methods+for+Assigning]
7019 * - {Deleting}[#class-Hash-label-Methods+for+Deleting]
7020 * - {Iterating}[#class-Hash-label-Methods+for+Iterating]
7021 * - {Converting}[#class-Hash-label-Methods+for+Converting]
7022 * - {Transforming Keys and Values}[#class-Hash-label-Methods+for+Transforming+Keys+and+Values]
7023 * - {And more....}[#class-Hash-label-Other+Methods]
7025 * \Class \Hash also includes methods from module Enumerable.
7027 * ==== Methods for Creating a \Hash
7029 * ::[]:: Returns a new hash populated with given objects.
7030 * ::new:: Returns a new empty hash.
7031 * ::try_convert:: Returns a new hash created from a given object.
7033 * ==== Methods for Setting \Hash State
7035 * #compare_by_identity:: Sets +self+ to consider only identity in comparing keys.
7036 * #default=:: Sets the default to a given value.
7037 * #default_proc=:: Sets the default proc to a given proc.
7038 * #rehash:: Rebuilds the hash table by recomputing the hash index for each key.
7040 * ==== Methods for Querying
7042 * #any?:: Returns whether any element satisfies a given criterion.
7043 * #compare_by_identity?:: Returns whether the hash considers only identity when comparing keys.
7044 * #default:: Returns the default value, or the default value for a given key.
7045 * #default_proc:: Returns the default proc.
7046 * #empty?:: Returns whether there are no entries.
7047 * #eql?:: Returns whether a given object is equal to +self+.
7048 * #hash:: Returns the integer hash code.
7049 * #has_value?:: Returns whether a given object is a value in +self+.
7050 * #include?, #has_key?, #member?, #key?:: Returns whether a given object is a key in +self+.
7051 * #length, #size:: Returns the count of entries.
7052 * #value?:: Returns whether a given object is a value in +self+.
7054 * ==== Methods for Comparing
7056 * {#<}[#method-i-3C]:: Returns whether +self+ is a proper subset of a given object.
7057 * {#<=}[#method-i-3C-3D]:: Returns whether +self+ is a subset of a given object.
7058 * {#==}[#method-i-3D-3D]:: Returns whether a given object is equal to +self+.
7059 * {#>}[#method-i-3E]:: Returns whether +self+ is a proper superset of a given object
7060 * {#>=}[#method-i-3E-3D]:: Returns whether +self+ is a proper superset of a given object.
7062 * ==== Methods for Fetching
7064 * #[]:: Returns the value associated with a given key.
7065 * #assoc:: Returns a 2-element array containing a given key and its value.
7066 * #dig:: Returns the object in nested objects that is specified
7067 * by a given key and additional arguments.
7068 * #fetch:: Returns the value for a given key.
7069 * #fetch_values:: Returns array containing the values associated with given keys.
7070 * #key:: Returns the key for the first-found entry with a given value.
7071 * #keys:: Returns an array containing all keys in +self+.
7072 * #rassoc:: Returns a 2-element array consisting of the key and value
7073 of the first-found entry having a given value.
7074 * #values:: Returns an array containing all values in +self+/
7075 * #values_at:: Returns an array containing values for given keys.
7077 * ==== Methods for Assigning
7079 * #[]=, #store:: Associates a given key with a given value.
7080 * #merge:: Returns the hash formed by merging each given hash into a copy of +self+.
7081 * #merge!, #update:: Merges each given hash into +self+.
7082 * #replace:: Replaces the entire contents of +self+ with the contents of a givan hash.
7084 * ==== Methods for Deleting
7086 * These methods remove entries from +self+:
7088 * #clear:: Removes all entries from +self+.
7089 * #compact!:: Removes all +nil+-valued entries from +self+.
7090 * #delete:: Removes the entry for a given key.
7091 * #delete_if:: Removes entries selected by a given block.
7092 * #filter!, #select!:: Keep only those entries selected by a given block.
7093 * #keep_if:: Keep only those entries selected by a given block.
7094 * #reject!:: Removes entries selected by a given block.
7095 * #shift:: Removes and returns the first entry.
7097 * These methods return a copy of +self+ with some entries removed:
7099 * #compact:: Returns a copy of +self+ with all +nil+-valued entries removed.
7100 * #except:: Returns a copy of +self+ with entries removed for specified keys.
7101 * #filter, #select:: Returns a copy of +self+ with only those entries selected by a given block.
7102 * #reject:: Returns a copy of +self+ with entries removed as specified by a given block.
7103 * #slice:: Returns a hash containing the entries for given keys.
7105 * ==== Methods for Iterating
7106 * #each, #each_pair:: Calls a given block with each key-value pair.
7107 * #each_key:: Calls a given block with each key.
7108 * #each_value:: Calls a given block with each value.
7110 * ==== Methods for Converting
7112 * #inspect, #to_s:: Returns a new String containing the hash entries.
7113 * #to_a:: Returns a new array of 2-element arrays;
7114 * each nested array contains a key-value pair from +self+.
7115 * #to_h:: Returns +self+ if a \Hash;
7116 * if a subclass of \Hash, returns a \Hash containing the entries from +self+.
7117 * #to_hash:: Returns +self+.
7118 * #to_proc:: Returns a proc that maps a given key to its value.
7120 * ==== Methods for Transforming Keys and Values
7122 * #transform_keys:: Returns a copy of +self+ with modified keys.
7123 * #transform_keys!:: Modifies keys in +self+
7124 * #transform_values:: Returns a copy of +self+ with modified values.
7125 * #transform_values!:: Modifies values in +self+.
7127 * ==== Other Methods
7128 * #flatten:: Returns an array that is a 1-dimensional flattening of +self+.
7129 * #invert:: Returns a hash with the each key-value pair inverted.
7136 id_hash
= rb_intern_const("hash");
7137 id_default
= rb_intern_const("default");
7138 id_flatten_bang
= rb_intern_const("flatten!");
7139 id_hash_iter_lev
= rb_make_internal_id();
7141 rb_cHash
= rb_define_class("Hash", rb_cObject
);
7143 rb_include_module(rb_cHash
, rb_mEnumerable
);
7145 rb_define_alloc_func(rb_cHash
, empty_hash_alloc
);
7146 rb_define_singleton_method(rb_cHash
, "[]", rb_hash_s_create
, -1);
7147 rb_define_singleton_method(rb_cHash
, "try_convert", rb_hash_s_try_convert
, 1);
7148 rb_define_method(rb_cHash
, "initialize", rb_hash_initialize
, -1);
7149 rb_define_method(rb_cHash
, "initialize_copy", rb_hash_replace
, 1);
7150 rb_define_method(rb_cHash
, "rehash", rb_hash_rehash
, 0);
7152 rb_define_method(rb_cHash
, "to_hash", rb_hash_to_hash
, 0);
7153 rb_define_method(rb_cHash
, "to_h", rb_hash_to_h
, 0);
7154 rb_define_method(rb_cHash
, "to_a", rb_hash_to_a
, 0);
7155 rb_define_method(rb_cHash
, "inspect", rb_hash_inspect
, 0);
7156 rb_define_alias(rb_cHash
, "to_s", "inspect");
7157 rb_define_method(rb_cHash
, "to_proc", rb_hash_to_proc
, 0);
7159 rb_define_method(rb_cHash
, "==", rb_hash_equal
, 1);
7160 rb_define_method(rb_cHash
, "[]", rb_hash_aref
, 1);
7161 rb_define_method(rb_cHash
, "hash", rb_hash_hash
, 0);
7162 rb_define_method(rb_cHash
, "eql?", rb_hash_eql
, 1);
7163 rb_define_method(rb_cHash
, "fetch", rb_hash_fetch_m
, -1);
7164 rb_define_method(rb_cHash
, "[]=", rb_hash_aset
, 2);
7165 rb_define_method(rb_cHash
, "store", rb_hash_aset
, 2);
7166 rb_define_method(rb_cHash
, "default", rb_hash_default
, -1);
7167 rb_define_method(rb_cHash
, "default=", rb_hash_set_default
, 1);
7168 rb_define_method(rb_cHash
, "default_proc", rb_hash_default_proc
, 0);
7169 rb_define_method(rb_cHash
, "default_proc=", rb_hash_set_default_proc
, 1);
7170 rb_define_method(rb_cHash
, "key", rb_hash_key
, 1);
7171 rb_define_method(rb_cHash
, "size", rb_hash_size
, 0);
7172 rb_define_method(rb_cHash
, "length", rb_hash_size
, 0);
7173 rb_define_method(rb_cHash
, "empty?", rb_hash_empty_p
, 0);
7175 rb_define_method(rb_cHash
, "each_value", rb_hash_each_value
, 0);
7176 rb_define_method(rb_cHash
, "each_key", rb_hash_each_key
, 0);
7177 rb_define_method(rb_cHash
, "each_pair", rb_hash_each_pair
, 0);
7178 rb_define_method(rb_cHash
, "each", rb_hash_each_pair
, 0);
7180 rb_define_method(rb_cHash
, "transform_keys", rb_hash_transform_keys
, -1);
7181 rb_define_method(rb_cHash
, "transform_keys!", rb_hash_transform_keys_bang
, -1);
7182 rb_define_method(rb_cHash
, "transform_values", rb_hash_transform_values
, 0);
7183 rb_define_method(rb_cHash
, "transform_values!", rb_hash_transform_values_bang
, 0);
7185 rb_define_method(rb_cHash
, "keys", rb_hash_keys
, 0);
7186 rb_define_method(rb_cHash
, "values", rb_hash_values
, 0);
7187 rb_define_method(rb_cHash
, "values_at", rb_hash_values_at
, -1);
7188 rb_define_method(rb_cHash
, "fetch_values", rb_hash_fetch_values
, -1);
7190 rb_define_method(rb_cHash
, "shift", rb_hash_shift
, 0);
7191 rb_define_method(rb_cHash
, "delete", rb_hash_delete_m
, 1);
7192 rb_define_method(rb_cHash
, "delete_if", rb_hash_delete_if
, 0);
7193 rb_define_method(rb_cHash
, "keep_if", rb_hash_keep_if
, 0);
7194 rb_define_method(rb_cHash
, "select", rb_hash_select
, 0);
7195 rb_define_method(rb_cHash
, "select!", rb_hash_select_bang
, 0);
7196 rb_define_method(rb_cHash
, "filter", rb_hash_select
, 0);
7197 rb_define_method(rb_cHash
, "filter!", rb_hash_select_bang
, 0);
7198 rb_define_method(rb_cHash
, "reject", rb_hash_reject
, 0);
7199 rb_define_method(rb_cHash
, "reject!", rb_hash_reject_bang
, 0);
7200 rb_define_method(rb_cHash
, "slice", rb_hash_slice
, -1);
7201 rb_define_method(rb_cHash
, "except", rb_hash_except
, -1);
7202 rb_define_method(rb_cHash
, "clear", rb_hash_clear
, 0);
7203 rb_define_method(rb_cHash
, "invert", rb_hash_invert
, 0);
7204 rb_define_method(rb_cHash
, "update", rb_hash_update
, -1);
7205 rb_define_method(rb_cHash
, "replace", rb_hash_replace
, 1);
7206 rb_define_method(rb_cHash
, "merge!", rb_hash_update
, -1);
7207 rb_define_method(rb_cHash
, "merge", rb_hash_merge
, -1);
7208 rb_define_method(rb_cHash
, "assoc", rb_hash_assoc
, 1);
7209 rb_define_method(rb_cHash
, "rassoc", rb_hash_rassoc
, 1);
7210 rb_define_method(rb_cHash
, "flatten", rb_hash_flatten
, -1);
7211 rb_define_method(rb_cHash
, "compact", rb_hash_compact
, 0);
7212 rb_define_method(rb_cHash
, "compact!", rb_hash_compact_bang
, 0);
7214 rb_define_method(rb_cHash
, "include?", rb_hash_has_key
, 1);
7215 rb_define_method(rb_cHash
, "member?", rb_hash_has_key
, 1);
7216 rb_define_method(rb_cHash
, "has_key?", rb_hash_has_key
, 1);
7217 rb_define_method(rb_cHash
, "has_value?", rb_hash_has_value
, 1);
7218 rb_define_method(rb_cHash
, "key?", rb_hash_has_key
, 1);
7219 rb_define_method(rb_cHash
, "value?", rb_hash_has_value
, 1);
7221 rb_define_method(rb_cHash
, "compare_by_identity", rb_hash_compare_by_id
, 0);
7222 rb_define_method(rb_cHash
, "compare_by_identity?", rb_hash_compare_by_id_p
, 0);
7224 rb_define_method(rb_cHash
, "any?", rb_hash_any_p
, -1);
7225 rb_define_method(rb_cHash
, "dig", rb_hash_dig
, -1);
7227 rb_define_method(rb_cHash
, "<=", rb_hash_le
, 1);
7228 rb_define_method(rb_cHash
, "<", rb_hash_lt
, 1);
7229 rb_define_method(rb_cHash
, ">=", rb_hash_ge
, 1);
7230 rb_define_method(rb_cHash
, ">", rb_hash_gt
, 1);
7232 rb_define_method(rb_cHash
, "deconstruct_keys", rb_hash_deconstruct_keys
, 1);
7234 rb_define_singleton_method(rb_cHash
, "ruby2_keywords_hash?", rb_hash_s_ruby2_keywords_hash_p
, 1);
7235 rb_define_singleton_method(rb_cHash
, "ruby2_keywords_hash", rb_hash_s_ruby2_keywords_hash
, 1);
7237 /* Document-class: ENV
7239 * ENV is a hash-like accessor for environment variables.
7241 * === Interaction with the Operating System
7243 * The ENV object interacts with the operating system's environment variables:
7245 * - When you get the value for a name in ENV, the value is retrieved from among the current environment variables.
7246 * - When you create or set a name-value pair in ENV, the name and value are immediately set in the environment variables.
7247 * - When you delete a name-value pair in ENV, it is immediately deleted from the environment variables.
7249 * === Names and Values
7251 * Generally, a name or value is a String.
7253 * ==== Valid Names and Values
7255 * Each name or value must be one of the following:
7258 * - An object that responds to \#to_str by returning a String, in which case that String will be used as the name or value.
7260 * ==== Invalid Names and Values
7264 * - May not be the empty string:
7266 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv())
7268 * - May not contain character <code>"="</code>:
7270 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv(=))
7272 * A new name or value:
7274 * - May not be a non-String that does not respond to \#to_str:
7276 * ENV['foo'] = Object.new
7277 * # Raises TypeError (no implicit conversion of Object into String)
7278 * ENV[Object.new] = '0'
7279 * # Raises TypeError (no implicit conversion of Object into String)
7281 * - May not contain the NUL character <code>"\0"</code>:
7284 * # Raises ArgumentError (bad environment variable value: contains null byte)
7286 * # Raises ArgumentError (bad environment variable name: contains null byte)
7288 * - May not have an ASCII-incompatible encoding such as UTF-16LE or ISO-2022-JP:
7290 * ENV['foo'] = '0'.force_encoding(Encoding::ISO_2022_JP)
7291 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7292 * ENV["foo".force_encoding(Encoding::ISO_2022_JP)] = '0'
7293 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7295 * === About Ordering
7297 * ENV enumerates its name/value pairs in the order found
7298 * in the operating system's environment variables.
7299 * Therefore the ordering of ENV content is OS-dependent, and may be indeterminate.
7301 * This will be seen in:
7302 * - A Hash returned by an ENV method.
7303 * - An Enumerator returned by an ENV method.
7304 * - An Array returned by ENV.keys, ENV.values, or ENV.to_a.
7305 * - The String returned by ENV.inspect.
7306 * - The Array returned by ENV.shift.
7307 * - The name returned by ENV.key.
7309 * === About the Examples
7310 * Some methods in ENV return ENV itself. Typically, there are many environment variables.
7311 * It's not useful to display a large ENV in the examples here,
7312 * so most example snippets begin by resetting the contents of ENV:
7313 * - ENV.replace replaces ENV with a new collection of entries.
7314 * - ENV.clear empties ENV.
7318 * First, what's elsewhere. \Class \ENV:
7320 * - Inherits from {class Object}[Object.html#class-Object-label-What-27s+Here].
7321 * - Extends {module Enumerable}[Enumerable.html#module-Enumerable-label-What-27s+Here],
7323 * Here, class \ENV provides methods that are useful for:
7325 * - {Querying}[#class-ENV-label-Methods+for+Querying]
7326 * - {Assigning}[#class-ENV-label-Methods+for+Assigning]
7327 * - {Deleting}[#class-ENV-label-Methods+for+Deleting]
7328 * - {Iterating}[#class-ENV-label-Methods+for+Iterating]
7329 * - {Converting}[#class-ENV-label-Methods+for+Converting]
7330 * - {And more ....}[#class-ENV-label-More+Methods]
7332 * === Methods for Querying
7334 * - ::[]:: Returns the value for the given environment variable name if it exists:
7335 * - ::empty?:: Returns whether \ENV is empty.
7336 * - ::has_value?, ::value?:: Returns whether the given value is in \ENV.
7337 * - ::include?, ::has_key?, ::key?, ::member?:: Returns whether the given name
7339 * - ::key:: Returns the name of the first entry with the given value.
7340 * - ::size, ::length:: Returns the number of entries.
7341 * - ::value?:: Returns whether any entry has the given value.
7343 * === Methods for Assigning
7345 * - ::[]=, ::store:: Creates, updates, or deletes the named environment variable.
7346 * - ::clear:: Removes every environment variable; returns \ENV:
7347 * - ::update, ::merge!:: Adds to \ENV each key/value pair in the given hash.
7348 * - ::replace:: Replaces the entire content of the \ENV
7349 * with the name/value pairs in the given hash.
7351 * === Methods for Deleting
7353 * - ::delete:: Deletes the named environment variable name if it exists.
7354 * - ::delete_if:: Deletes entries selected by the block.
7355 * - ::keep_if:: Deletes entries not selected by the block.
7356 * - ::reject!:: Similar to #delete_if, but returns +nil+ if no change was made.
7357 * - ::select!, ::filter!:: Deletes entries selected by the block.
7358 * - ::shift:: Removes and returns the first entry.
7360 * === Methods for Iterating
7362 * - ::each, ::each_pair:: Calls the block with each name/value pair.
7363 * - ::each_key:: Calls the block with each name.
7364 * - ::each_value:: Calls the block with each value.
7366 * === Methods for Converting
7368 * - ::assoc:: Returns a 2-element array containing the name and value
7369 * of the named environment variable if it exists:
7370 * - ::clone:: Returns \ENV (and issues a warning).
7371 * - ::except:: Returns a hash of all name/value pairs except those given.
7372 * - ::fetch:: Returns the value for the given name.
7373 * - ::inspect:: Returns the contents of \ENV as a string.
7374 * - ::invert:: Returns a hash whose keys are the ENV values,
7375 and whose values are the corresponding ENV names.
7376 * - ::keys:: Returns an array of all names.
7377 * - ::rassoc:: Returns the name and value of the first found entry
7378 * that has the given value.
7379 * - ::reject:: Returns a hash of those entries not rejected by the block.
7380 * - ::select, ::filter:: Returns a hash of name/value pairs selected by the block.
7381 * - ::slice:: Returns a hash of the given names and their corresponding values.
7382 * - ::to_a:: Returns the entries as an array of 2-element Arrays.
7383 * - ::to_h:: Returns a hash of entries selected by the block.
7384 * - ::to_hash:: Returns a hash of all entries.
7385 * - ::to_s:: Returns the string <tt>'ENV'</tt>.
7386 * - ::values:: Returns all values as an array.
7387 * - ::values_at:: Returns an array of the values for the given name.
7391 * - ::dup:: Raises an exception.
7392 * - ::freeze:: Raises an exception.
7393 * - ::rehash:: Returns +nil+, without modifying \ENV.
7398 * Hack to get RDoc to regard ENV as a class:
7399 * envtbl = rb_define_class("ENV", rb_cObject);
7401 origenviron
= environ
;
7402 envtbl
= TypedData_Wrap_Struct(rb_cObject
, &env_data_type
, NULL
);
7403 rb_extend_object(envtbl
, rb_mEnumerable
);
7404 FL_SET_RAW(envtbl
, RUBY_FL_SHAREABLE
);
7407 rb_define_singleton_method(envtbl
, "[]", rb_f_getenv
, 1);
7408 rb_define_singleton_method(envtbl
, "fetch", env_fetch
, -1);
7409 rb_define_singleton_method(envtbl
, "[]=", env_aset_m
, 2);
7410 rb_define_singleton_method(envtbl
, "store", env_aset_m
, 2);
7411 rb_define_singleton_method(envtbl
, "each", env_each_pair
, 0);
7412 rb_define_singleton_method(envtbl
, "each_pair", env_each_pair
, 0);
7413 rb_define_singleton_method(envtbl
, "each_key", env_each_key
, 0);
7414 rb_define_singleton_method(envtbl
, "each_value", env_each_value
, 0);
7415 rb_define_singleton_method(envtbl
, "delete", env_delete_m
, 1);
7416 rb_define_singleton_method(envtbl
, "delete_if", env_delete_if
, 0);
7417 rb_define_singleton_method(envtbl
, "keep_if", env_keep_if
, 0);
7418 rb_define_singleton_method(envtbl
, "slice", env_slice
, -1);
7419 rb_define_singleton_method(envtbl
, "except", env_except
, -1);
7420 rb_define_singleton_method(envtbl
, "clear", env_clear
, 0);
7421 rb_define_singleton_method(envtbl
, "reject", env_reject
, 0);
7422 rb_define_singleton_method(envtbl
, "reject!", env_reject_bang
, 0);
7423 rb_define_singleton_method(envtbl
, "select", env_select
, 0);
7424 rb_define_singleton_method(envtbl
, "select!", env_select_bang
, 0);
7425 rb_define_singleton_method(envtbl
, "filter", env_select
, 0);
7426 rb_define_singleton_method(envtbl
, "filter!", env_select_bang
, 0);
7427 rb_define_singleton_method(envtbl
, "shift", env_shift
, 0);
7428 rb_define_singleton_method(envtbl
, "freeze", env_freeze
, 0);
7429 rb_define_singleton_method(envtbl
, "invert", env_invert
, 0);
7430 rb_define_singleton_method(envtbl
, "replace", env_replace
, 1);
7431 rb_define_singleton_method(envtbl
, "update", env_update
, 1);
7432 rb_define_singleton_method(envtbl
, "merge!", env_update
, 1);
7433 rb_define_singleton_method(envtbl
, "inspect", env_inspect
, 0);
7434 rb_define_singleton_method(envtbl
, "rehash", env_none
, 0);
7435 rb_define_singleton_method(envtbl
, "to_a", env_to_a
, 0);
7436 rb_define_singleton_method(envtbl
, "to_s", env_to_s
, 0);
7437 rb_define_singleton_method(envtbl
, "key", env_key
, 1);
7438 rb_define_singleton_method(envtbl
, "size", env_size
, 0);
7439 rb_define_singleton_method(envtbl
, "length", env_size
, 0);
7440 rb_define_singleton_method(envtbl
, "empty?", env_empty_p
, 0);
7441 rb_define_singleton_method(envtbl
, "keys", env_f_keys
, 0);
7442 rb_define_singleton_method(envtbl
, "values", env_f_values
, 0);
7443 rb_define_singleton_method(envtbl
, "values_at", env_values_at
, -1);
7444 rb_define_singleton_method(envtbl
, "include?", env_has_key
, 1);
7445 rb_define_singleton_method(envtbl
, "member?", env_has_key
, 1);
7446 rb_define_singleton_method(envtbl
, "has_key?", env_has_key
, 1);
7447 rb_define_singleton_method(envtbl
, "has_value?", env_has_value
, 1);
7448 rb_define_singleton_method(envtbl
, "key?", env_has_key
, 1);
7449 rb_define_singleton_method(envtbl
, "value?", env_has_value
, 1);
7450 rb_define_singleton_method(envtbl
, "to_hash", env_f_to_hash
, 0);
7451 rb_define_singleton_method(envtbl
, "to_h", env_to_h
, 0);
7452 rb_define_singleton_method(envtbl
, "assoc", env_assoc
, 1);
7453 rb_define_singleton_method(envtbl
, "rassoc", env_rassoc
, 1);
7454 rb_define_singleton_method(envtbl
, "clone", env_clone
, -1);
7455 rb_define_singleton_method(envtbl
, "dup", env_dup
, 0);
7457 VALUE envtbl_class
= rb_singleton_class(envtbl
);
7458 rb_undef_method(envtbl_class
, "initialize");
7459 rb_undef_method(envtbl_class
, "initialize_clone");
7460 rb_undef_method(envtbl_class
, "initialize_copy");
7461 rb_undef_method(envtbl_class
, "initialize_dup");
7464 * ENV is a Hash-like accessor for environment variables.
7466 * See ENV (the class) for more details.
7468 rb_define_global_const("ENV", envtbl
);
7471 ruby_register_rollback_func_for_ensure(hash_foreach_ensure
, hash_foreach_ensure_rollback
);
7473 HASH_ASSERT(sizeof(ar_hint_t
) * RHASH_AR_TABLE_MAX_SIZE
== sizeof(VALUE
));