Ruby: hash.c Source File

Ruby 3.4.8p72 (2025-12-17 revision 995b59f66677d44767ce9faac6957e5543617ff9)

hash.c
1/**********************************************************************
2
3 hash.c -
4
5 $Author$
6 created at: Mon Nov 22 18:51:18 JST 1993
7
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
11
12**********************************************************************/
13
14#include "ruby/internal/config.h"
15
16#include <errno.h>
17
18#ifdef __APPLE__
19# ifdef HAVE_CRT_EXTERNS_H
20# include <crt_externs.h>
21# else
22# include "missing/crt_externs.h"
23# endif
24#endif
25
26#include "debug_counter.h"
27#include "id.h"
28#include "internal.h"
29#include "internal/array.h"
30#include "internal/bignum.h"
31#include "internal/basic_operators.h"
32#include "internal/class.h"
33#include "internal/cont.h"
34#include "internal/error.h"
35#include "internal/hash.h"
36#include "internal/object.h"
37#include "internal/proc.h"
38#include "internal/st.h"
39#include "internal/symbol.h"
40#include "internal/thread.h"
41#include "internal/time.h"
42#include "internal/vm.h"
43#include "probes.h"
44#include "ruby/st.h"
45#include "ruby/util.h"
46#include "ruby_assert.h"
47#include "symbol.h"
48#include "ruby/thread_native.h"
49#include "ruby/ractor.h"
50#include "vm_sync.h"
51#include "builtin.h"
52
53/* Flags of RHash
54 *
55 * 1: RHASH_PASS_AS_KEYWORDS
56 * The hash is flagged as Ruby 2 keywords hash.
57 * 2: RHASH_PROC_DEFAULT
58 * The hash has a default proc (rather than a default value).
59 * 3: RHASH_ST_TABLE_FLAG
60 * The hash uses a ST table (rather than an AR table).
61 * 4-7: RHASH_AR_TABLE_SIZE_MASK
62 * The size of the AR table.
63 * 8-11: RHASH_AR_TABLE_BOUND_MASK
64 * The bounds of the AR table.
65 * 13-19: RHASH_LEV_MASK
66 * The iterational level of the hash. Used to prevent modifications
67 * to the hash during iteration.
68 */
69
70#ifndef HASH_DEBUG
71#define HASH_DEBUG 0
72#endif
73
74#if HASH_DEBUG
75#include "internal/gc.h"
76#endif
77
78#define SET_DEFAULT(hash, ifnone) ( \
79 FL_UNSET_RAW(hash, RHASH_PROC_DEFAULT), \
80 RHASH_SET_IFNONE(hash, ifnone))
81
82#define SET_PROC_DEFAULT(hash, proc) set_proc_default(hash, proc)
83
84#define COPY_DEFAULT(hash, hash2) copy_default(RHASH(hash), RHASH(hash2))
85
86static inline void
87copy_default(struct RHash *hash, const struct RHash *hash2)
88{
89 hash->basic.flags &= ~RHASH_PROC_DEFAULT;
90 hash->basic.flags |= hash2->basic.flags & RHASH_PROC_DEFAULT;
91 RHASH_SET_IFNONE(hash, RHASH_IFNONE((VALUE)hash2));
92}
93
94static VALUE rb_hash_s_try_convert(VALUE, VALUE);
95
96/*
97 * Hash WB strategy:
98 * 1. Check mutate st_* functions
99 * * st_insert()
100 * * st_insert2()
101 * * st_update()
102 * * st_add_direct()
103 * 2. Insert WBs
104 */
105
106/* :nodoc: */
107 VALUE
108rb_hash_freeze(VALUE hash)
109{
110 return rb_obj_freeze(hash);
111}
112
113 VALUE rb_cHash;
114 VALUE rb_cHash_empty_frozen;
115
116static VALUE envtbl;
117static ID id_hash, id_flatten_bang;
118static ID id_hash_iter_lev;
119
120#define id_default idDefault
121
122 VALUE
123rb_hash_set_ifnone(VALUE hash, VALUE ifnone)
124{
125 RB_OBJ_WRITE(hash, (&RHASH(hash)->ifnone), ifnone);
126 return hash;
127}
128
129int
130rb_any_cmp(VALUE a, VALUE b)
131{
132 if (a == b) return 0;
133 if (RB_TYPE_P(a, T_STRING) && RBASIC(a)->klass == rb_cString &&
134 RB_TYPE_P(b, T_STRING) && RBASIC(b)->klass == rb_cString) {
135 return rb_str_hash_cmp(a, b);
136 }
137 if (UNDEF_P(a) || UNDEF_P(b)) return -1;
138 if (SYMBOL_P(a) && SYMBOL_P(b)) {
139 return a != b;
140 }
141
142 return !rb_eql(a, b);
143}
144
145static VALUE
146hash_recursive(VALUE obj, VALUE arg, int recurse)
147{
148 if (recurse) return INT2FIX(0);
149 return rb_funcallv(obj, id_hash, 0, 0);
150}
151
152static long rb_objid_hash(st_index_t index);
153
154static st_index_t
155dbl_to_index(double d)
156{
157 union {double d; st_index_t i;} u;
158 u.d = d;
159 return u.i;
160}
161
162long
163rb_dbl_long_hash(double d)
164{
165 /* normalize -0.0 to 0.0 */
166 if (d == 0.0) d = 0.0;
167#if SIZEOF_INT == SIZEOF_VOIDP
168 return rb_memhash(&d, sizeof(d));
169#else
170 return rb_objid_hash(dbl_to_index(d));
171#endif
172}
173
174static inline long
175any_hash(VALUE a, st_index_t (*other_func)(VALUE))
176{
177 VALUE hval;
178 st_index_t hnum;
179
180 switch (TYPE(a)) {
181 case T_SYMBOL:
182 if (STATIC_SYM_P(a)) {
183 hnum = a >> (RUBY_SPECIAL_SHIFT + ID_SCOPE_SHIFT);
184 hnum = rb_hash_start(hnum);
185 }
186 else {
187 hnum = RSYMBOL(a)->hashval;
188 }
189 break;
190 case T_FIXNUM:
191 case T_TRUE:
192 case T_FALSE:
193 case T_NIL:
194 hnum = rb_objid_hash((st_index_t)a);
195 break;
196 case T_STRING:
197 hnum = rb_str_hash(a);
198 break;
199 case T_BIGNUM:
200 hval = rb_big_hash(a);
201 hnum = FIX2LONG(hval);
202 break;
203 case T_FLOAT: /* prevent pathological behavior: [Bug #10761] */
204 hnum = rb_dbl_long_hash(rb_float_value(a));
205 break;
206 default:
207 hnum = other_func(a);
208 }
209 if ((SIGNED_VALUE)hnum > 0)
210 hnum &= FIXNUM_MAX;
211 else
212 hnum |= FIXNUM_MIN;
213 return (long)hnum;
214}
215
216 VALUE rb_obj_hash(VALUE obj);
217 VALUE rb_vm_call0(rb_execution_context_t *ec, VALUE recv, ID id, int argc, const VALUE *argv, const rb_callable_method_entry_t *cme, int kw_splat);
218
219static st_index_t
220obj_any_hash(VALUE obj)
221{
222 VALUE hval = Qundef;
223 VALUE klass = CLASS_OF(obj);
224 if (klass) {
225 const rb_callable_method_entry_t *cme = rb_callable_method_entry(klass, id_hash);
226 if (cme && METHOD_ENTRY_BASIC(cme)) {
227 // Optimize away the frame push overhead if it's the default Kernel#hash
228 if (cme->def->type == VM_METHOD_TYPE_CFUNC && cme->def->body.cfunc.func == (rb_cfunc_t)rb_obj_hash) {
229 hval = rb_obj_hash(obj);
230 }
231 else if (RBASIC_CLASS(cme->defined_class) == rb_mKernel) {
232 hval = rb_vm_call0(GET_EC(), obj, id_hash, 0, 0, cme, 0);
233 }
234 }
235 }
236
237 if (UNDEF_P(hval)) {
238 hval = rb_exec_recursive_outer_mid(hash_recursive, obj, 0, id_hash);
239 }
240
241 while (!FIXNUM_P(hval)) {
242 if (RB_TYPE_P(hval, T_BIGNUM)) {
243 int sign;
244 unsigned long ul;
245 sign = rb_integer_pack(hval, &ul, 1, sizeof(ul), 0,
246 INTEGER_PACK_NATIVE_BYTE_ORDER);
247 if (sign < 0) {
248 hval = LONG2FIX(ul | FIXNUM_MIN);
249 }
250 else {
251 hval = LONG2FIX(ul & FIXNUM_MAX);
252 }
253 }
254 hval = rb_to_int(hval);
255 }
256
257 return FIX2LONG(hval);
258}
259
260st_index_t
261rb_any_hash(VALUE a)
262{
263 return any_hash(a, obj_any_hash);
264}
265
266 VALUE
267rb_hash(VALUE obj)
268{
269 return LONG2FIX(any_hash(obj, obj_any_hash));
270}
271
272
273/* Here is a hash function for 64-bit key. It is about 5 times faster
274 (2 times faster when uint128 type is absent) on Haswell than
275 tailored Spooky or City hash function can be. */
276
277/* Here we two primes with random bit generation. */
278static const uint64_t prime1 = ((uint64_t)0x2e0bb864 << 32) | 0xe9ea7df5;
279static const uint32_t prime2 = 0x830fcab9;
280
281
282static inline uint64_t
283mult_and_mix(uint64_t m1, uint64_t m2)
284{
285#if defined HAVE_UINT128_T
286 uint128_t r = (uint128_t) m1 * (uint128_t) m2;
287 return (uint64_t) (r >> 64) ^ (uint64_t) r;
288#else
289 uint64_t hm1 = m1 >> 32, hm2 = m2 >> 32;
290 uint64_t lm1 = m1, lm2 = m2;
291 uint64_t v64_128 = hm1 * hm2;
292 uint64_t v32_96 = hm1 * lm2 + lm1 * hm2;
293 uint64_t v1_32 = lm1 * lm2;
294
295 return (v64_128 + (v32_96 >> 32)) ^ ((v32_96 << 32) + v1_32);
296#endif
297}
298
299static inline uint64_t
300key64_hash(uint64_t key, uint32_t seed)
301{
302 return mult_and_mix(key + seed, prime1);
303}
304
305/* Should cast down the result for each purpose */
306#define st_index_hash(index) key64_hash(rb_hash_start(index), prime2)
307
308static long
309rb_objid_hash(st_index_t index)
310{
311 return (long)st_index_hash(index);
312}
313
314static st_index_t
315objid_hash(VALUE obj)
316{
317 VALUE object_id = rb_obj_id(obj);
318 if (!FIXNUM_P(object_id))
319 object_id = rb_big_hash(object_id);
320
321#if SIZEOF_LONG == SIZEOF_VOIDP
322 return (st_index_t)st_index_hash((st_index_t)NUM2LONG(object_id));
323#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
324 return (st_index_t)st_index_hash((st_index_t)NUM2LL(object_id));
325#endif
326}
327
331 VALUE
332rb_obj_hash(VALUE obj)
333{
334 long hnum = any_hash(obj, objid_hash);
335 return ST2FIX(hnum);
336}
337
338static const struct st_hash_type objhash = {
339 rb_any_cmp,
340 rb_any_hash,
341};
342
343#define rb_ident_cmp st_numcmp
344
345static st_index_t
346rb_ident_hash(st_data_t n)
347{
348#ifdef USE_FLONUM /* RUBY */
349 /*
350 * - flonum (on 64-bit) is pathologically bad, mix the actual
351 * float value in, but do not use the float value as-is since
352 * many integers get interpreted as 2.0 or -2.0 [Bug #10761]
353 */
354 if (FLONUM_P(n)) {
355 n ^= dbl_to_index(rb_float_value(n));
356 }
357#endif
358
359 return (st_index_t)st_index_hash((st_index_t)n);
360}
361
362#define identhash rb_hashtype_ident
363const struct st_hash_type rb_hashtype_ident = {
364 rb_ident_cmp,
365 rb_ident_hash,
366};
367
368#define RHASH_IDENTHASH_P(hash) (RHASH_TYPE(hash) == &identhash)
369#define RHASH_STRING_KEY_P(hash, key) (!RHASH_IDENTHASH_P(hash) && (rb_obj_class(key) == rb_cString))
370
371typedef st_index_t st_hash_t;
372
373/*
374 * RHASH_AR_TABLE_P(h):
375 * RHASH_AR_TABLE points to ar_table.
376 *
377 * !RHASH_AR_TABLE_P(h):
378 * RHASH_ST_TABLE points st_table.
379 */
380
381#define RHASH_AR_TABLE_MAX_BOUND RHASH_AR_TABLE_MAX_SIZE
382
383#define RHASH_AR_TABLE_REF(hash, n) (&RHASH_AR_TABLE(hash)->pairs[n])
384#define RHASH_AR_CLEARED_HINT 0xff
385
386static inline st_hash_t
387ar_do_hash(st_data_t key)
388{
389 return (st_hash_t)rb_any_hash(key);
390}
391
392static inline ar_hint_t
393ar_do_hash_hint(st_hash_t hash_value)
394{
395 return (ar_hint_t)hash_value;
396}
397
398static inline ar_hint_t
399ar_hint(VALUE hash, unsigned int index)
400{
401 return RHASH_AR_TABLE(hash)->ar_hint.ary[index];
402}
403
404static inline void
405ar_hint_set_hint(VALUE hash, unsigned int index, ar_hint_t hint)
406{
407 RHASH_AR_TABLE(hash)->ar_hint.ary[index] = hint;
408}
409
410static inline void
411ar_hint_set(VALUE hash, unsigned int index, st_hash_t hash_value)
412{
413 ar_hint_set_hint(hash, index, ar_do_hash_hint(hash_value));
414}
415
416static inline void
417ar_clear_entry(VALUE hash, unsigned int index)
418{
419 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
420 pair->key = Qundef;
421 ar_hint_set_hint(hash, index, RHASH_AR_CLEARED_HINT);
422}
423
424static inline int
425ar_cleared_entry(VALUE hash, unsigned int index)
426{
427 if (ar_hint(hash, index) == RHASH_AR_CLEARED_HINT) {
428 /* RHASH_AR_CLEARED_HINT is only a hint, not mean cleared entry,
429 * so you need to check key == Qundef
430 */
431 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
432 return UNDEF_P(pair->key);
433 }
434 else {
435 return FALSE;
436 }
437}
438
439static inline void
440ar_set_entry(VALUE hash, unsigned int index, st_data_t key, st_data_t val, st_hash_t hash_value)
441{
442 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, index);
443 pair->key = key;
444 pair->val = val;
445 ar_hint_set(hash, index, hash_value);
446}
447
448#define RHASH_AR_TABLE_SIZE(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
449 RHASH_AR_TABLE_SIZE_RAW(h))
450
451#define RHASH_AR_TABLE_BOUND_RAW(h) \
452 ((unsigned int)((RBASIC(h)->flags >> RHASH_AR_TABLE_BOUND_SHIFT) & \
453 (RHASH_AR_TABLE_BOUND_MASK >> RHASH_AR_TABLE_BOUND_SHIFT)))
454
455#define RHASH_ST_TABLE_SET(h, s) rb_hash_st_table_set(h, s)
456#define RHASH_TYPE(hash) (RHASH_AR_TABLE_P(hash) ? &objhash : RHASH_ST_TABLE(hash)->type)
457
458#define HASH_ASSERT(expr) RUBY_ASSERT_MESG_WHEN(HASH_DEBUG, expr, #expr)
459
460static inline unsigned int
461RHASH_AR_TABLE_BOUND(VALUE h)
462{
463 HASH_ASSERT(RHASH_AR_TABLE_P(h));
464 const unsigned int bound = RHASH_AR_TABLE_BOUND_RAW(h);
465 HASH_ASSERT(bound <= RHASH_AR_TABLE_MAX_SIZE);
466 return bound;
467}
468
469#if HASH_DEBUG
470#define hash_verify(hash) hash_verify_(hash, __FILE__, __LINE__)
471
472void
473rb_hash_dump(VALUE hash)
474{
475 rb_obj_info_dump(hash);
476
477 if (RHASH_AR_TABLE_P(hash)) {
478 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
479
480 fprintf(stderr, " size:%u bound:%u\n",
481 RHASH_AR_TABLE_SIZE(hash), bound);
482
483 for (i=0; i<bound; i++) {
484 st_data_t k, v;
485
486 if (!ar_cleared_entry(hash, i)) {
487 char b1[0x100], b2[0x100];
488 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
489 k = pair->key;
490 v = pair->val;
491 fprintf(stderr, " %d key:%s val:%s hint:%02x\n", i,
492 rb_raw_obj_info(b1, 0x100, k),
493 rb_raw_obj_info(b2, 0x100, v),
494 ar_hint(hash, i));
495 }
496 else {
497 fprintf(stderr, " %d empty\n", i);
498 }
499 }
500 }
501}
502
503static VALUE
504hash_verify_(VALUE hash, const char *file, int line)
505{
506 HASH_ASSERT(RB_TYPE_P(hash, T_HASH));
507
508 if (RHASH_AR_TABLE_P(hash)) {
509 unsigned i, n = 0, bound = RHASH_AR_TABLE_BOUND(hash);
510
511 for (i=0; i<bound; i++) {
512 st_data_t k, v;
513 if (!ar_cleared_entry(hash, i)) {
514 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
515 k = pair->key;
516 v = pair->val;
517 HASH_ASSERT(!UNDEF_P(k));
518 HASH_ASSERT(!UNDEF_P(v));
519 n++;
520 }
521 }
522 if (n != RHASH_AR_TABLE_SIZE(hash)) {
523 rb_bug("n:%u, RHASH_AR_TABLE_SIZE:%u", n, RHASH_AR_TABLE_SIZE(hash));
524 }
525 }
526 else {
527 HASH_ASSERT(RHASH_ST_TABLE(hash) != NULL);
528 HASH_ASSERT(RHASH_AR_TABLE_SIZE_RAW(hash) == 0);
529 HASH_ASSERT(RHASH_AR_TABLE_BOUND_RAW(hash) == 0);
530 }
531
532 return hash;
533}
534
535#else
536#define hash_verify(h) ((void)0)
537#endif
538
539static inline int
540RHASH_TABLE_EMPTY_P(VALUE hash)
541{
542 return RHASH_SIZE(hash) == 0;
543}
544
545#define RHASH_SET_ST_FLAG(h) FL_SET_RAW(h, RHASH_ST_TABLE_FLAG)
546#define RHASH_UNSET_ST_FLAG(h) FL_UNSET_RAW(h, RHASH_ST_TABLE_FLAG)
547
548static void
549hash_st_table_init(VALUE hash, const struct st_hash_type *type, st_index_t size)
550{
551 st_init_existing_table_with_size(RHASH_ST_TABLE(hash), type, size);
552 RHASH_SET_ST_FLAG(hash);
553}
554
555void
556rb_hash_st_table_set(VALUE hash, st_table *st)
557{
558 HASH_ASSERT(st != NULL);
559 RHASH_SET_ST_FLAG(hash);
560
561 *RHASH_ST_TABLE(hash) = *st;
562}
563
564static inline void
565RHASH_AR_TABLE_BOUND_SET(VALUE h, st_index_t n)
566{
567 HASH_ASSERT(RHASH_AR_TABLE_P(h));
568 HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_BOUND);
569
570 RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
571 RBASIC(h)->flags |= n << RHASH_AR_TABLE_BOUND_SHIFT;
572}
573
574static inline void
575RHASH_AR_TABLE_SIZE_SET(VALUE h, st_index_t n)
576{
577 HASH_ASSERT(RHASH_AR_TABLE_P(h));
578 HASH_ASSERT(n <= RHASH_AR_TABLE_MAX_SIZE);
579
580 RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
581 RBASIC(h)->flags |= n << RHASH_AR_TABLE_SIZE_SHIFT;
582}
583
584static inline void
585HASH_AR_TABLE_SIZE_ADD(VALUE h, st_index_t n)
586{
587 HASH_ASSERT(RHASH_AR_TABLE_P(h));
588
589 RHASH_AR_TABLE_SIZE_SET(h, RHASH_AR_TABLE_SIZE(h) + n);
590
591 hash_verify(h);
592}
593
594#define RHASH_AR_TABLE_SIZE_INC(h) HASH_AR_TABLE_SIZE_ADD(h, 1)
595
596static inline void
597RHASH_AR_TABLE_SIZE_DEC(VALUE h)
598{
599 HASH_ASSERT(RHASH_AR_TABLE_P(h));
600 int new_size = RHASH_AR_TABLE_SIZE(h) - 1;
601
602 if (new_size != 0) {
603 RHASH_AR_TABLE_SIZE_SET(h, new_size);
604 }
605 else {
606 RHASH_AR_TABLE_SIZE_SET(h, 0);
607 RHASH_AR_TABLE_BOUND_SET(h, 0);
608 }
609 hash_verify(h);
610}
611
612static inline void
613RHASH_AR_TABLE_CLEAR(VALUE h)
614{
615 RBASIC(h)->flags &= ~RHASH_AR_TABLE_SIZE_MASK;
616 RBASIC(h)->flags &= ~RHASH_AR_TABLE_BOUND_MASK;
617
618 memset(RHASH_AR_TABLE(h), 0, sizeof(ar_table));
619}
620
621NOINLINE(static int ar_equal(VALUE x, VALUE y));
622
623static int
624ar_equal(VALUE x, VALUE y)
625{
626 return rb_any_cmp(x, y) == 0;
627}
628
629static unsigned
630ar_find_entry_hint(VALUE hash, ar_hint_t hint, st_data_t key)
631{
632 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
633 const ar_hint_t *hints = RHASH_AR_TABLE(hash)->ar_hint.ary;
634
635 /* if table is NULL, then bound also should be 0 */
636
637 for (i = 0; i < bound; i++) {
638 if (hints[i] == hint) {
639 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
640 if (ar_equal(key, pair->key)) {
641 RB_DEBUG_COUNTER_INC(artable_hint_hit);
642 return i;
643 }
644 else {
645#if 0
646 static int pid;
647 static char fname[256];
648 static FILE *fp;
649
650 if (pid != getpid()) {
651 snprintf(fname, sizeof(fname), "/tmp/ruby-armiss.%d", pid = getpid());
652 if ((fp = fopen(fname, "w")) == NULL) rb_bug("fopen");
653 }
654
655 st_hash_t h1 = ar_do_hash(key);
656 st_hash_t h2 = ar_do_hash(pair->key);
657
658 fprintf(fp, "miss: hash_eq:%d hints[%d]:%02x hint:%02x\n"
659 " key :%016lx %s\n"
660 " pair->key:%016lx %s\n",
661 h1 == h2, i, hints[i], hint,
662 h1, rb_obj_info(key), h2, rb_obj_info(pair->key));
663#endif
664 RB_DEBUG_COUNTER_INC(artable_hint_miss);
665 }
666 }
667 }
668 RB_DEBUG_COUNTER_INC(artable_hint_notfound);
669 return RHASH_AR_TABLE_MAX_BOUND;
670}
671
672static unsigned
673ar_find_entry(VALUE hash, st_hash_t hash_value, st_data_t key)
674{
675 ar_hint_t hint = ar_do_hash_hint(hash_value);
676 return ar_find_entry_hint(hash, hint, key);
677}
678
679static inline void
680hash_ar_free_and_clear_table(VALUE hash)
681{
682 RHASH_AR_TABLE_CLEAR(hash);
683
684 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
685 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
686}
687
688void rb_st_add_direct_with_hash(st_table *tab, st_data_t key, st_data_t value, st_hash_t hash); // st.c
689
690enum ar_each_key_type {
691 ar_each_key_copy,
692 ar_each_key_cmp,
693 ar_each_key_insert,
694};
695
696static inline int
697ar_each_key(ar_table *ar, int max, enum ar_each_key_type type, st_data_t *dst_keys, st_table *new_tab, st_hash_t *hashes)
698{
699 for (int i = 0; i < max; i++) {
700 ar_table_pair *pair = &ar->pairs[i];
701
702 switch (type) {
703 case ar_each_key_copy:
704 dst_keys[i] = pair->key;
705 break;
706 case ar_each_key_cmp:
707 if (dst_keys[i] != pair->key) return 1;
708 break;
709 case ar_each_key_insert:
710 if (UNDEF_P(pair->key)) continue; // deleted entry
711 rb_st_add_direct_with_hash(new_tab, pair->key, pair->val, hashes[i]);
712 break;
713 }
714 }
715
716 return 0;
717}
718
719static st_table *
720ar_force_convert_table(VALUE hash, const char *file, int line)
721{
722 if (RHASH_ST_TABLE_P(hash)) {
723 return RHASH_ST_TABLE(hash);
724 }
725 else {
726 ar_table *ar = RHASH_AR_TABLE(hash);
727 st_hash_t hashes[RHASH_AR_TABLE_MAX_SIZE];
728 unsigned int bound, size;
729
730 // prepare hash values
731 do {
732 st_data_t keys[RHASH_AR_TABLE_MAX_SIZE];
733 bound = RHASH_AR_TABLE_BOUND(hash);
734 size = RHASH_AR_TABLE_SIZE(hash);
735 ar_each_key(ar, bound, ar_each_key_copy, keys, NULL, NULL);
736
737 for (unsigned int i = 0; i < bound; i++) {
738 // do_hash calls #hash method and it can modify hash object
739 hashes[i] = UNDEF_P(keys[i]) ? 0 : ar_do_hash(keys[i]);
740 }
741
742 // check if modified
743 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) return RHASH_ST_TABLE(hash);
744 if (UNLIKELY(RHASH_AR_TABLE_BOUND(hash) != bound)) continue;
745 if (UNLIKELY(ar_each_key(ar, bound, ar_each_key_cmp, keys, NULL, NULL))) continue;
746 } while (0);
747
748 // make st
749 st_table tab;
750 st_table *new_tab = &tab;
751 st_init_existing_table_with_size(new_tab, &objhash, size);
752 ar_each_key(ar, bound, ar_each_key_insert, NULL, new_tab, hashes);
753 hash_ar_free_and_clear_table(hash);
754 RHASH_ST_TABLE_SET(hash, new_tab);
755 return RHASH_ST_TABLE(hash);
756 }
757}
758
759static int
760ar_compact_table(VALUE hash)
761{
762 const unsigned bound = RHASH_AR_TABLE_BOUND(hash);
763 const unsigned size = RHASH_AR_TABLE_SIZE(hash);
764
765 if (size == bound) {
766 return size;
767 }
768 else {
769 unsigned i, j=0;
770 ar_table_pair *pairs = RHASH_AR_TABLE(hash)->pairs;
771
772 for (i=0; i<bound; i++) {
773 if (ar_cleared_entry(hash, i)) {
774 if (j <= i) j = i+1;
775 for (; j<bound; j++) {
776 if (!ar_cleared_entry(hash, j)) {
777 pairs[i] = pairs[j];
778 ar_hint_set_hint(hash, i, (st_hash_t)ar_hint(hash, j));
779 ar_clear_entry(hash, j);
780 j++;
781 goto found;
782 }
783 }
784 /* non-empty is not found */
785 goto done;
786 found:;
787 }
788 }
789 done:
790 HASH_ASSERT(i<=bound);
791
792 RHASH_AR_TABLE_BOUND_SET(hash, size);
793 hash_verify(hash);
794 return size;
795 }
796}
797
798static int
799ar_add_direct_with_hash(VALUE hash, st_data_t key, st_data_t val, st_hash_t hash_value)
800{
801 unsigned bin = RHASH_AR_TABLE_BOUND(hash);
802
803 if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
804 return 1;
805 }
806 else {
807 if (UNLIKELY(bin >= RHASH_AR_TABLE_MAX_BOUND)) {
808 bin = ar_compact_table(hash);
809 }
810 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
811
812 ar_set_entry(hash, bin, key, val, hash_value);
813 RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
814 RHASH_AR_TABLE_SIZE_INC(hash);
815 return 0;
816 }
817}
818
819static void
820ensure_ar_table(VALUE hash)
821{
822 if (!RHASH_AR_TABLE_P(hash)) {
823 rb_raise(rb_eRuntimeError, "hash representation was changed during iteration");
824 }
825}
826
827static int
828ar_general_foreach(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
829{
830 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
831 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
832
833 for (i = 0; i < bound; i++) {
834 if (ar_cleared_entry(hash, i)) continue;
835
836 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
837 st_data_t key = (st_data_t)pair->key;
838 st_data_t val = (st_data_t)pair->val;
839 enum st_retval retval = (*func)(key, val, arg, 0);
840 ensure_ar_table(hash);
841 /* pair may be not valid here because of theap */
842
843 switch (retval) {
844 case ST_CONTINUE:
845 break;
846 case ST_CHECK:
847 case ST_STOP:
848 return 0;
849 case ST_REPLACE:
850 if (replace) {
851 (*replace)(&key, &val, arg, TRUE);
852
853 // TODO: pair should be same as pair before.
854 pair = RHASH_AR_TABLE_REF(hash, i);
855 pair->key = (VALUE)key;
856 pair->val = (VALUE)val;
857 }
858 break;
859 case ST_DELETE:
860 ar_clear_entry(hash, i);
861 RHASH_AR_TABLE_SIZE_DEC(hash);
862 break;
863 }
864 }
865 }
866 return 0;
867}
868
869static int
870ar_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
871{
872 return ar_general_foreach(hash, func, replace, arg);
873}
874
875 struct functor {
876 st_foreach_callback_func *func;
877 st_data_t arg;
878};
879
880static int
881apply_functor(st_data_t k, st_data_t v, st_data_t d, int _)
882{
883 const struct functor *f = (void *)d;
884 return f->func(k, v, f->arg);
885}
886
887static int
888ar_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
889{
890 const struct functor f = { func, arg };
891 return ar_general_foreach(hash, apply_functor, NULL, (st_data_t)&f);
892}
893
894static int
895ar_foreach_check(VALUE hash, st_foreach_check_callback_func *func, st_data_t arg,
896 st_data_t never)
897{
898 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
899 unsigned i, ret = 0, bound = RHASH_AR_TABLE_BOUND(hash);
900 enum st_retval retval;
901 st_data_t key;
902 ar_table_pair *pair;
903 ar_hint_t hint;
904
905 for (i = 0; i < bound; i++) {
906 if (ar_cleared_entry(hash, i)) continue;
907
908 pair = RHASH_AR_TABLE_REF(hash, i);
909 key = pair->key;
910 hint = ar_hint(hash, i);
911
912 retval = (*func)(key, pair->val, arg, 0);
913 ensure_ar_table(hash);
914 hash_verify(hash);
915
916 switch (retval) {
917 case ST_CHECK: {
918 pair = RHASH_AR_TABLE_REF(hash, i);
919 if (pair->key == never) break;
920 ret = ar_find_entry_hint(hash, hint, key);
921 if (ret == RHASH_AR_TABLE_MAX_BOUND) {
922 (*func)(0, 0, arg, 1);
923 return 2;
924 }
925 }
926 case ST_CONTINUE:
927 break;
928 case ST_STOP:
929 case ST_REPLACE:
930 return 0;
931 case ST_DELETE: {
932 if (!ar_cleared_entry(hash, i)) {
933 ar_clear_entry(hash, i);
934 RHASH_AR_TABLE_SIZE_DEC(hash);
935 }
936 break;
937 }
938 }
939 }
940 }
941 return 0;
942}
943
944static int
945ar_update(VALUE hash, st_data_t key,
946 st_update_callback_func *func, st_data_t arg)
947{
948 int retval, existing;
949 unsigned bin = RHASH_AR_TABLE_MAX_BOUND;
950 st_data_t value = 0, old_key;
951 st_hash_t hash_value = ar_do_hash(key);
952
953 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
954 // `#hash` changes ar_table -> st_table
955 return -1;
956 }
957
958 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
959 bin = ar_find_entry(hash, hash_value, key);
960 existing = (bin != RHASH_AR_TABLE_MAX_BOUND) ? TRUE : FALSE;
961 }
962 else {
963 existing = FALSE;
964 }
965
966 if (existing) {
967 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
968 key = pair->key;
969 value = pair->val;
970 }
971 old_key = key;
972 retval = (*func)(&key, &value, arg, existing);
973 /* pair can be invalid here because of theap */
974 ensure_ar_table(hash);
975
976 switch (retval) {
977 case ST_CONTINUE:
978 if (!existing) {
979 if (ar_add_direct_with_hash(hash, key, value, hash_value)) {
980 return -1;
981 }
982 }
983 else {
984 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
985 if (old_key != key) {
986 pair->key = key;
987 }
988 pair->val = value;
989 }
990 break;
991 case ST_DELETE:
992 if (existing) {
993 ar_clear_entry(hash, bin);
994 RHASH_AR_TABLE_SIZE_DEC(hash);
995 }
996 break;
997 }
998 return existing;
999}
1000
1001static int
1002ar_insert(VALUE hash, st_data_t key, st_data_t value)
1003{
1004 unsigned bin = RHASH_AR_TABLE_BOUND(hash);
1005 st_hash_t hash_value = ar_do_hash(key);
1006
1007 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1008 // `#hash` changes ar_table -> st_table
1009 return -1;
1010 }
1011
1012 bin = ar_find_entry(hash, hash_value, key);
1013 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1014 if (RHASH_AR_TABLE_SIZE(hash) >= RHASH_AR_TABLE_MAX_SIZE) {
1015 return -1;
1016 }
1017 else if (bin >= RHASH_AR_TABLE_MAX_BOUND) {
1018 bin = ar_compact_table(hash);
1019 }
1020 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1021
1022 ar_set_entry(hash, bin, key, value, hash_value);
1023 RHASH_AR_TABLE_BOUND_SET(hash, bin+1);
1024 RHASH_AR_TABLE_SIZE_INC(hash);
1025 return 0;
1026 }
1027 else {
1028 RHASH_AR_TABLE_REF(hash, bin)->val = value;
1029 return 1;
1030 }
1031}
1032
1033static int
1034ar_lookup(VALUE hash, st_data_t key, st_data_t *value)
1035{
1036 if (RHASH_AR_TABLE_SIZE(hash) == 0) {
1037 return 0;
1038 }
1039 else {
1040 st_hash_t hash_value = ar_do_hash(key);
1041 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1042 // `#hash` changes ar_table -> st_table
1043 return st_lookup(RHASH_ST_TABLE(hash), key, value);
1044 }
1045 unsigned bin = ar_find_entry(hash, hash_value, key);
1046
1047 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1048 return 0;
1049 }
1050 else {
1051 HASH_ASSERT(bin < RHASH_AR_TABLE_MAX_BOUND);
1052 if (value != NULL) {
1053 *value = RHASH_AR_TABLE_REF(hash, bin)->val;
1054 }
1055 return 1;
1056 }
1057 }
1058}
1059
1060static int
1061ar_delete(VALUE hash, st_data_t *key, st_data_t *value)
1062{
1063 unsigned bin;
1064 st_hash_t hash_value = ar_do_hash(*key);
1065
1066 if (UNLIKELY(!RHASH_AR_TABLE_P(hash))) {
1067 // `#hash` changes ar_table -> st_table
1068 return st_delete(RHASH_ST_TABLE(hash), key, value);
1069 }
1070
1071 bin = ar_find_entry(hash, hash_value, *key);
1072
1073 if (bin == RHASH_AR_TABLE_MAX_BOUND) {
1074 if (value != 0) *value = 0;
1075 return 0;
1076 }
1077 else {
1078 if (value != 0) {
1079 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, bin);
1080 *value = pair->val;
1081 }
1082 ar_clear_entry(hash, bin);
1083 RHASH_AR_TABLE_SIZE_DEC(hash);
1084 return 1;
1085 }
1086}
1087
1088static int
1089ar_shift(VALUE hash, st_data_t *key, st_data_t *value)
1090{
1091 if (RHASH_AR_TABLE_SIZE(hash) > 0) {
1092 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1093
1094 for (i = 0; i < bound; i++) {
1095 if (!ar_cleared_entry(hash, i)) {
1096 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
1097 if (value != 0) *value = pair->val;
1098 *key = pair->key;
1099 ar_clear_entry(hash, i);
1100 RHASH_AR_TABLE_SIZE_DEC(hash);
1101 return 1;
1102 }
1103 }
1104 }
1105 if (value != NULL) *value = 0;
1106 return 0;
1107}
1108
1109static long
1110ar_keys(VALUE hash, st_data_t *keys, st_index_t size)
1111{
1112 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1113 st_data_t *keys_start = keys, *keys_end = keys + size;
1114
1115 for (i = 0; i < bound; i++) {
1116 if (keys == keys_end) {
1117 break;
1118 }
1119 else {
1120 if (!ar_cleared_entry(hash, i)) {
1121 *keys++ = RHASH_AR_TABLE_REF(hash, i)->key;
1122 }
1123 }
1124 }
1125
1126 return keys - keys_start;
1127}
1128
1129static long
1130ar_values(VALUE hash, st_data_t *values, st_index_t size)
1131{
1132 unsigned i, bound = RHASH_AR_TABLE_BOUND(hash);
1133 st_data_t *values_start = values, *values_end = values + size;
1134
1135 for (i = 0; i < bound; i++) {
1136 if (values == values_end) {
1137 break;
1138 }
1139 else {
1140 if (!ar_cleared_entry(hash, i)) {
1141 *values++ = RHASH_AR_TABLE_REF(hash, i)->val;
1142 }
1143 }
1144 }
1145
1146 return values - values_start;
1147}
1148
1149static ar_table*
1150ar_copy(VALUE hash1, VALUE hash2)
1151{
1152 ar_table *old_tab = RHASH_AR_TABLE(hash2);
1153 ar_table *new_tab = RHASH_AR_TABLE(hash1);
1154
1155 *new_tab = *old_tab;
1156 RHASH_AR_TABLE(hash1)->ar_hint.word = RHASH_AR_TABLE(hash2)->ar_hint.word;
1157 RHASH_AR_TABLE_BOUND_SET(hash1, RHASH_AR_TABLE_BOUND(hash2));
1158 RHASH_AR_TABLE_SIZE_SET(hash1, RHASH_AR_TABLE_SIZE(hash2));
1159
1160 rb_gc_writebarrier_remember(hash1);
1161
1162 return new_tab;
1163}
1164
1165static void
1166ar_clear(VALUE hash)
1167{
1168 if (RHASH_AR_TABLE(hash) != NULL) {
1169 RHASH_AR_TABLE_SIZE_SET(hash, 0);
1170 RHASH_AR_TABLE_BOUND_SET(hash, 0);
1171 }
1172 else {
1173 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash) == 0);
1174 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash) == 0);
1175 }
1176}
1177
1178static void
1179hash_st_free(VALUE hash)
1180{
1181 HASH_ASSERT(RHASH_ST_TABLE_P(hash));
1182
1183 st_table *tab = RHASH_ST_TABLE(hash);
1184
1185 xfree(tab->bins);
1186 xfree(tab->entries);
1187}
1188
1189static void
1190hash_st_free_and_clear_table(VALUE hash)
1191{
1192 hash_st_free(hash);
1193
1194 RHASH_ST_CLEAR(hash);
1195}
1196
1197void
1198rb_hash_free(VALUE hash)
1199{
1200 if (RHASH_ST_TABLE_P(hash)) {
1201 hash_st_free(hash);
1202 }
1203}
1204
1205typedef int st_foreach_func(st_data_t, st_data_t, st_data_t);
1206
1207 struct foreach_safe_arg {
1208 st_table *tbl;
1209 st_foreach_func *func;
1210 st_data_t arg;
1211};
1212
1213static int
1214foreach_safe_i(st_data_t key, st_data_t value, st_data_t args, int error)
1215{
1216 int status;
1217 struct foreach_safe_arg *arg = (void *)args;
1218
1219 if (error) return ST_STOP;
1220 status = (*arg->func)(key, value, arg->arg);
1221 if (status == ST_CONTINUE) {
1222 return ST_CHECK;
1223 }
1224 return status;
1225}
1226
1227void
1228 st_foreach_safe(st_table *table, st_foreach_func *func, st_data_t a)
1229{
1230 struct foreach_safe_arg arg;
1231
1232 arg.tbl = table;
1233 arg.func = (st_foreach_func *)func;
1234 arg.arg = a;
1235 if (st_foreach_check(table, foreach_safe_i, (st_data_t)&arg, 0)) {
1236 rb_raise(rb_eRuntimeError, "hash modified during iteration");
1237 }
1238}
1239
1240typedef int rb_foreach_func(VALUE, VALUE, VALUE);
1241
1242 struct hash_foreach_arg {
1243 VALUE hash;
1244 rb_foreach_func *func;
1245 VALUE arg;
1246};
1247
1248static int
1249hash_iter_status_check(int status)
1250{
1251 switch (status) {
1252 case ST_DELETE:
1253 return ST_DELETE;
1254 case ST_CONTINUE:
1255 break;
1256 case ST_STOP:
1257 return ST_STOP;
1258 }
1259
1260 return ST_CHECK;
1261}
1262
1263static int
1264hash_ar_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1265{
1266 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1267
1268 if (error) return ST_STOP;
1269
1270 int status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1271 /* TODO: rehash check? rb_raise(rb_eRuntimeError, "rehash occurred during iteration"); */
1272
1273 return hash_iter_status_check(status);
1274}
1275
1276static int
1277hash_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error)
1278{
1279 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)argp;
1280
1281 if (error) return ST_STOP;
1282
1283 st_table *tbl = RHASH_ST_TABLE(arg->hash);
1284 int status = (*arg->func)((VALUE)key, (VALUE)value, arg->arg);
1285
1286 if (RHASH_ST_TABLE(arg->hash) != tbl) {
1287 rb_raise(rb_eRuntimeError, "rehash occurred during iteration");
1288 }
1289
1290 return hash_iter_status_check(status);
1291}
1292
1293static unsigned long
1294iter_lev_in_ivar(VALUE hash)
1295{
1296 VALUE levval = rb_ivar_get(hash, id_hash_iter_lev);
1297 HASH_ASSERT(FIXNUM_P(levval));
1298 long lev = FIX2LONG(levval);
1299 HASH_ASSERT(lev >= 0);
1300 return (unsigned long)lev;
1301}
1302
1303void rb_ivar_set_internal(VALUE obj, ID id, VALUE val);
1304
1305static void
1306iter_lev_in_ivar_set(VALUE hash, unsigned long lev)
1307{
1308 HASH_ASSERT(lev >= RHASH_LEV_MAX);
1309 HASH_ASSERT(POSFIXABLE(lev)); /* POSFIXABLE means fitting to long */
1310 rb_ivar_set_internal(hash, id_hash_iter_lev, LONG2FIX((long)lev));
1311}
1312
1313static inline unsigned long
1314iter_lev_in_flags(VALUE hash)
1315{
1316 return (unsigned long)((RBASIC(hash)->flags >> RHASH_LEV_SHIFT) & RHASH_LEV_MAX);
1317}
1318
1319static inline void
1320iter_lev_in_flags_set(VALUE hash, unsigned long lev)
1321{
1322 HASH_ASSERT(lev <= RHASH_LEV_MAX);
1323 RBASIC(hash)->flags = ((RBASIC(hash)->flags & ~RHASH_LEV_MASK) | ((VALUE)lev << RHASH_LEV_SHIFT));
1324}
1325
1326static inline bool
1327hash_iterating_p(VALUE hash)
1328{
1329 return iter_lev_in_flags(hash) > 0;
1330}
1331
1332static void
1333hash_iter_lev_inc(VALUE hash)
1334{
1335 unsigned long lev = iter_lev_in_flags(hash);
1336 if (lev == RHASH_LEV_MAX) {
1337 lev = iter_lev_in_ivar(hash) + 1;
1338 if (!POSFIXABLE(lev)) { /* paranoiac check */
1339 rb_raise(rb_eRuntimeError, "too much nested iterations");
1340 }
1341 }
1342 else {
1343 lev += 1;
1344 iter_lev_in_flags_set(hash, lev);
1345 if (lev < RHASH_LEV_MAX) return;
1346 }
1347 iter_lev_in_ivar_set(hash, lev);
1348}
1349
1350static void
1351hash_iter_lev_dec(VALUE hash)
1352{
1353 unsigned long lev = iter_lev_in_flags(hash);
1354 if (lev == RHASH_LEV_MAX) {
1355 lev = iter_lev_in_ivar(hash);
1356 if (lev > RHASH_LEV_MAX) {
1357 iter_lev_in_ivar_set(hash, lev-1);
1358 return;
1359 }
1360 rb_attr_delete(hash, id_hash_iter_lev);
1361 }
1362 else if (lev == 0) {
1363 rb_raise(rb_eRuntimeError, "iteration level underflow");
1364 }
1365 iter_lev_in_flags_set(hash, lev - 1);
1366}
1367
1368static VALUE
1369hash_foreach_ensure(VALUE hash)
1370{
1371 hash_iter_lev_dec(hash);
1372 return 0;
1373}
1374
1375/* This does not manage iteration level */
1376int
1377rb_hash_stlike_foreach(VALUE hash, st_foreach_callback_func *func, st_data_t arg)
1378{
1379 if (RHASH_AR_TABLE_P(hash)) {
1380 return ar_foreach(hash, func, arg);
1381 }
1382 else {
1383 return st_foreach(RHASH_ST_TABLE(hash), func, arg);
1384 }
1385}
1386
1387/* This does not manage iteration level */
1388int
1389rb_hash_stlike_foreach_with_replace(VALUE hash, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg)
1390{
1391 if (RHASH_AR_TABLE_P(hash)) {
1392 return ar_foreach_with_replace(hash, func, replace, arg);
1393 }
1394 else {
1395 return st_foreach_with_replace(RHASH_ST_TABLE(hash), func, replace, arg);
1396 }
1397}
1398
1399static VALUE
1400hash_foreach_call(VALUE arg)
1401{
1402 VALUE hash = ((struct hash_foreach_arg *)arg)->hash;
1403 int ret = 0;
1404 if (RHASH_AR_TABLE_P(hash)) {
1405 ret = ar_foreach_check(hash, hash_ar_foreach_iter,
1406 (st_data_t)arg, (st_data_t)Qundef);
1407 }
1408 else if (RHASH_ST_TABLE_P(hash)) {
1409 ret = st_foreach_check(RHASH_ST_TABLE(hash), hash_foreach_iter,
1410 (st_data_t)arg, (st_data_t)Qundef);
1411 }
1412 if (ret) {
1413 rb_raise(rb_eRuntimeError, "ret: %d, hash modified during iteration", ret);
1414 }
1415 return Qnil;
1416}
1417
1418void
1419rb_hash_foreach(VALUE hash, rb_foreach_func *func, VALUE farg)
1420{
1421 struct hash_foreach_arg arg;
1422
1423 if (RHASH_TABLE_EMPTY_P(hash))
1424 return;
1425 arg.hash = hash;
1426 arg.func = (rb_foreach_func *)func;
1427 arg.arg = farg;
1428 if (RB_OBJ_FROZEN(hash)) {
1429 hash_foreach_call((VALUE)&arg);
1430 }
1431 else {
1432 hash_iter_lev_inc(hash);
1433 rb_ensure(hash_foreach_call, (VALUE)&arg, hash_foreach_ensure, hash);
1434 }
1435 hash_verify(hash);
1436}
1437
1438void rb_st_compact_table(st_table *tab);
1439
1440static void
1441compact_after_delete(VALUE hash)
1442{
1443 if (!hash_iterating_p(hash) && RHASH_ST_TABLE_P(hash)) {
1444 rb_st_compact_table(RHASH_ST_TABLE(hash));
1445 }
1446}
1447
1448static VALUE
1449hash_alloc_flags(VALUE klass, VALUE flags, VALUE ifnone, bool st)
1450{
1451 const VALUE wb = (RGENGC_WB_PROTECTED_HASH ? FL_WB_PROTECTED : 0);
1452 const size_t size = sizeof(struct RHash) + (st ? sizeof(st_table) : sizeof(ar_table));
1453
1454 NEWOBJ_OF(hash, struct RHash, klass, T_HASH | wb | flags, size, 0);
1455
1456 RHASH_SET_IFNONE((VALUE)hash, ifnone);
1457
1458 return (VALUE)hash;
1459}
1460
1461static VALUE
1462hash_alloc(VALUE klass)
1463{
1464 /* Allocate to be able to fit both st_table and ar_table. */
1465 return hash_alloc_flags(klass, 0, Qnil, sizeof(st_table) > sizeof(ar_table));
1466}
1467
1468static VALUE
1469empty_hash_alloc(VALUE klass)
1470{
1471 RUBY_DTRACE_CREATE_HOOK(HASH, 0);
1472
1473 return hash_alloc(klass);
1474}
1475
1476 VALUE
1477rb_hash_new(void)
1478{
1479 return hash_alloc(rb_cHash);
1480}
1481
1482static VALUE
1483copy_compare_by_id(VALUE hash, VALUE basis)
1484{
1485 if (rb_hash_compare_by_id_p(basis)) {
1486 return rb_hash_compare_by_id(hash);
1487 }
1488 return hash;
1489}
1490
1491 VALUE
1492rb_hash_new_with_size(st_index_t size)
1493{
1494 bool st = size > RHASH_AR_TABLE_MAX_SIZE;
1495 VALUE ret = hash_alloc_flags(rb_cHash, 0, Qnil, st);
1496
1497 if (st) {
1498 hash_st_table_init(ret, &objhash, size);
1499 }
1500
1501 return ret;
1502}
1503
1504 VALUE
1505rb_hash_new_capa(long capa)
1506{
1507 return rb_hash_new_with_size((st_index_t)capa);
1508}
1509
1510static VALUE
1511hash_copy(VALUE ret, VALUE hash)
1512{
1513 if (RHASH_AR_TABLE_P(hash)) {
1514 if (RHASH_AR_TABLE_P(ret)) {
1515 ar_copy(ret, hash);
1516 }
1517 else {
1518 st_table *tab = RHASH_ST_TABLE(ret);
1519 st_init_existing_table_with_size(tab, &objhash, RHASH_AR_TABLE_SIZE(hash));
1520
1521 int bound = RHASH_AR_TABLE_BOUND(hash);
1522 for (int i = 0; i < bound; i++) {
1523 if (ar_cleared_entry(hash, i)) continue;
1524
1525 ar_table_pair *pair = RHASH_AR_TABLE_REF(hash, i);
1526 st_add_direct(tab, pair->key, pair->val);
1527 RB_OBJ_WRITTEN(ret, Qundef, pair->key);
1528 RB_OBJ_WRITTEN(ret, Qundef, pair->val);
1529 }
1530 }
1531 }
1532 else {
1533 HASH_ASSERT(sizeof(st_table) <= sizeof(ar_table));
1534
1535 RHASH_SET_ST_FLAG(ret);
1536 st_replace(RHASH_ST_TABLE(ret), RHASH_ST_TABLE(hash));
1537
1538 rb_gc_writebarrier_remember(ret);
1539 }
1540 return ret;
1541}
1542
1543static VALUE
1544hash_dup_with_compare_by_id(VALUE hash)
1545{
1546 VALUE dup = hash_alloc_flags(rb_cHash, 0, Qnil, RHASH_ST_TABLE_P(hash));
1547 if (RHASH_ST_TABLE_P(hash)) {
1548 RHASH_SET_ST_FLAG(dup);
1549 }
1550 else {
1551 RHASH_UNSET_ST_FLAG(dup);
1552 }
1553
1554 return hash_copy(dup, hash);
1555}
1556
1557static VALUE
1558hash_dup(VALUE hash, VALUE klass, VALUE flags)
1559{
1560 return hash_copy(hash_alloc_flags(klass, flags, RHASH_IFNONE(hash), !RHASH_EMPTY_P(hash) && RHASH_ST_TABLE_P(hash)),
1561 hash);
1562}
1563
1564 VALUE
1565rb_hash_dup(VALUE hash)
1566{
1567 const VALUE flags = RBASIC(hash)->flags;
1568 VALUE ret = hash_dup(hash, rb_obj_class(hash),
1569 flags & (FL_EXIVAR|RHASH_PROC_DEFAULT));
1570 if (flags & FL_EXIVAR)
1571 rb_copy_generic_ivar(ret, hash);
1572 return ret;
1573}
1574
1575 VALUE
1576rb_hash_resurrect(VALUE hash)
1577{
1578 VALUE ret = hash_dup(hash, rb_cHash, 0);
1579 return ret;
1580}
1581
1582static void
1583rb_hash_modify_check(VALUE hash)
1584{
1585 rb_check_frozen(hash);
1586}
1587
1588struct st_table *
1589rb_hash_tbl_raw(VALUE hash, const char *file, int line)
1590{
1591 return ar_force_convert_table(hash, file, line);
1592}
1593
1594struct st_table *
1595rb_hash_tbl(VALUE hash, const char *file, int line)
1596{
1597 OBJ_WB_UNPROTECT(hash);
1598 return rb_hash_tbl_raw(hash, file, line);
1599}
1600
1601static void
1602rb_hash_modify(VALUE hash)
1603{
1604 rb_hash_modify_check(hash);
1605}
1606
1607NORETURN(static void no_new_key(void));
1608static void
1609no_new_key(void)
1610{
1611 rb_raise(rb_eRuntimeError, "can't add a new key into hash during iteration");
1612}
1613
1614 struct update_callback_arg {
1615 VALUE hash;
1616 st_data_t arg;
1617};
1618
1619#define NOINSERT_UPDATE_CALLBACK(func) \
1620static int \
1621func##_noinsert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1622{ \
1623 if (!existing) no_new_key(); \
1624 return func(key, val, (struct update_arg *)arg, existing); \
1625} \
1626 \
1627static int \
1628func##_insert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1629{ \
1630 return func(key, val, (struct update_arg *)arg, existing); \
1631}
1632
1633 struct update_arg {
1634 st_data_t arg;
1635 st_update_callback_func *func;
1636 VALUE hash;
1637 VALUE key;
1638 VALUE value;
1639};
1640
1641typedef int (*tbl_update_func)(st_data_t *, st_data_t *, st_data_t, int);
1642
1643int
1644rb_hash_stlike_update(VALUE hash, st_data_t key, st_update_callback_func *func, st_data_t arg)
1645{
1646 if (RHASH_AR_TABLE_P(hash)) {
1647 int result = ar_update(hash, key, func, arg);
1648 if (result == -1) {
1649 ar_force_convert_table(hash, __FILE__, __LINE__);
1650 }
1651 else {
1652 return result;
1653 }
1654 }
1655
1656 return st_update(RHASH_ST_TABLE(hash), key, func, arg);
1657}
1658
1659static int
1660tbl_update_modify(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
1661{
1662 struct update_arg *p = (struct update_arg *)arg;
1663 st_data_t old_key = *key;
1664 st_data_t old_value = *val;
1665 VALUE hash = p->hash;
1666 int ret = (p->func)(key, val, arg, existing);
1667 switch (ret) {
1668 default:
1669 break;
1670 case ST_CONTINUE:
1671 if (!existing || *key != old_key || *val != old_value) {
1672 rb_hash_modify(hash);
1673 p->key = *key;
1674 p->value = *val;
1675 }
1676 break;
1677 case ST_DELETE:
1678 if (existing)
1679 rb_hash_modify(hash);
1680 break;
1681 }
1682
1683 return ret;
1684}
1685
1686static int
1687tbl_update(VALUE hash, VALUE key, tbl_update_func func, st_data_t optional_arg)
1688{
1689 struct update_arg arg = {
1690 .arg = optional_arg,
1691 .func = func,
1692 .hash = hash,
1693 .key = key,
1694 .value = 0
1695 };
1696
1697 int ret = rb_hash_stlike_update(hash, key, tbl_update_modify, (st_data_t)&arg);
1698
1699 /* write barrier */
1700 RB_OBJ_WRITTEN(hash, Qundef, arg.key);
1701 if (arg.value) RB_OBJ_WRITTEN(hash, Qundef, arg.value);
1702
1703 return ret;
1704}
1705
1706#define UPDATE_CALLBACK(iter_p, func) ((iter_p) ? func##_noinsert : func##_insert)
1707
1708#define RHASH_UPDATE_ITER(h, iter_p, key, func, a) do { \
1709 tbl_update((h), (key), UPDATE_CALLBACK(iter_p, func), (st_data_t)(a)); \
1710} while (0)
1711
1712#define RHASH_UPDATE(hash, key, func, arg) \
1713 RHASH_UPDATE_ITER(hash, hash_iterating_p(hash), key, func, arg)
1714
1715static void
1716set_proc_default(VALUE hash, VALUE proc)
1717{
1718 if (rb_proc_lambda_p(proc)) {
1719 int n = rb_proc_arity(proc);
1720
1721 if (n != 2 && (n >= 0 || n < -3)) {
1722 if (n < 0) n = -n-1;
1723 rb_raise(rb_eTypeError, "default_proc takes two arguments (2 for %d)", n);
1724 }
1725 }
1726
1727 FL_SET_RAW(hash, RHASH_PROC_DEFAULT);
1728 RHASH_SET_IFNONE(hash, proc);
1729}
1730
1731static VALUE
1732rb_hash_init(rb_execution_context_t *ec, VALUE hash, VALUE capa_value, VALUE ifnone_unset, VALUE ifnone, VALUE block)
1733{
1734 rb_hash_modify(hash);
1735
1736 if (capa_value != INT2FIX(0)) {
1737 long capa = NUM2LONG(capa_value);
1738 if (capa > 0 && RHASH_SIZE(hash) == 0 && RHASH_AR_TABLE_P(hash)) {
1739 hash_st_table_init(hash, &objhash, capa);
1740 }
1741 }
1742
1743 if (!NIL_P(block)) {
1744 if (ifnone_unset != Qtrue) {
1745 rb_check_arity(1, 0, 0);
1746 }
1747 else {
1748 SET_PROC_DEFAULT(hash, block);
1749 }
1750 }
1751 else {
1752 RHASH_SET_IFNONE(hash, ifnone_unset == Qtrue ? Qnil : ifnone);
1753 }
1754
1755 hash_verify(hash);
1756 return hash;
1757}
1758
1759static VALUE rb_hash_to_a(VALUE hash);
1760
1761/*
1762 * call-seq:
1763 * Hash[] -> new_empty_hash
1764 * Hash[hash] -> new_hash
1765 * Hash[ [*2_element_arrays] ] -> new_hash
1766 * Hash[*objects] -> new_hash
1767 *
1768 * Returns a new +Hash+ object populated with the given objects, if any.
1769 * See Hash::new.
1770 *
1771 * With no argument, returns a new empty +Hash+.
1772 *
1773 * When the single given argument is a +Hash+, returns a new +Hash+
1774 * populated with the entries from the given +Hash+, excluding the
1775 * default value or proc.
1776 *
1777 * h = {foo: 0, bar: 1, baz: 2}
1778 * Hash[h] # => {:foo=>0, :bar=>1, :baz=>2}
1779 *
1780 * When the single given argument is an Array of 2-element Arrays,
1781 * returns a new +Hash+ object wherein each 2-element array forms a
1782 * key-value entry:
1783 *
1784 * Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {:foo=>0, :bar=>1}
1785 *
1786 * When the argument count is an even number;
1787 * returns a new +Hash+ object wherein each successive pair of arguments
1788 * has become a key-value entry:
1789 *
1790 * Hash[:foo, 0, :bar, 1] # => {:foo=>0, :bar=>1}
1791 *
1792 * Raises an exception if the argument list does not conform to any
1793 * of the above.
1794 */
1795
1796static VALUE
1797rb_hash_s_create(int argc, VALUE *argv, VALUE klass)
1798{
1799 VALUE hash, tmp;
1800
1801 if (argc == 1) {
1802 tmp = rb_hash_s_try_convert(Qnil, argv[0]);
1803 if (!NIL_P(tmp)) {
1804 if (!RHASH_EMPTY_P(tmp) && rb_hash_compare_by_id_p(tmp)) {
1805 /* hash_copy for non-empty hash will copy compare_by_identity
1806 flag, but we don't want it copied. Work around by
1807 converting hash to flattened array and using that. */
1808 tmp = rb_hash_to_a(tmp);
1809 }
1810 else {
1811 hash = hash_alloc(klass);
1812 if (!RHASH_EMPTY_P(tmp))
1813 hash_copy(hash, tmp);
1814 return hash;
1815 }
1816 }
1817 else {
1818 tmp = rb_check_array_type(argv[0]);
1819 }
1820
1821 if (!NIL_P(tmp)) {
1822 long i;
1823
1824 hash = hash_alloc(klass);
1825 for (i = 0; i < RARRAY_LEN(tmp); ++i) {
1826 VALUE e = RARRAY_AREF(tmp, i);
1827 VALUE v = rb_check_array_type(e);
1828 VALUE key, val = Qnil;
1829
1830 if (NIL_P(v)) {
1831 rb_raise(rb_eArgError, "wrong element type %s at %ld (expected array)",
1832 rb_builtin_class_name(e), i);
1833 }
1834 switch (RARRAY_LEN(v)) {
1835 default:
1836 rb_raise(rb_eArgError, "invalid number of elements (%ld for 1..2)",
1837 RARRAY_LEN(v));
1838 case 2:
1839 val = RARRAY_AREF(v, 1);
1840 case 1:
1841 key = RARRAY_AREF(v, 0);
1842 rb_hash_aset(hash, key, val);
1843 }
1844 }
1845 return hash;
1846 }
1847 }
1848 if (argc % 2 != 0) {
1849 rb_raise(rb_eArgError, "odd number of arguments for Hash");
1850 }
1851
1852 hash = hash_alloc(klass);
1853 rb_hash_bulk_insert(argc, argv, hash);
1854 hash_verify(hash);
1855 return hash;
1856}
1857
1858 VALUE
1859rb_to_hash_type(VALUE hash)
1860{
1861 return rb_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1862}
1863#define to_hash rb_to_hash_type
1864
1865 VALUE
1866rb_check_hash_type(VALUE hash)
1867{
1868 return rb_check_convert_type_with_id(hash, T_HASH, "Hash", idTo_hash);
1869}
1870
1871/*
1872 * call-seq:
1873 * Hash.try_convert(obj) -> obj, new_hash, or nil
1874 *
1875 * If +obj+ is a +Hash+ object, returns +obj+.
1876 *
1877 * Otherwise if +obj+ responds to <tt>:to_hash</tt>,
1878 * calls <tt>obj.to_hash</tt> and returns the result.
1879 *
1880 * Returns +nil+ if +obj+ does not respond to <tt>:to_hash</tt>
1881 *
1882 * Raises an exception unless <tt>obj.to_hash</tt> returns a +Hash+ object.
1883 */
1884static VALUE
1885rb_hash_s_try_convert(VALUE dummy, VALUE hash)
1886{
1887 return rb_check_hash_type(hash);
1888}
1889
1890/*
1891 * call-seq:
1892 * Hash.ruby2_keywords_hash?(hash) -> true or false
1893 *
1894 * Checks if a given hash is flagged by Module#ruby2_keywords (or
1895 * Proc#ruby2_keywords).
1896 * This method is not for casual use; debugging, researching, and
1897 * some truly necessary cases like serialization of arguments.
1898 *
1899 * ruby2_keywords def foo(*args)
1900 * Hash.ruby2_keywords_hash?(args.last)
1901 * end
1902 * foo(k: 1) #=> true
1903 * foo({k: 1}) #=> false
1904 */
1905static VALUE
1906rb_hash_s_ruby2_keywords_hash_p(VALUE dummy, VALUE hash)
1907{
1908 Check_Type(hash, T_HASH);
1909 return RBOOL(RHASH(hash)->basic.flags & RHASH_PASS_AS_KEYWORDS);
1910}
1911
1912/*
1913 * call-seq:
1914 * Hash.ruby2_keywords_hash(hash) -> hash
1915 *
1916 * Duplicates a given hash and adds a ruby2_keywords flag.
1917 * This method is not for casual use; debugging, researching, and
1918 * some truly necessary cases like deserialization of arguments.
1919 *
1920 * h = {k: 1}
1921 * h = Hash.ruby2_keywords_hash(h)
1922 * def foo(k: 42)
1923 * k
1924 * end
1925 * foo(*[h]) #=> 1 with neither a warning or an error
1926 */
1927static VALUE
1928rb_hash_s_ruby2_keywords_hash(VALUE dummy, VALUE hash)
1929{
1930 Check_Type(hash, T_HASH);
1931 VALUE tmp = rb_hash_dup(hash);
1932 if (RHASH_EMPTY_P(hash) && rb_hash_compare_by_id_p(hash)) {
1933 rb_hash_compare_by_id(tmp);
1934 }
1935 RHASH(tmp)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
1936 return tmp;
1937}
1938
1939 struct rehash_arg {
1940 VALUE hash;
1941 st_table *tbl;
1942};
1943
1944static int
1945rb_hash_rehash_i(VALUE key, VALUE value, VALUE arg)
1946{
1947 if (RHASH_AR_TABLE_P(arg)) {
1948 ar_insert(arg, (st_data_t)key, (st_data_t)value);
1949 }
1950 else {
1951 st_insert(RHASH_ST_TABLE(arg), (st_data_t)key, (st_data_t)value);
1952 }
1953 return ST_CONTINUE;
1954}
1955
1956/*
1957 * call-seq:
1958 * hash.rehash -> self
1959 *
1960 * Rebuilds the hash table by recomputing the hash index for each key;
1961 * returns <tt>self</tt>.
1962 *
1963 * The hash table becomes invalid if the hash value of a key
1964 * has changed after the entry was created.
1965 * See {Modifying an Active Hash Key}[rdoc-ref:Hash@Modifying+an+Active+Hash+Key].
1966 */
1967
1968 VALUE
1969rb_hash_rehash(VALUE hash)
1970{
1971 VALUE tmp;
1972 st_table *tbl;
1973
1974 if (hash_iterating_p(hash)) {
1975 rb_raise(rb_eRuntimeError, "rehash during iteration");
1976 }
1977 rb_hash_modify_check(hash);
1978 if (RHASH_AR_TABLE_P(hash)) {
1979 tmp = hash_alloc(0);
1980 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
1981
1982 hash_ar_free_and_clear_table(hash);
1983 ar_copy(hash, tmp);
1984 }
1985 else if (RHASH_ST_TABLE_P(hash)) {
1986 st_table *old_tab = RHASH_ST_TABLE(hash);
1987 tmp = hash_alloc(0);
1988
1989 hash_st_table_init(tmp, old_tab->type, old_tab->num_entries);
1990 tbl = RHASH_ST_TABLE(tmp);
1991
1992 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
1993
1994 hash_st_free(hash);
1995 RHASH_ST_TABLE_SET(hash, tbl);
1996 RHASH_ST_CLEAR(tmp);
1997 }
1998 hash_verify(hash);
1999 return hash;
2000}
2001
2002static VALUE
2003call_default_proc(VALUE proc, VALUE hash, VALUE key)
2004{
2005 VALUE args[2] = {hash, key};
2006 return rb_proc_call_with_block(proc, 2, args, Qnil);
2007}
2008
2009static bool
2010rb_hash_default_unredefined(VALUE hash)
2011{
2012 VALUE klass = RBASIC_CLASS(hash);
2013 if (LIKELY(klass == rb_cHash)) {
2014 return !!BASIC_OP_UNREDEFINED_P(BOP_DEFAULT, HASH_REDEFINED_OP_FLAG);
2015 }
2016 else {
2017 return LIKELY(rb_method_basic_definition_p(klass, id_default));
2018 }
2019}
2020
2021 VALUE
2022rb_hash_default_value(VALUE hash, VALUE key)
2023{
2024 RUBY_ASSERT(RB_TYPE_P(hash, T_HASH));
2025
2026 if (LIKELY(rb_hash_default_unredefined(hash))) {
2027 VALUE ifnone = RHASH_IFNONE(hash);
2028 if (LIKELY(!FL_TEST_RAW(hash, RHASH_PROC_DEFAULT))) return ifnone;
2029 if (UNDEF_P(key)) return Qnil;
2030 return call_default_proc(ifnone, hash, key);
2031 }
2032 else {
2033 return rb_funcall(hash, id_default, 1, key);
2034 }
2035}
2036
2037static inline int
2038hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2039{
2040 hash_verify(hash);
2041
2042 if (RHASH_AR_TABLE_P(hash)) {
2043 return ar_lookup(hash, key, pval);
2044 }
2045 else {
2046 extern st_index_t rb_iseq_cdhash_hash(VALUE);
2047 RUBY_ASSERT(RHASH_ST_TABLE(hash)->type->hash == rb_any_hash ||
2048 RHASH_ST_TABLE(hash)->type->hash == rb_ident_hash ||
2049 RHASH_ST_TABLE(hash)->type->hash == rb_iseq_cdhash_hash);
2050 return st_lookup(RHASH_ST_TABLE(hash), key, pval);
2051 }
2052}
2053
2054int
2055rb_hash_stlike_lookup(VALUE hash, st_data_t key, st_data_t *pval)
2056{
2057 return hash_stlike_lookup(hash, key, pval);
2058}
2059
2060/*
2061 * call-seq:
2062 * hash[key] -> value
2063 *
2064 * Returns the value associated with the given +key+, if found:
2065 * h = {foo: 0, bar: 1, baz: 2}
2066 * h[:foo] # => 0
2067 *
2068 * If +key+ is not found, returns a default value
2069 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2070 * h = {foo: 0, bar: 1, baz: 2}
2071 * h[:nosuch] # => nil
2072 */
2073
2074 VALUE
2075rb_hash_aref(VALUE hash, VALUE key)
2076{
2077 st_data_t val;
2078
2079 if (hash_stlike_lookup(hash, key, &val)) {
2080 return (VALUE)val;
2081 }
2082 else {
2083 return rb_hash_default_value(hash, key);
2084 }
2085}
2086
2087 VALUE
2088rb_hash_lookup2(VALUE hash, VALUE key, VALUE def)
2089{
2090 st_data_t val;
2091
2092 if (hash_stlike_lookup(hash, key, &val)) {
2093 return (VALUE)val;
2094 }
2095 else {
2096 return def; /* without Hash#default */
2097 }
2098}
2099
2100 VALUE
2101rb_hash_lookup(VALUE hash, VALUE key)
2102{
2103 return rb_hash_lookup2(hash, key, Qnil);
2104}
2105
2106/*
2107 * call-seq:
2108 * hash.fetch(key) -> object
2109 * hash.fetch(key, default_value) -> object
2110 * hash.fetch(key) {|key| ... } -> object
2111 *
2112 * Returns the value for the given +key+, if found.
2113 * h = {foo: 0, bar: 1, baz: 2}
2114 * h.fetch(:bar) # => 1
2115 *
2116 * If +key+ is not found and no block was given,
2117 * returns +default_value+:
2118 * {}.fetch(:nosuch, :default) # => :default
2119 *
2120 * If +key+ is not found and a block was given,
2121 * yields +key+ to the block and returns the block's return value:
2122 * {}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
2123 *
2124 * Raises KeyError if neither +default_value+ nor a block was given.
2125 *
2126 * Note that this method does not use the values of either #default or #default_proc.
2127 */
2128
2129static VALUE
2130rb_hash_fetch_m(int argc, VALUE *argv, VALUE hash)
2131{
2132 VALUE key;
2133 st_data_t val;
2134 long block_given;
2135
2136 rb_check_arity(argc, 1, 2);
2137 key = argv[0];
2138
2139 block_given = rb_block_given_p();
2140 if (block_given && argc == 2) {
2141 rb_warn("block supersedes default value argument");
2142 }
2143
2144 if (hash_stlike_lookup(hash, key, &val)) {
2145 return (VALUE)val;
2146 }
2147 else {
2148 if (block_given) {
2149 return rb_yield(key);
2150 }
2151 else if (argc == 1) {
2152 VALUE desc = rb_protect(rb_inspect, key, 0);
2153 if (NIL_P(desc)) {
2154 desc = rb_any_to_s(key);
2155 }
2156 desc = rb_str_ellipsize(desc, 65);
2157 rb_key_err_raise(rb_sprintf("key not found: %"PRIsVALUE, desc), hash, key);
2158 }
2159 else {
2160 return argv[1];
2161 }
2162 }
2163}
2164
2165 VALUE
2166rb_hash_fetch(VALUE hash, VALUE key)
2167{
2168 return rb_hash_fetch_m(1, &key, hash);
2169}
2170
2171/*
2172 * call-seq:
2173 * hash.default -> object
2174 * hash.default(key) -> object
2175 *
2176 * Returns the default value for the given +key+.
2177 * The returned value will be determined either by the default proc or by the default value.
2178 * See {Default Values}[rdoc-ref:Hash@Default+Values].
2179 *
2180 * With no argument, returns the current default value:
2181 * h = {}
2182 * h.default # => nil
2183 *
2184 * If +key+ is given, returns the default value for +key+,
2185 * regardless of whether that key exists:
2186 * h = Hash.new { |hash, key| hash[key] = "No key #{key}"}
2187 * h[:foo] = "Hello"
2188 * h.default(:foo) # => "No key foo"
2189 */
2190
2191static VALUE
2192rb_hash_default(int argc, VALUE *argv, VALUE hash)
2193{
2194 VALUE ifnone;
2195
2196 rb_check_arity(argc, 0, 1);
2197 ifnone = RHASH_IFNONE(hash);
2198 if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2199 if (argc == 0) return Qnil;
2200 return call_default_proc(ifnone, hash, argv[0]);
2201 }
2202 return ifnone;
2203}
2204
2205/*
2206 * call-seq:
2207 * hash.default = value -> object
2208 *
2209 * Sets the default value to +value+; returns +value+:
2210 * h = {}
2211 * h.default # => nil
2212 * h.default = false # => false
2213 * h.default # => false
2214 *
2215 * See {Default Values}[rdoc-ref:Hash@Default+Values].
2216 */
2217
2218static VALUE
2219rb_hash_set_default(VALUE hash, VALUE ifnone)
2220{
2221 rb_hash_modify_check(hash);
2222 SET_DEFAULT(hash, ifnone);
2223 return ifnone;
2224}
2225
2226/*
2227 * call-seq:
2228 * hash.default_proc -> proc or nil
2229 *
2230 * Returns the default proc for +self+
2231 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2232 * h = {}
2233 * h.default_proc # => nil
2234 * h.default_proc = proc {|hash, key| "Default value for #{key}" }
2235 * h.default_proc.class # => Proc
2236 */
2237
2238static VALUE
2239rb_hash_default_proc(VALUE hash)
2240{
2241 if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
2242 return RHASH_IFNONE(hash);
2243 }
2244 return Qnil;
2245}
2246
2247/*
2248 * call-seq:
2249 * hash.default_proc = proc -> proc
2250 *
2251 * Sets the default proc for +self+ to +proc+
2252 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2253 * h = {}
2254 * h.default_proc # => nil
2255 * h.default_proc = proc { |hash, key| "Default value for #{key}" }
2256 * h.default_proc.class # => Proc
2257 * h.default_proc = nil
2258 * h.default_proc # => nil
2259 */
2260
2261 VALUE
2262rb_hash_set_default_proc(VALUE hash, VALUE proc)
2263{
2264 VALUE b;
2265
2266 rb_hash_modify_check(hash);
2267 if (NIL_P(proc)) {
2268 SET_DEFAULT(hash, proc);
2269 return proc;
2270 }
2271 b = rb_check_convert_type_with_id(proc, T_DATA, "Proc", idTo_proc);
2272 if (NIL_P(b) || !rb_obj_is_proc(b)) {
2273 rb_raise(rb_eTypeError,
2274 "wrong default_proc type %s (expected Proc)",
2275 rb_obj_classname(proc));
2276 }
2277 proc = b;
2278 SET_PROC_DEFAULT(hash, proc);
2279 return proc;
2280}
2281
2282static int
2283key_i(VALUE key, VALUE value, VALUE arg)
2284{
2285 VALUE *args = (VALUE *)arg;
2286
2287 if (rb_equal(value, args[0])) {
2288 args[1] = key;
2289 return ST_STOP;
2290 }
2291 return ST_CONTINUE;
2292}
2293
2294/*
2295 * call-seq:
2296 * hash.key(value) -> key or nil
2297 *
2298 * Returns the key for the first-found entry with the given +value+
2299 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2300 * h = {foo: 0, bar: 2, baz: 2}
2301 * h.key(0) # => :foo
2302 * h.key(2) # => :bar
2303 *
2304 * Returns +nil+ if no such value is found.
2305 */
2306
2307static VALUE
2308rb_hash_key(VALUE hash, VALUE value)
2309{
2310 VALUE args[2];
2311
2312 args[0] = value;
2313 args[1] = Qnil;
2314
2315 rb_hash_foreach(hash, key_i, (VALUE)args);
2316
2317 return args[1];
2318}
2319
2320int
2321rb_hash_stlike_delete(VALUE hash, st_data_t *pkey, st_data_t *pval)
2322{
2323 if (RHASH_AR_TABLE_P(hash)) {
2324 return ar_delete(hash, pkey, pval);
2325 }
2326 else {
2327 return st_delete(RHASH_ST_TABLE(hash), pkey, pval);
2328 }
2329}
2330
2331/*
2332 * delete a specified entry by a given key.
2333 * if there is the corresponding entry, return a value of the entry.
2334 * if there is no corresponding entry, return Qundef.
2335 */
2336 VALUE
2337rb_hash_delete_entry(VALUE hash, VALUE key)
2338{
2339 st_data_t ktmp = (st_data_t)key, val;
2340
2341 if (rb_hash_stlike_delete(hash, &ktmp, &val)) {
2342 return (VALUE)val;
2343 }
2344 else {
2345 return Qundef;
2346 }
2347}
2348
2349/*
2350 * delete a specified entry by a given key.
2351 * if there is the corresponding entry, return a value of the entry.
2352 * if there is no corresponding entry, return Qnil.
2353 */
2354 VALUE
2355rb_hash_delete(VALUE hash, VALUE key)
2356{
2357 VALUE deleted_value = rb_hash_delete_entry(hash, key);
2358
2359 if (!UNDEF_P(deleted_value)) { /* likely pass */
2360 return deleted_value;
2361 }
2362 else {
2363 return Qnil;
2364 }
2365}
2366
2367/*
2368 * call-seq:
2369 * hash.delete(key) -> value or nil
2370 * hash.delete(key) {|key| ... } -> object
2371 *
2372 * Deletes the entry for the given +key+ and returns its associated value.
2373 *
2374 * If no block is given and +key+ is found, deletes the entry and returns the associated value:
2375 * h = {foo: 0, bar: 1, baz: 2}
2376 * h.delete(:bar) # => 1
2377 * h # => {:foo=>0, :baz=>2}
2378 *
2379 * If no block given and +key+ is not found, returns +nil+.
2380 *
2381 * If a block is given and +key+ is found, ignores the block,
2382 * deletes the entry, and returns the associated value:
2383 * h = {foo: 0, bar: 1, baz: 2}
2384 * h.delete(:baz) { |key| raise 'Will never happen'} # => 2
2385 * h # => {:foo=>0, :bar=>1}
2386 *
2387 * If a block is given and +key+ is not found,
2388 * calls the block and returns the block's return value:
2389 * h = {foo: 0, bar: 1, baz: 2}
2390 * h.delete(:nosuch) { |key| "Key #{key} not found" } # => "Key nosuch not found"
2391 * h # => {:foo=>0, :bar=>1, :baz=>2}
2392 */
2393
2394static VALUE
2395rb_hash_delete_m(VALUE hash, VALUE key)
2396{
2397 VALUE val;
2398
2399 rb_hash_modify_check(hash);
2400 val = rb_hash_delete_entry(hash, key);
2401
2402 if (!UNDEF_P(val)) {
2403 compact_after_delete(hash);
2404 return val;
2405 }
2406 else {
2407 if (rb_block_given_p()) {
2408 return rb_yield(key);
2409 }
2410 else {
2411 return Qnil;
2412 }
2413 }
2414}
2415
2416 struct shift_var {
2417 VALUE key;
2418 VALUE val;
2419};
2420
2421static int
2422shift_i_safe(VALUE key, VALUE value, VALUE arg)
2423{
2424 struct shift_var *var = (struct shift_var *)arg;
2425
2426 var->key = key;
2427 var->val = value;
2428 return ST_STOP;
2429}
2430
2431/*
2432 * call-seq:
2433 * hash.shift -> [key, value] or nil
2434 *
2435 * Removes the first hash entry
2436 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]);
2437 * returns a 2-element Array containing the removed key and value:
2438 * h = {foo: 0, bar: 1, baz: 2}
2439 * h.shift # => [:foo, 0]
2440 * h # => {:bar=>1, :baz=>2}
2441 *
2442 * Returns nil if the hash is empty.
2443 */
2444
2445static VALUE
2446rb_hash_shift(VALUE hash)
2447{
2448 struct shift_var var;
2449
2450 rb_hash_modify_check(hash);
2451 if (RHASH_AR_TABLE_P(hash)) {
2452 var.key = Qundef;
2453 if (!hash_iterating_p(hash)) {
2454 if (ar_shift(hash, &var.key, &var.val)) {
2455 return rb_assoc_new(var.key, var.val);
2456 }
2457 }
2458 else {
2459 rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2460 if (!UNDEF_P(var.key)) {
2461 rb_hash_delete_entry(hash, var.key);
2462 return rb_assoc_new(var.key, var.val);
2463 }
2464 }
2465 }
2466 if (RHASH_ST_TABLE_P(hash)) {
2467 var.key = Qundef;
2468 if (!hash_iterating_p(hash)) {
2469 if (st_shift(RHASH_ST_TABLE(hash), &var.key, &var.val)) {
2470 return rb_assoc_new(var.key, var.val);
2471 }
2472 }
2473 else {
2474 rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
2475 if (!UNDEF_P(var.key)) {
2476 rb_hash_delete_entry(hash, var.key);
2477 return rb_assoc_new(var.key, var.val);
2478 }
2479 }
2480 }
2481 return Qnil;
2482}
2483
2484static int
2485delete_if_i(VALUE key, VALUE value, VALUE hash)
2486{
2487 if (RTEST(rb_yield_values(2, key, value))) {
2488 rb_hash_modify(hash);
2489 return ST_DELETE;
2490 }
2491 return ST_CONTINUE;
2492}
2493
2494static VALUE
2495hash_enum_size(VALUE hash, VALUE args, VALUE eobj)
2496{
2497 return rb_hash_size(hash);
2498}
2499
2500/*
2501 * call-seq:
2502 * hash.delete_if {|key, value| ... } -> self
2503 * hash.delete_if -> new_enumerator
2504 *
2505 * If a block given, calls the block with each key-value pair;
2506 * deletes each entry for which the block returns a truthy value;
2507 * returns +self+:
2508 * h = {foo: 0, bar: 1, baz: 2}
2509 * h.delete_if {|key, value| value > 0 } # => {:foo=>0}
2510 *
2511 * If no block given, returns a new Enumerator:
2512 * h = {foo: 0, bar: 1, baz: 2}
2513 * e = h.delete_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:delete_if>
2514 * e.each { |key, value| value > 0 } # => {:foo=>0}
2515 */
2516
2517 VALUE
2518rb_hash_delete_if(VALUE hash)
2519{
2520 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2521 rb_hash_modify_check(hash);
2522 if (!RHASH_TABLE_EMPTY_P(hash)) {
2523 rb_hash_foreach(hash, delete_if_i, hash);
2524 compact_after_delete(hash);
2525 }
2526 return hash;
2527}
2528
2529/*
2530 * call-seq:
2531 * hash.reject! {|key, value| ... } -> self or nil
2532 * hash.reject! -> new_enumerator
2533 *
2534 * Returns +self+, whose remaining entries are those
2535 * for which the block returns +false+ or +nil+:
2536 * h = {foo: 0, bar: 1, baz: 2}
2537 * h.reject! {|key, value| value < 2 } # => {:baz=>2}
2538 *
2539 * Returns +nil+ if no entries are removed.
2540 *
2541 * Returns a new Enumerator if no block given:
2542 * h = {foo: 0, bar: 1, baz: 2}
2543 * e = h.reject! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject!>
2544 * e.each {|key, value| key.start_with?('b') } # => {:foo=>0}
2545 */
2546
2547static VALUE
2548rb_hash_reject_bang(VALUE hash)
2549{
2550 st_index_t n;
2551
2552 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2553 rb_hash_modify(hash);
2554 n = RHASH_SIZE(hash);
2555 if (!n) return Qnil;
2556 rb_hash_foreach(hash, delete_if_i, hash);
2557 if (n == RHASH_SIZE(hash)) return Qnil;
2558 return hash;
2559}
2560
2561/*
2562 * call-seq:
2563 * hash.reject {|key, value| ... } -> new_hash
2564 * hash.reject -> new_enumerator
2565 *
2566 * Returns a new +Hash+ object whose entries are all those
2567 * from +self+ for which the block returns +false+ or +nil+:
2568 * h = {foo: 0, bar: 1, baz: 2}
2569 * h1 = h.reject {|key, value| key.start_with?('b') }
2570 * h1 # => {:foo=>0}
2571 *
2572 * Returns a new Enumerator if no block given:
2573 * h = {foo: 0, bar: 1, baz: 2}
2574 * e = h.reject # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject>
2575 * h1 = e.each {|key, value| key.start_with?('b') }
2576 * h1 # => {:foo=>0}
2577 */
2578
2579static VALUE
2580rb_hash_reject(VALUE hash)
2581{
2582 VALUE result;
2583
2584 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2585 result = hash_dup_with_compare_by_id(hash);
2586 if (!RHASH_EMPTY_P(hash)) {
2587 rb_hash_foreach(result, delete_if_i, result);
2588 compact_after_delete(result);
2589 }
2590 return result;
2591}
2592
2593/*
2594 * call-seq:
2595 * hash.slice(*keys) -> new_hash
2596 *
2597 * Returns a new +Hash+ object containing the entries for the given +keys+:
2598 * h = {foo: 0, bar: 1, baz: 2}
2599 * h.slice(:baz, :foo) # => {:baz=>2, :foo=>0}
2600 *
2601 * Any given +keys+ that are not found are ignored.
2602 */
2603
2604static VALUE
2605rb_hash_slice(int argc, VALUE *argv, VALUE hash)
2606{
2607 int i;
2608 VALUE key, value, result;
2609
2610 if (argc == 0 || RHASH_EMPTY_P(hash)) {
2611 return copy_compare_by_id(rb_hash_new(), hash);
2612 }
2613 result = copy_compare_by_id(rb_hash_new_with_size(argc), hash);
2614
2615 for (i = 0; i < argc; i++) {
2616 key = argv[i];
2617 value = rb_hash_lookup2(hash, key, Qundef);
2618 if (!UNDEF_P(value))
2619 rb_hash_aset(result, key, value);
2620 }
2621
2622 return result;
2623}
2624
2625/*
2626 * call-seq:
2627 * hsh.except(*keys) -> a_hash
2628 *
2629 * Returns a new +Hash+ excluding entries for the given +keys+:
2630 * h = { a: 100, b: 200, c: 300 }
2631 * h.except(:a) #=> {:b=>200, :c=>300}
2632 *
2633 * Any given +keys+ that are not found are ignored.
2634 */
2635
2636static VALUE
2637rb_hash_except(int argc, VALUE *argv, VALUE hash)
2638{
2639 int i;
2640 VALUE key, result;
2641
2642 result = hash_dup_with_compare_by_id(hash);
2643
2644 for (i = 0; i < argc; i++) {
2645 key = argv[i];
2646 rb_hash_delete(result, key);
2647 }
2648 compact_after_delete(result);
2649
2650 return result;
2651}
2652
2653/*
2654 * call-seq:
2655 * hash.values_at(*keys) -> new_array
2656 *
2657 * Returns a new Array containing values for the given +keys+:
2658 * h = {foo: 0, bar: 1, baz: 2}
2659 * h.values_at(:baz, :foo) # => [2, 0]
2660 *
2661 * The {default values}[rdoc-ref:Hash@Default+Values] are returned
2662 * for any keys that are not found:
2663 * h.values_at(:hello, :foo) # => [nil, 0]
2664 */
2665
2666static VALUE
2667rb_hash_values_at(int argc, VALUE *argv, VALUE hash)
2668{
2669 VALUE result = rb_ary_new2(argc);
2670 long i;
2671
2672 for (i=0; i<argc; i++) {
2673 rb_ary_push(result, rb_hash_aref(hash, argv[i]));
2674 }
2675 return result;
2676}
2677
2678/*
2679 * call-seq:
2680 * hash.fetch_values(*keys) -> new_array
2681 * hash.fetch_values(*keys) {|key| ... } -> new_array
2682 *
2683 * Returns a new Array containing the values associated with the given keys *keys:
2684 * h = {foo: 0, bar: 1, baz: 2}
2685 * h.fetch_values(:baz, :foo) # => [2, 0]
2686 *
2687 * Returns a new empty Array if no arguments given.
2688 *
2689 * When a block is given, calls the block with each missing key,
2690 * treating the block's return value as the value for that key:
2691 * h = {foo: 0, bar: 1, baz: 2}
2692 * values = h.fetch_values(:bar, :foo, :bad, :bam) {|key| key.to_s}
2693 * values # => [1, 0, "bad", "bam"]
2694 *
2695 * When no block is given, raises an exception if any given key is not found.
2696 */
2697
2698static VALUE
2699rb_hash_fetch_values(int argc, VALUE *argv, VALUE hash)
2700{
2701 VALUE result = rb_ary_new2(argc);
2702 long i;
2703
2704 for (i=0; i<argc; i++) {
2705 rb_ary_push(result, rb_hash_fetch(hash, argv[i]));
2706 }
2707 return result;
2708}
2709
2710static int
2711keep_if_i(VALUE key, VALUE value, VALUE hash)
2712{
2713 if (!RTEST(rb_yield_values(2, key, value))) {
2714 rb_hash_modify(hash);
2715 return ST_DELETE;
2716 }
2717 return ST_CONTINUE;
2718}
2719
2720/*
2721 * call-seq:
2722 * hash.select {|key, value| ... } -> new_hash
2723 * hash.select -> new_enumerator
2724 *
2725 * Returns a new +Hash+ object whose entries are those for which the block returns a truthy value:
2726 * h = {foo: 0, bar: 1, baz: 2}
2727 * h.select {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2728 *
2729 * Returns a new Enumerator if no block given:
2730 * h = {foo: 0, bar: 1, baz: 2}
2731 * e = h.select # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select>
2732 * e.each {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2733 */
2734
2735static VALUE
2736rb_hash_select(VALUE hash)
2737{
2738 VALUE result;
2739
2740 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2741 result = hash_dup_with_compare_by_id(hash);
2742 if (!RHASH_EMPTY_P(hash)) {
2743 rb_hash_foreach(result, keep_if_i, result);
2744 compact_after_delete(result);
2745 }
2746 return result;
2747}
2748
2749/*
2750 * call-seq:
2751 * hash.select! {|key, value| ... } -> self or nil
2752 * hash.select! -> new_enumerator
2753 *
2754 * Returns +self+, whose entries are those for which the block returns a truthy value:
2755 * h = {foo: 0, bar: 1, baz: 2}
2756 * h.select! {|key, value| value < 2 } => {:foo=>0, :bar=>1}
2757 *
2758 * Returns +nil+ if no entries were removed.
2759 *
2760 * Returns a new Enumerator if no block given:
2761 * h = {foo: 0, bar: 1, baz: 2}
2762 * e = h.select! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select!>
2763 * e.each { |key, value| value < 2 } # => {:foo=>0, :bar=>1}
2764 */
2765
2766static VALUE
2767rb_hash_select_bang(VALUE hash)
2768{
2769 st_index_t n;
2770
2771 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2772 rb_hash_modify_check(hash);
2773 n = RHASH_SIZE(hash);
2774 if (!n) return Qnil;
2775 rb_hash_foreach(hash, keep_if_i, hash);
2776 if (n == RHASH_SIZE(hash)) return Qnil;
2777 return hash;
2778}
2779
2780/*
2781 * call-seq:
2782 * hash.keep_if {|key, value| ... } -> self
2783 * hash.keep_if -> new_enumerator
2784 *
2785 * Calls the block for each key-value pair;
2786 * retains the entry if the block returns a truthy value;
2787 * otherwise deletes the entry; returns +self+.
2788 * h = {foo: 0, bar: 1, baz: 2}
2789 * h.keep_if { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2790 *
2791 * Returns a new Enumerator if no block given:
2792 * h = {foo: 0, bar: 1, baz: 2}
2793 * e = h.keep_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:keep_if>
2794 * e.each { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2795 */
2796
2797static VALUE
2798rb_hash_keep_if(VALUE hash)
2799{
2800 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
2801 rb_hash_modify_check(hash);
2802 if (!RHASH_TABLE_EMPTY_P(hash)) {
2803 rb_hash_foreach(hash, keep_if_i, hash);
2804 }
2805 return hash;
2806}
2807
2808static int
2809clear_i(VALUE key, VALUE value, VALUE dummy)
2810{
2811 return ST_DELETE;
2812}
2813
2814/*
2815 * call-seq:
2816 * hash.clear -> self
2817 *
2818 * Removes all hash entries; returns +self+.
2819 */
2820
2821 VALUE
2822rb_hash_clear(VALUE hash)
2823{
2824 rb_hash_modify_check(hash);
2825
2826 if (hash_iterating_p(hash)) {
2827 rb_hash_foreach(hash, clear_i, 0);
2828 }
2829 else if (RHASH_AR_TABLE_P(hash)) {
2830 ar_clear(hash);
2831 }
2832 else {
2833 st_clear(RHASH_ST_TABLE(hash));
2834 compact_after_delete(hash);
2835 }
2836
2837 return hash;
2838}
2839
2840static int
2841hash_aset(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2842{
2843 *val = arg->arg;
2844 return ST_CONTINUE;
2845}
2846
2847 VALUE
2848rb_hash_key_str(VALUE key)
2849{
2850 if (!RB_FL_ANY_RAW(key, FL_EXIVAR) && RBASIC_CLASS(key) == rb_cString) {
2851 return rb_fstring(key);
2852 }
2853 else {
2854 return rb_str_new_frozen(key);
2855 }
2856}
2857
2858static int
2859hash_aset_str(st_data_t *key, st_data_t *val, struct update_arg *arg, int existing)
2860{
2861 if (!existing && !RB_OBJ_FROZEN(*key)) {
2862 *key = rb_hash_key_str(*key);
2863 }
2864 return hash_aset(key, val, arg, existing);
2865}
2866
2867NOINSERT_UPDATE_CALLBACK(hash_aset)
2868NOINSERT_UPDATE_CALLBACK(hash_aset_str)
2869
2870/*
2871 * call-seq:
2872 * hash[key] = value -> value
2873 * hash.store(key, value)
2874 *
2875 * Associates the given +value+ with the given +key+; returns +value+.
2876 *
2877 * If the given +key+ exists, replaces its value with the given +value+;
2878 * the ordering is not affected
2879 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2880 * h = {foo: 0, bar: 1}
2881 * h[:foo] = 2 # => 2
2882 * h.store(:bar, 3) # => 3
2883 * h # => {:foo=>2, :bar=>3}
2884 *
2885 * If +key+ does not exist, adds the +key+ and +value+;
2886 * the new entry is last in the order
2887 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2888 * h = {foo: 0, bar: 1}
2889 * h[:baz] = 2 # => 2
2890 * h.store(:bat, 3) # => 3
2891 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
2892 */
2893
2894 VALUE
2895rb_hash_aset(VALUE hash, VALUE key, VALUE val)
2896{
2897 bool iter_p = hash_iterating_p(hash);
2898
2899 rb_hash_modify(hash);
2900
2901 if (!RHASH_STRING_KEY_P(hash, key)) {
2902 RHASH_UPDATE_ITER(hash, iter_p, key, hash_aset, val);
2903 }
2904 else {
2905 RHASH_UPDATE_ITER(hash, iter_p, key, hash_aset_str, val);
2906 }
2907 return val;
2908}
2909
2910/*
2911 * call-seq:
2912 * hash.replace(other_hash) -> self
2913 *
2914 * Replaces the entire contents of +self+ with the contents of +other_hash+;
2915 * returns +self+:
2916 * h = {foo: 0, bar: 1, baz: 2}
2917 * h.replace({bat: 3, bam: 4}) # => {:bat=>3, :bam=>4}
2918 */
2919
2920static VALUE
2921rb_hash_replace(VALUE hash, VALUE hash2)
2922{
2923 rb_hash_modify_check(hash);
2924 if (hash == hash2) return hash;
2925 if (hash_iterating_p(hash)) {
2926 rb_raise(rb_eRuntimeError, "can't replace hash during iteration");
2927 }
2928 hash2 = to_hash(hash2);
2929
2930 COPY_DEFAULT(hash, hash2);
2931
2932 if (RHASH_AR_TABLE_P(hash)) {
2933 hash_ar_free_and_clear_table(hash);
2934 }
2935 else {
2936 hash_st_free_and_clear_table(hash);
2937 }
2938
2939 hash_copy(hash, hash2);
2940
2941 return hash;
2942}
2943
2944/*
2945 * call-seq:
2946 * hash.length -> integer
2947 * hash.size -> integer
2948 *
2949 * Returns the count of entries in +self+:
2950 *
2951 * {foo: 0, bar: 1, baz: 2}.length # => 3
2952 *
2953 */
2954
2955 VALUE
2956rb_hash_size(VALUE hash)
2957{
2958 return INT2FIX(RHASH_SIZE(hash));
2959}
2960
2961size_t
2962rb_hash_size_num(VALUE hash)
2963{
2964 return (long)RHASH_SIZE(hash);
2965}
2966
2967/*
2968 * call-seq:
2969 * hash.empty? -> true or false
2970 *
2971 * Returns +true+ if there are no hash entries, +false+ otherwise:
2972 * {}.empty? # => true
2973 * {foo: 0, bar: 1, baz: 2}.empty? # => false
2974 */
2975
2976 VALUE
2977rb_hash_empty_p(VALUE hash)
2978{
2979 return RBOOL(RHASH_EMPTY_P(hash));
2980}
2981
2982static int
2983each_value_i(VALUE key, VALUE value, VALUE _)
2984{
2985 rb_yield(value);
2986 return ST_CONTINUE;
2987}
2988
2989/*
2990 * call-seq:
2991 * hash.each_value {|value| ... } -> self
2992 * hash.each_value -> new_enumerator
2993 *
2994 * Calls the given block with each value; returns +self+:
2995 * h = {foo: 0, bar: 1, baz: 2}
2996 * h.each_value {|value| puts value } # => {:foo=>0, :bar=>1, :baz=>2}
2997 * Output:
2998 * 0
2999 * 1
3000 * 2
3001 *
3002 * Returns a new Enumerator if no block given:
3003 * h = {foo: 0, bar: 1, baz: 2}
3004 * e = h.each_value # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_value>
3005 * h1 = e.each {|value| puts value }
3006 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3007 * Output:
3008 * 0
3009 * 1
3010 * 2
3011 */
3012
3013static VALUE
3014rb_hash_each_value(VALUE hash)
3015{
3016 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3017 rb_hash_foreach(hash, each_value_i, 0);
3018 return hash;
3019}
3020
3021static int
3022each_key_i(VALUE key, VALUE value, VALUE _)
3023{
3024 rb_yield(key);
3025 return ST_CONTINUE;
3026}
3027
3028/*
3029 * call-seq:
3030 * hash.each_key {|key| ... } -> self
3031 * hash.each_key -> new_enumerator
3032 *
3033 * Calls the given block with each key; returns +self+:
3034 * h = {foo: 0, bar: 1, baz: 2}
3035 * h.each_key {|key| puts key } # => {:foo=>0, :bar=>1, :baz=>2}
3036 * Output:
3037 * foo
3038 * bar
3039 * baz
3040 *
3041 * Returns a new Enumerator if no block given:
3042 * h = {foo: 0, bar: 1, baz: 2}
3043 * e = h.each_key # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_key>
3044 * h1 = e.each {|key| puts key }
3045 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3046 * Output:
3047 * foo
3048 * bar
3049 * baz
3050 */
3051static VALUE
3052rb_hash_each_key(VALUE hash)
3053{
3054 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3055 rb_hash_foreach(hash, each_key_i, 0);
3056 return hash;
3057}
3058
3059static int
3060each_pair_i(VALUE key, VALUE value, VALUE _)
3061{
3062 rb_yield(rb_assoc_new(key, value));
3063 return ST_CONTINUE;
3064}
3065
3066static int
3067each_pair_i_fast(VALUE key, VALUE value, VALUE _)
3068{
3069 VALUE argv[2];
3070 argv[0] = key;
3071 argv[1] = value;
3072 rb_yield_values2(2, argv);
3073 return ST_CONTINUE;
3074}
3075
3076/*
3077 * call-seq:
3078 * hash.each {|key, value| ... } -> self
3079 * hash.each_pair {|key, value| ... } -> self
3080 * hash.each -> new_enumerator
3081 * hash.each_pair -> new_enumerator
3082 *
3083 * Calls the given block with each key-value pair; returns +self+:
3084 * h = {foo: 0, bar: 1, baz: 2}
3085 * h.each_pair {|key, value| puts "#{key}: #{value}"} # => {:foo=>0, :bar=>1, :baz=>2}
3086 * Output:
3087 * foo: 0
3088 * bar: 1
3089 * baz: 2
3090 *
3091 * Returns a new Enumerator if no block given:
3092 * h = {foo: 0, bar: 1, baz: 2}
3093 * e = h.each_pair # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_pair>
3094 * h1 = e.each {|key, value| puts "#{key}: #{value}"}
3095 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3096 * Output:
3097 * foo: 0
3098 * bar: 1
3099 * baz: 2
3100 */
3101
3102static VALUE
3103rb_hash_each_pair(VALUE hash)
3104{
3105 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3106 if (rb_block_pair_yield_optimizable())
3107 rb_hash_foreach(hash, each_pair_i_fast, 0);
3108 else
3109 rb_hash_foreach(hash, each_pair_i, 0);
3110 return hash;
3111}
3112
3113 struct transform_keys_args{
3114 VALUE trans;
3115 VALUE result;
3116 int block_given;
3117};
3118
3119static int
3120transform_keys_hash_i(VALUE key, VALUE value, VALUE transarg)
3121{
3122 struct transform_keys_args *p = (void *)transarg;
3123 VALUE trans = p->trans, result = p->result;
3124 VALUE new_key = rb_hash_lookup2(trans, key, Qundef);
3125 if (UNDEF_P(new_key)) {
3126 if (p->block_given)
3127 new_key = rb_yield(key);
3128 else
3129 new_key = key;
3130 }
3131 rb_hash_aset(result, new_key, value);
3132 return ST_CONTINUE;
3133}
3134
3135static int
3136transform_keys_i(VALUE key, VALUE value, VALUE result)
3137{
3138 VALUE new_key = rb_yield(key);
3139 rb_hash_aset(result, new_key, value);
3140 return ST_CONTINUE;
3141}
3142
3143/*
3144 * call-seq:
3145 * hash.transform_keys {|key| ... } -> new_hash
3146 * hash.transform_keys(hash2) -> new_hash
3147 * hash.transform_keys(hash2) {|other_key| ...} -> new_hash
3148 * hash.transform_keys -> new_enumerator
3149 *
3150 * Returns a new +Hash+ object; each entry has:
3151 * * A key provided by the block.
3152 * * The value from +self+.
3153 *
3154 * An optional hash argument can be provided to map keys to new keys.
3155 * Any key not given will be mapped using the provided block,
3156 * or remain the same if no block is given.
3157 *
3158 * Transform keys:
3159 * h = {foo: 0, bar: 1, baz: 2}
3160 * h1 = h.transform_keys {|key| key.to_s }
3161 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3162 *
3163 * h.transform_keys(foo: :bar, bar: :foo)
3164 * #=> {bar: 0, foo: 1, baz: 2}
3165 *
3166 * h.transform_keys(foo: :hello, &:to_s)
3167 * #=> {:hello=>0, "bar"=>1, "baz"=>2}
3168 *
3169 * Overwrites values for duplicate keys:
3170 * h = {foo: 0, bar: 1, baz: 2}
3171 * h1 = h.transform_keys {|key| :bat }
3172 * h1 # => {:bat=>2}
3173 *
3174 * Returns a new Enumerator if no block given:
3175 * h = {foo: 0, bar: 1, baz: 2}
3176 * e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys>
3177 * h1 = e.each { |key| key.to_s }
3178 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3179 */
3180static VALUE
3181rb_hash_transform_keys(int argc, VALUE *argv, VALUE hash)
3182{
3183 VALUE result;
3184 struct transform_keys_args transarg = {0};
3185
3186 argc = rb_check_arity(argc, 0, 1);
3187 if (argc > 0) {
3188 transarg.trans = to_hash(argv[0]);
3189 transarg.block_given = rb_block_given_p();
3190 }
3191 else {
3192 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3193 }
3194 result = rb_hash_new();
3195 if (!RHASH_EMPTY_P(hash)) {
3196 if (transarg.trans) {
3197 transarg.result = result;
3198 rb_hash_foreach(hash, transform_keys_hash_i, (VALUE)&transarg);
3199 }
3200 else {
3201 rb_hash_foreach(hash, transform_keys_i, result);
3202 }
3203 }
3204
3205 return result;
3206}
3207
3208static int flatten_i(VALUE key, VALUE val, VALUE ary);
3209
3210/*
3211 * call-seq:
3212 * hash.transform_keys! {|key| ... } -> self
3213 * hash.transform_keys!(hash2) -> self
3214 * hash.transform_keys!(hash2) {|other_key| ...} -> self
3215 * hash.transform_keys! -> new_enumerator
3216 *
3217 * Same as Hash#transform_keys but modifies the receiver in place
3218 * instead of returning a new hash.
3219 */
3220static VALUE
3221rb_hash_transform_keys_bang(int argc, VALUE *argv, VALUE hash)
3222{
3223 VALUE trans = 0;
3224 int block_given = 0;
3225
3226 argc = rb_check_arity(argc, 0, 1);
3227 if (argc > 0) {
3228 trans = to_hash(argv[0]);
3229 block_given = rb_block_given_p();
3230 }
3231 else {
3232 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3233 }
3234 rb_hash_modify_check(hash);
3235 if (!RHASH_TABLE_EMPTY_P(hash)) {
3236 long i;
3237 VALUE new_keys = hash_alloc(0);
3238 VALUE pairs = rb_ary_hidden_new(RHASH_SIZE(hash) * 2);
3239 rb_hash_foreach(hash, flatten_i, pairs);
3240 for (i = 0; i < RARRAY_LEN(pairs); i += 2) {
3241 VALUE key = RARRAY_AREF(pairs, i), new_key, val;
3242
3243 if (!trans) {
3244 new_key = rb_yield(key);
3245 }
3246 else if (!UNDEF_P(new_key = rb_hash_lookup2(trans, key, Qundef))) {
3247 /* use the transformed key */
3248 }
3249 else if (block_given) {
3250 new_key = rb_yield(key);
3251 }
3252 else {
3253 new_key = key;
3254 }
3255 val = RARRAY_AREF(pairs, i+1);
3256 if (!hash_stlike_lookup(new_keys, key, NULL)) {
3257 rb_hash_stlike_delete(hash, &key, NULL);
3258 }
3259 rb_hash_aset(hash, new_key, val);
3260 rb_hash_aset(new_keys, new_key, Qnil);
3261 }
3262 rb_ary_clear(pairs);
3263 rb_hash_clear(new_keys);
3264 }
3265 compact_after_delete(hash);
3266 return hash;
3267}
3268
3269static int
3270transform_values_foreach_func(st_data_t key, st_data_t value, st_data_t argp, int error)
3271{
3272 return ST_REPLACE;
3273}
3274
3275static int
3276transform_values_foreach_replace(st_data_t *key, st_data_t *value, st_data_t argp, int existing)
3277{
3278 VALUE new_value = rb_yield((VALUE)*value);
3279 VALUE hash = (VALUE)argp;
3280 rb_hash_modify(hash);
3281 RB_OBJ_WRITE(hash, value, new_value);
3282 return ST_CONTINUE;
3283}
3284
3285static VALUE
3286transform_values_call(VALUE hash)
3287{
3288 rb_hash_stlike_foreach_with_replace(hash, transform_values_foreach_func, transform_values_foreach_replace, hash);
3289 return hash;
3290}
3291
3292static void
3293transform_values(VALUE hash)
3294{
3295 hash_iter_lev_inc(hash);
3296 rb_ensure(transform_values_call, hash, hash_foreach_ensure, hash);
3297}
3298
3299/*
3300 * call-seq:
3301 * hash.transform_values {|value| ... } -> new_hash
3302 * hash.transform_values -> new_enumerator
3303 *
3304 * Returns a new +Hash+ object; each entry has:
3305 * * A key from +self+.
3306 * * A value provided by the block.
3307 *
3308 * Transform values:
3309 * h = {foo: 0, bar: 1, baz: 2}
3310 * h1 = h.transform_values {|value| value * 100}
3311 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3312 *
3313 * Returns a new Enumerator if no block given:
3314 * h = {foo: 0, bar: 1, baz: 2}
3315 * e = h.transform_values # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_values>
3316 * h1 = e.each { |value| value * 100}
3317 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3318 */
3319static VALUE
3320rb_hash_transform_values(VALUE hash)
3321{
3322 VALUE result;
3323
3324 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3325 result = hash_dup_with_compare_by_id(hash);
3326 SET_DEFAULT(result, Qnil);
3327
3328 if (!RHASH_EMPTY_P(hash)) {
3329 transform_values(result);
3330 compact_after_delete(result);
3331 }
3332
3333 return result;
3334}
3335
3336/*
3337 * call-seq:
3338 * hash.transform_values! {|value| ... } -> self
3339 * hash.transform_values! -> new_enumerator
3340 *
3341 * Returns +self+, whose keys are unchanged, and whose values are determined by the given block.
3342 * h = {foo: 0, bar: 1, baz: 2}
3343 * h.transform_values! {|value| value * 100} # => {:foo=>0, :bar=>100, :baz=>200}
3344 *
3345 * Returns a new Enumerator if no block given:
3346 * h = {foo: 0, bar: 1, baz: 2}
3347 * e = h.transform_values! # => #<Enumerator: {:foo=>0, :bar=>100, :baz=>200}:transform_values!>
3348 * h1 = e.each {|value| value * 100}
3349 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3350 */
3351static VALUE
3352rb_hash_transform_values_bang(VALUE hash)
3353{
3354 RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
3355 rb_hash_modify_check(hash);
3356
3357 if (!RHASH_TABLE_EMPTY_P(hash)) {
3358 transform_values(hash);
3359 }
3360
3361 return hash;
3362}
3363
3364static int
3365to_a_i(VALUE key, VALUE value, VALUE ary)
3366{
3367 rb_ary_push(ary, rb_assoc_new(key, value));
3368 return ST_CONTINUE;
3369}
3370
3371/*
3372 * call-seq:
3373 * hash.to_a -> new_array
3374 *
3375 * Returns a new Array of 2-element Array objects;
3376 * each nested Array contains a key-value pair from +self+:
3377 * h = {foo: 0, bar: 1, baz: 2}
3378 * h.to_a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3379 */
3380
3381static VALUE
3382rb_hash_to_a(VALUE hash)
3383{
3384 VALUE ary;
3385
3386 ary = rb_ary_new_capa(RHASH_SIZE(hash));
3387 rb_hash_foreach(hash, to_a_i, ary);
3388
3389 return ary;
3390}
3391
3392static bool
3393symbol_key_needs_quote(VALUE str)
3394{
3395 long len = RSTRING_LEN(str);
3396 if (len == 0 || !rb_str_symname_p(str)) return true;
3397 const char *s = RSTRING_PTR(str);
3398 char first = s[0];
3399 if (first == '@' || first == '$' || first == '!') return true;
3400 if (!at_char_boundary(s, s + len - 1, RSTRING_END(str), rb_enc_get(str))) return false;
3401 switch (s[len - 1]) {
3402 case '+':
3403 case '-':
3404 case '*':
3405 case '/':
3406 case '`':
3407 case '%':
3408 case '^':
3409 case '&':
3410 case '|':
3411 case ']':
3412 case '<':
3413 case '=':
3414 case '>':
3415 case '~':
3416 case '@':
3417 return true;
3418 default:
3419 return false;
3420 }
3421}
3422
3423static int
3424inspect_i(VALUE key, VALUE value, VALUE str)
3425{
3426 VALUE str2;
3427
3428 bool is_symbol = SYMBOL_P(key);
3429 bool quote = false;
3430 if (is_symbol) {
3431 str2 = rb_sym2str(key);
3432 quote = symbol_key_needs_quote(str2);
3433 }
3434 else {
3435 str2 = rb_inspect(key);
3436 }
3437 if (RSTRING_LEN(str) > 1) {
3438 rb_str_buf_cat_ascii(str, ", ");
3439 }
3440 else {
3441 rb_enc_copy(str, str2);
3442 }
3443 if (quote) {
3444 rb_str_buf_append(str, rb_str_inspect(str2));
3445 }
3446 else {
3447 rb_str_buf_append(str, str2);
3448 }
3449
3450 rb_str_buf_cat_ascii(str, is_symbol ? ": " : " => ");
3451 str2 = rb_inspect(value);
3452 rb_str_buf_append(str, str2);
3453
3454 return ST_CONTINUE;
3455}
3456
3457static VALUE
3458inspect_hash(VALUE hash, VALUE dummy, int recur)
3459{
3460 VALUE str;
3461
3462 if (recur) return rb_usascii_str_new2("{...}");
3463 str = rb_str_buf_new2("{");
3464 rb_hash_foreach(hash, inspect_i, str);
3465 rb_str_buf_cat2(str, "}");
3466
3467 return str;
3468}
3469
3470/*
3471 * call-seq:
3472 * hash.inspect -> new_string
3473 *
3474 * Returns a new String containing the hash entries:
3475
3476 * h = {foo: 0, bar: 1, baz: 2}
3477 * h.inspect # => "{foo: 0, bar: 1, baz: 2}"
3478 *
3479 */
3480
3481static VALUE
3482rb_hash_inspect(VALUE hash)
3483{
3484 if (RHASH_EMPTY_P(hash))
3485 return rb_usascii_str_new2("{}");
3486 return rb_exec_recursive(inspect_hash, hash, 0);
3487}
3488
3489/*
3490 * call-seq:
3491 * hash.to_hash -> self
3492 *
3493 * Returns +self+.
3494 */
3495static VALUE
3496rb_hash_to_hash(VALUE hash)
3497{
3498 return hash;
3499}
3500
3501 VALUE
3502rb_hash_set_pair(VALUE hash, VALUE arg)
3503{
3504 VALUE pair;
3505
3506 pair = rb_check_array_type(arg);
3507 if (NIL_P(pair)) {
3508 rb_raise(rb_eTypeError, "wrong element type %s (expected array)",
3509 rb_builtin_class_name(arg));
3510 }
3511 if (RARRAY_LEN(pair) != 2) {
3512 rb_raise(rb_eArgError, "element has wrong array length (expected 2, was %ld)",
3513 RARRAY_LEN(pair));
3514 }
3515 rb_hash_aset(hash, RARRAY_AREF(pair, 0), RARRAY_AREF(pair, 1));
3516 return hash;
3517}
3518
3519static int
3520to_h_i(VALUE key, VALUE value, VALUE hash)
3521{
3522 rb_hash_set_pair(hash, rb_yield_values(2, key, value));
3523 return ST_CONTINUE;
3524}
3525
3526static VALUE
3527rb_hash_to_h_block(VALUE hash)
3528{
3529 VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
3530 rb_hash_foreach(hash, to_h_i, h);
3531 return h;
3532}
3533
3534/*
3535 * call-seq:
3536 * hash.to_h -> self or new_hash
3537 * hash.to_h {|key, value| ... } -> new_hash
3538 *
3539 * For an instance of +Hash+, returns +self+.
3540 *
3541 * For a subclass of +Hash+, returns a new +Hash+
3542 * containing the content of +self+.
3543 *
3544 * When a block is given, returns a new +Hash+ object
3545 * whose content is based on the block;
3546 * the block should return a 2-element Array object
3547 * specifying the key-value pair to be included in the returned Array:
3548 * h = {foo: 0, bar: 1, baz: 2}
3549 * h1 = h.to_h {|key, value| [value, key] }
3550 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3551 */
3552
3553static VALUE
3554rb_hash_to_h(VALUE hash)
3555{
3556 if (rb_block_given_p()) {
3557 return rb_hash_to_h_block(hash);
3558 }
3559 if (rb_obj_class(hash) != rb_cHash) {
3560 const VALUE flags = RBASIC(hash)->flags;
3561 hash = hash_dup(hash, rb_cHash, flags & RHASH_PROC_DEFAULT);
3562 }
3563 return hash;
3564}
3565
3566static int
3567keys_i(VALUE key, VALUE value, VALUE ary)
3568{
3569 rb_ary_push(ary, key);
3570 return ST_CONTINUE;
3571}
3572
3573/*
3574 * call-seq:
3575 * hash.keys -> new_array
3576 *
3577 * Returns a new Array containing all keys in +self+:
3578 * h = {foo: 0, bar: 1, baz: 2}
3579 * h.keys # => [:foo, :bar, :baz]
3580 */
3581
3582 VALUE
3583rb_hash_keys(VALUE hash)
3584{
3585 st_index_t size = RHASH_SIZE(hash);
3586 VALUE keys = rb_ary_new_capa(size);
3587
3588 if (size == 0) return keys;
3589
3590 if (ST_DATA_COMPATIBLE_P(VALUE)) {
3591 RARRAY_PTR_USE(keys, ptr, {
3592 if (RHASH_AR_TABLE_P(hash)) {
3593 size = ar_keys(hash, ptr, size);
3594 }
3595 else {
3596 st_table *table = RHASH_ST_TABLE(hash);
3597 size = st_keys(table, ptr, size);
3598 }
3599 });
3600 rb_gc_writebarrier_remember(keys);
3601 rb_ary_set_len(keys, size);
3602 }
3603 else {
3604 rb_hash_foreach(hash, keys_i, keys);
3605 }
3606
3607 return keys;
3608}
3609
3610static int
3611values_i(VALUE key, VALUE value, VALUE ary)
3612{
3613 rb_ary_push(ary, value);
3614 return ST_CONTINUE;
3615}
3616
3617/*
3618 * call-seq:
3619 * hash.values -> new_array
3620 *
3621 * Returns a new Array containing all values in +self+:
3622 * h = {foo: 0, bar: 1, baz: 2}
3623 * h.values # => [0, 1, 2]
3624 */
3625
3626 VALUE
3627rb_hash_values(VALUE hash)
3628{
3629 VALUE values;
3630 st_index_t size = RHASH_SIZE(hash);
3631
3632 values = rb_ary_new_capa(size);
3633 if (size == 0) return values;
3634
3635 if (ST_DATA_COMPATIBLE_P(VALUE)) {
3636 if (RHASH_AR_TABLE_P(hash)) {
3637 rb_gc_writebarrier_remember(values);
3638 RARRAY_PTR_USE(values, ptr, {
3639 size = ar_values(hash, ptr, size);
3640 });
3641 }
3642 else if (RHASH_ST_TABLE_P(hash)) {
3643 st_table *table = RHASH_ST_TABLE(hash);
3644 rb_gc_writebarrier_remember(values);
3645 RARRAY_PTR_USE(values, ptr, {
3646 size = st_values(table, ptr, size);
3647 });
3648 }
3649 rb_ary_set_len(values, size);
3650 }
3651
3652 else {
3653 rb_hash_foreach(hash, values_i, values);
3654 }
3655
3656 return values;
3657}
3658
3659/*
3660 * call-seq:
3661 * hash.include?(key) -> true or false
3662 * hash.has_key?(key) -> true or false
3663 * hash.key?(key) -> true or false
3664 * hash.member?(key) -> true or false
3665 *
3666 * Returns +true+ if +key+ is a key in +self+, otherwise +false+.
3667 */
3668
3669 VALUE
3670rb_hash_has_key(VALUE hash, VALUE key)
3671{
3672 return RBOOL(hash_stlike_lookup(hash, key, NULL));
3673}
3674
3675static int
3676rb_hash_search_value(VALUE key, VALUE value, VALUE arg)
3677{
3678 VALUE *data = (VALUE *)arg;
3679
3680 if (rb_equal(value, data[1])) {
3681 data[0] = Qtrue;
3682 return ST_STOP;
3683 }
3684 return ST_CONTINUE;
3685}
3686
3687/*
3688 * call-seq:
3689 * hash.has_value?(value) -> true or false
3690 * hash.value?(value) -> true or false
3691 *
3692 * Returns +true+ if +value+ is a value in +self+, otherwise +false+.
3693 */
3694
3695static VALUE
3696rb_hash_has_value(VALUE hash, VALUE val)
3697{
3698 VALUE data[2];
3699
3700 data[0] = Qfalse;
3701 data[1] = val;
3702 rb_hash_foreach(hash, rb_hash_search_value, (VALUE)data);
3703 return data[0];
3704}
3705
3706 struct equal_data {
3707 VALUE result;
3708 VALUE hash;
3709 int eql;
3710};
3711
3712static int
3713eql_i(VALUE key, VALUE val1, VALUE arg)
3714{
3715 struct equal_data *data = (struct equal_data *)arg;
3716 st_data_t val2;
3717
3718 if (!hash_stlike_lookup(data->hash, key, &val2)) {
3719 data->result = Qfalse;
3720 return ST_STOP;
3721 }
3722 else {
3723 if (!(data->eql ? rb_eql(val1, (VALUE)val2) : (int)rb_equal(val1, (VALUE)val2))) {
3724 data->result = Qfalse;
3725 return ST_STOP;
3726 }
3727 return ST_CONTINUE;
3728 }
3729}
3730
3731static VALUE
3732recursive_eql(VALUE hash, VALUE dt, int recur)
3733{
3734 struct equal_data *data;
3735
3736 if (recur) return Qtrue; /* Subtle! */
3737 data = (struct equal_data*)dt;
3738 data->result = Qtrue;
3739 rb_hash_foreach(hash, eql_i, dt);
3740
3741 return data->result;
3742}
3743
3744static VALUE
3745hash_equal(VALUE hash1, VALUE hash2, int eql)
3746{
3747 struct equal_data data;
3748
3749 if (hash1 == hash2) return Qtrue;
3750 if (!RB_TYPE_P(hash2, T_HASH)) {
3751 if (!rb_respond_to(hash2, idTo_hash)) {
3752 return Qfalse;
3753 }
3754 if (eql) {
3755 if (rb_eql(hash2, hash1)) {
3756 return Qtrue;
3757 }
3758 else {
3759 return Qfalse;
3760 }
3761 }
3762 else {
3763 return rb_equal(hash2, hash1);
3764 }
3765 }
3766 if (RHASH_SIZE(hash1) != RHASH_SIZE(hash2))
3767 return Qfalse;
3768 if (!RHASH_TABLE_EMPTY_P(hash1) && !RHASH_TABLE_EMPTY_P(hash2)) {
3769 if (RHASH_TYPE(hash1) != RHASH_TYPE(hash2)) {
3770 return Qfalse;
3771 }
3772 else {
3773 data.hash = hash2;
3774 data.eql = eql;
3775 return rb_exec_recursive_paired(recursive_eql, hash1, hash2, (VALUE)&data);
3776 }
3777 }
3778
3779#if 0
3780 if (!(rb_equal(RHASH_IFNONE(hash1), RHASH_IFNONE(hash2)) &&
3781 FL_TEST(hash1, RHASH_PROC_DEFAULT) == FL_TEST(hash2, RHASH_PROC_DEFAULT)))
3782 return Qfalse;
3783#endif
3784 return Qtrue;
3785}
3786
3787/*
3788 * call-seq:
3789 * hash == object -> true or false
3790 *
3791 * Returns +true+ if all of the following are true:
3792 * * +object+ is a +Hash+ object.
3793 * * +hash+ and +object+ have the same keys (regardless of order).
3794 * * For each key +key+, <tt>hash[key] == object[key]</tt>.
3795 *
3796 * Otherwise, returns +false+.
3797 *
3798 * Equal:
3799 * h1 = {foo: 0, bar: 1, baz: 2}
3800 * h2 = {foo: 0, bar: 1, baz: 2}
3801 * h1 == h2 # => true
3802 * h3 = {baz: 2, bar: 1, foo: 0}
3803 * h1 == h3 # => true
3804 */
3805
3806static VALUE
3807rb_hash_equal(VALUE hash1, VALUE hash2)
3808{
3809 return hash_equal(hash1, hash2, FALSE);
3810}
3811
3812/*
3813 * call-seq:
3814 * hash.eql?(object) -> true or false
3815 *
3816 * Returns +true+ if all of the following are true:
3817 * * +object+ is a +Hash+ object.
3818 * * +hash+ and +object+ have the same keys (regardless of order).
3819 * * For each key +key+, <tt>h[key].eql?(object[key])</tt>.
3820 *
3821 * Otherwise, returns +false+.
3822 *
3823 * h1 = {foo: 0, bar: 1, baz: 2}
3824 * h2 = {foo: 0, bar: 1, baz: 2}
3825 * h1.eql? h2 # => true
3826 * h3 = {baz: 2, bar: 1, foo: 0}
3827 * h1.eql? h3 # => true
3828 */
3829
3830static VALUE
3831rb_hash_eql(VALUE hash1, VALUE hash2)
3832{
3833 return hash_equal(hash1, hash2, TRUE);
3834}
3835
3836static int
3837hash_i(VALUE key, VALUE val, VALUE arg)
3838{
3839 st_index_t *hval = (st_index_t *)arg;
3840 st_index_t hdata[2];
3841
3842 hdata[0] = rb_hash(key);
3843 hdata[1] = rb_hash(val);
3844 *hval ^= st_hash(hdata, sizeof(hdata), 0);
3845 return ST_CONTINUE;
3846}
3847
3848/*
3849 * call-seq:
3850 * hash.hash -> an_integer
3851 *
3852 * Returns the Integer hash-code for the hash.
3853 *
3854 * Two +Hash+ objects have the same hash-code if their content is the same
3855 * (regardless of order):
3856 * h1 = {foo: 0, bar: 1, baz: 2}
3857 * h2 = {baz: 2, bar: 1, foo: 0}
3858 * h2.hash == h1.hash # => true
3859 * h2.eql? h1 # => true
3860 */
3861
3862static VALUE
3863rb_hash_hash(VALUE hash)
3864{
3865 st_index_t size = RHASH_SIZE(hash);
3866 st_index_t hval = rb_hash_start(size);
3867 hval = rb_hash_uint(hval, (st_index_t)rb_hash_hash);
3868 if (size) {
3869 rb_hash_foreach(hash, hash_i, (VALUE)&hval);
3870 }
3871 hval = rb_hash_end(hval);
3872 return ST2FIX(hval);
3873}
3874
3875static int
3876rb_hash_invert_i(VALUE key, VALUE value, VALUE hash)
3877{
3878 rb_hash_aset(hash, value, key);
3879 return ST_CONTINUE;
3880}
3881
3882/*
3883 * call-seq:
3884 * hash.invert -> new_hash
3885 *
3886 * Returns a new +Hash+ object with the each key-value pair inverted:
3887 * h = {foo: 0, bar: 1, baz: 2}
3888 * h1 = h.invert
3889 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3890 *
3891 * Overwrites any repeated new keys:
3892 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
3893 * h = {foo: 0, bar: 0, baz: 0}
3894 * h.invert # => {0=>:baz}
3895 */
3896
3897static VALUE
3898rb_hash_invert(VALUE hash)
3899{
3900 VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
3901
3902 rb_hash_foreach(hash, rb_hash_invert_i, h);
3903 return h;
3904}
3905
3906static int
3907rb_hash_update_i(VALUE key, VALUE value, VALUE hash)
3908{
3909 rb_hash_aset(hash, key, value);
3910 return ST_CONTINUE;
3911}
3912
3913 struct update_call_args {
3914 VALUE hash, newvalue, *argv;
3915 int argc;
3916 bool block_given;
3917 bool iterating;
3918};
3919
3920static int
3921rb_hash_update_block_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
3922{
3923 VALUE k = (VALUE)*key, v = (VALUE)*value;
3924 struct update_call_args *ua = (void *)arg->arg;
3925 VALUE newvalue = ua->newvalue, hash = arg->hash;
3926
3927 if (existing) {
3928 hash_iter_lev_inc(hash);
3929 ua->iterating = true;
3930 newvalue = rb_yield_values(3, k, v, newvalue);
3931 hash_iter_lev_dec(hash);
3932 ua->iterating = false;
3933 }
3934 else if (RHASH_STRING_KEY_P(hash, k) && !RB_OBJ_FROZEN(k)) {
3935 *key = (st_data_t)rb_hash_key_str(k);
3936 }
3937 *value = (st_data_t)newvalue;
3938 return ST_CONTINUE;
3939}
3940
3941NOINSERT_UPDATE_CALLBACK(rb_hash_update_block_callback)
3942
3943static int
3944rb_hash_update_block_i(VALUE key, VALUE value, VALUE args)
3945{
3946 struct update_call_args *ua = (void *)args;
3947 ua->newvalue = value;
3948 RHASH_UPDATE(ua->hash, key, rb_hash_update_block_callback, args);
3949 return ST_CONTINUE;
3950}
3951
3952static VALUE
3953rb_hash_update_call(VALUE args)
3954{
3955 struct update_call_args *arg = (void *)args;
3956
3957 for (int i = 0; i < arg->argc; i++){
3958 VALUE hash = to_hash(arg->argv[i]);
3959 if (arg->block_given) {
3960 rb_hash_foreach(hash, rb_hash_update_block_i, args);
3961 }
3962 else {
3963 rb_hash_foreach(hash, rb_hash_update_i, arg->hash);
3964 }
3965 }
3966 return arg->hash;
3967}
3968
3969static VALUE
3970rb_hash_update_ensure(VALUE args)
3971{
3972 struct update_call_args *ua = (void *)args;
3973 if (ua->iterating) hash_iter_lev_dec(ua->hash);
3974 return Qnil;
3975}
3976
3977/*
3978 * call-seq:
3979 * hash.merge! -> self
3980 * hash.merge!(*other_hashes) -> self
3981 * hash.merge!(*other_hashes) { |key, old_value, new_value| ... } -> self
3982 *
3983 * Merges each of +other_hashes+ into +self+; returns +self+.
3984 *
3985 * Each argument in +other_hashes+ must be a +Hash+.
3986 *
3987 * With arguments and no block:
3988 * * Returns +self+, after the given hashes are merged into it.
3989 * * The given hashes are merged left to right.
3990 * * Each new entry is added at the end.
3991 * * Each duplicate-key entry's value overwrites the previous value.
3992 *
3993 * Example:
3994 * h = {foo: 0, bar: 1, baz: 2}
3995 * h1 = {bat: 3, bar: 4}
3996 * h2 = {bam: 5, bat:6}
3997 * h.merge!(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
3998 *
3999 * With arguments and a block:
4000 * * Returns +self+, after the given hashes are merged.
4001 * * The given hashes are merged left to right.
4002 * * Each new-key entry is added at the end.
4003 * * For each duplicate key:
4004 * * Calls the block with the key and the old and new values.
4005 * * The block's return value becomes the new value for the entry.
4006 *
4007 * Example:
4008 * h = {foo: 0, bar: 1, baz: 2}
4009 * h1 = {bat: 3, bar: 4}
4010 * h2 = {bam: 5, bat:6}
4011 * h3 = h.merge!(h1, h2) { |key, old_value, new_value| old_value + new_value }
4012 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
4013 *
4014 * With no arguments:
4015 * * Returns +self+, unmodified.
4016 * * The block, if given, is ignored.
4017 *
4018 * Example:
4019 * h = {foo: 0, bar: 1, baz: 2}
4020 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
4021 * h1 = h.merge! { |key, old_value, new_value| raise 'Cannot happen' }
4022 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
4023 */
4024
4025static VALUE
4026rb_hash_update(int argc, VALUE *argv, VALUE self)
4027{
4028 struct update_call_args args = {
4029 .hash = self,
4030 .argv = argv,
4031 .argc = argc,
4032 .block_given = rb_block_given_p(),
4033 .iterating = false,
4034 };
4035 VALUE arg = (VALUE)&args;
4036
4037 rb_hash_modify(self);
4038 return rb_ensure(rb_hash_update_call, arg, rb_hash_update_ensure, arg);
4039}
4040
4041 struct update_func_arg {
4042 VALUE hash;
4043 VALUE value;
4044 rb_hash_update_func *func;
4045};
4046
4047static int
4048rb_hash_update_func_callback(st_data_t *key, st_data_t *value, struct update_arg *arg, int existing)
4049{
4050 struct update_func_arg *uf_arg = (struct update_func_arg *)arg->arg;
4051 VALUE newvalue = uf_arg->value;
4052
4053 if (existing) {
4054 newvalue = (*uf_arg->func)((VALUE)*key, (VALUE)*value, newvalue);
4055 }
4056 *value = newvalue;
4057 return ST_CONTINUE;
4058}
4059
4060NOINSERT_UPDATE_CALLBACK(rb_hash_update_func_callback)
4061
4062static int
4063rb_hash_update_func_i(VALUE key, VALUE value, VALUE arg0)
4064{
4065 struct update_func_arg *arg = (struct update_func_arg *)arg0;
4066 VALUE hash = arg->hash;
4067
4068 arg->value = value;
4069 RHASH_UPDATE(hash, key, rb_hash_update_func_callback, (VALUE)arg);
4070 return ST_CONTINUE;
4071}
4072
4073 VALUE
4074rb_hash_update_by(VALUE hash1, VALUE hash2, rb_hash_update_func *func)
4075{
4076 rb_hash_modify(hash1);
4077 hash2 = to_hash(hash2);
4078 if (func) {
4079 struct update_func_arg arg;
4080 arg.hash = hash1;
4081 arg.func = func;
4082 rb_hash_foreach(hash2, rb_hash_update_func_i, (VALUE)&arg);
4083 }
4084 else {
4085 rb_hash_foreach(hash2, rb_hash_update_i, hash1);
4086 }
4087 return hash1;
4088}
4089
4090/*
4091 * call-seq:
4092 * hash.merge -> copy_of_self
4093 * hash.merge(*other_hashes) -> new_hash
4094 * hash.merge(*other_hashes) { |key, old_value, new_value| ... } -> new_hash
4095 *
4096 * Returns the new +Hash+ formed by merging each of +other_hashes+
4097 * into a copy of +self+.
4098 *
4099 * Each argument in +other_hashes+ must be a +Hash+.
4100 *
4101 * ---
4102 *
4103 * With arguments and no block:
4104 * * Returns the new +Hash+ object formed by merging each successive
4105 * +Hash+ in +other_hashes+ into +self+.
4106 * * Each new-key entry is added at the end.
4107 * * Each duplicate-key entry's value overwrites the previous value.
4108 *
4109 * Example:
4110 * h = {foo: 0, bar: 1, baz: 2}
4111 * h1 = {bat: 3, bar: 4}
4112 * h2 = {bam: 5, bat:6}
4113 * h.merge(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
4114 *
4115 * With arguments and a block:
4116 * * Returns a new +Hash+ object that is the merge of +self+ and each given hash.
4117 * * The given hashes are merged left to right.
4118 * * Each new-key entry is added at the end.
4119 * * For each duplicate key:
4120 * * Calls the block with the key and the old and new values.
4121 * * The block's return value becomes the new value for the entry.
4122 *
4123 * Example:
4124 * h = {foo: 0, bar: 1, baz: 2}
4125 * h1 = {bat: 3, bar: 4}
4126 * h2 = {bam: 5, bat:6}
4127 * h3 = h.merge(h1, h2) { |key, old_value, new_value| old_value + new_value }
4128 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
4129 *
4130 * With no arguments:
4131 * * Returns a copy of +self+.
4132 * * The block, if given, is ignored.
4133 *
4134 * Example:
4135 * h = {foo: 0, bar: 1, baz: 2}
4136 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
4137 * h1 = h.merge { |key, old_value, new_value| raise 'Cannot happen' }
4138 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
4139 */
4140
4141static VALUE
4142rb_hash_merge(int argc, VALUE *argv, VALUE self)
4143{
4144 return rb_hash_update(argc, argv, copy_compare_by_id(rb_hash_dup(self), self));
4145}
4146
4147static int
4148assoc_cmp(VALUE a, VALUE b)
4149{
4150 return !RTEST(rb_equal(a, b));
4151}
4152
4153 struct assoc_arg {
4154 st_table *tbl;
4155 st_data_t key;
4156};
4157
4158static VALUE
4159assoc_lookup(VALUE arg)
4160{
4161 struct assoc_arg *p = (struct assoc_arg*)arg;
4162 st_data_t data;
4163 if (st_lookup(p->tbl, p->key, &data)) return (VALUE)data;
4164 return Qundef;
4165}
4166
4167static int
4168assoc_i(VALUE key, VALUE val, VALUE arg)
4169{
4170 VALUE *args = (VALUE *)arg;
4171
4172 if (RTEST(rb_equal(args[0], key))) {
4173 args[1] = rb_assoc_new(key, val);
4174 return ST_STOP;
4175 }
4176 return ST_CONTINUE;
4177}
4178
4179/*
4180 * call-seq:
4181 * hash.assoc(key) -> new_array or nil
4182 *
4183 * If the given +key+ is found, returns a 2-element Array containing that key and its value:
4184 * h = {foo: 0, bar: 1, baz: 2}
4185 * h.assoc(:bar) # => [:bar, 1]
4186 *
4187 * Returns +nil+ if key +key+ is not found.
4188 */
4189
4190static VALUE
4191rb_hash_assoc(VALUE hash, VALUE key)
4192{
4193 VALUE args[2];
4194
4195 if (RHASH_EMPTY_P(hash)) return Qnil;
4196
4197 if (RHASH_ST_TABLE_P(hash) && !RHASH_IDENTHASH_P(hash)) {
4198 VALUE value = Qundef;
4199 st_table assoctable = *RHASH_ST_TABLE(hash);
4200 assoctable.type = &(struct st_hash_type){
4201 .compare = assoc_cmp,
4202 .hash = assoctable.type->hash,
4203 };
4204 VALUE arg = (VALUE)&(struct assoc_arg){
4205 .tbl = &assoctable,
4206 .key = (st_data_t)key,
4207 };
4208
4209 if (RB_OBJ_FROZEN(hash)) {
4210 value = assoc_lookup(arg);
4211 }
4212 else {
4213 hash_iter_lev_inc(hash);
4214 value = rb_ensure(assoc_lookup, arg, hash_foreach_ensure, hash);
4215 }
4216 hash_verify(hash);
4217 if (!UNDEF_P(value)) return rb_assoc_new(key, value);
4218 }
4219
4220 args[0] = key;
4221 args[1] = Qnil;
4222 rb_hash_foreach(hash, assoc_i, (VALUE)args);
4223 return args[1];
4224}
4225
4226static int
4227rassoc_i(VALUE key, VALUE val, VALUE arg)
4228{
4229 VALUE *args = (VALUE *)arg;
4230
4231 if (RTEST(rb_equal(args[0], val))) {
4232 args[1] = rb_assoc_new(key, val);
4233 return ST_STOP;
4234 }
4235 return ST_CONTINUE;
4236}
4237
4238/*
4239 * call-seq:
4240 * hash.rassoc(value) -> new_array or nil
4241 *
4242 * Returns a new 2-element Array consisting of the key and value
4243 * of the first-found entry whose value is <tt>==</tt> to value
4244 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
4245 * h = {foo: 0, bar: 1, baz: 1}
4246 * h.rassoc(1) # => [:bar, 1]
4247 *
4248 * Returns +nil+ if no such value found.
4249 */
4250
4251static VALUE
4252rb_hash_rassoc(VALUE hash, VALUE obj)
4253{
4254 VALUE args[2];
4255
4256 args[0] = obj;
4257 args[1] = Qnil;
4258 rb_hash_foreach(hash, rassoc_i, (VALUE)args);
4259 return args[1];
4260}
4261
4262static int
4263flatten_i(VALUE key, VALUE val, VALUE ary)
4264{
4265 VALUE pair[2];
4266
4267 pair[0] = key;
4268 pair[1] = val;
4269 rb_ary_cat(ary, pair, 2);
4270
4271 return ST_CONTINUE;
4272}
4273
4274/*
4275 * call-seq:
4276 * hash.flatten -> new_array
4277 * hash.flatten(level) -> new_array
4278 *
4279 * Returns a new Array object that is a 1-dimensional flattening of +self+.
4280 *
4281 * ---
4282 *
4283 * By default, nested Arrays are not flattened:
4284 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4285 * h.flatten # => [:foo, 0, :bar, [:bat, 3], :baz, 2]
4286 *
4287 * Takes the depth of recursive flattening from Integer argument +level+:
4288 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4289 * h.flatten(1) # => [:foo, 0, :bar, [:bat, [:baz, [:bat]]]]
4290 * h.flatten(2) # => [:foo, 0, :bar, :bat, [:baz, [:bat]]]
4291 * h.flatten(3) # => [:foo, 0, :bar, :bat, :baz, [:bat]]
4292 * h.flatten(4) # => [:foo, 0, :bar, :bat, :baz, :bat]
4293 *
4294 * When +level+ is negative, flattens all nested Arrays:
4295 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4296 * h.flatten(-1) # => [:foo, 0, :bar, :bat, :baz, :bat]
4297 * h.flatten(-2) # => [:foo, 0, :bar, :bat, :baz, :bat]
4298 *
4299 * When +level+ is zero, returns the equivalent of #to_a :
4300 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4301 * h.flatten(0) # => [[:foo, 0], [:bar, [:bat, 3]], [:baz, 2]]
4302 * h.flatten(0) == h.to_a # => true
4303 */
4304
4305static VALUE
4306rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
4307{
4308 VALUE ary;
4309
4310 rb_check_arity(argc, 0, 1);
4311
4312 if (argc) {
4313 int level = NUM2INT(argv[0]);
4314
4315 if (level == 0) return rb_hash_to_a(hash);
4316
4317 ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4318 rb_hash_foreach(hash, flatten_i, ary);
4319 level--;
4320
4321 if (level > 0) {
4322 VALUE ary_flatten_level = INT2FIX(level);
4323 rb_funcallv(ary, id_flatten_bang, 1, &ary_flatten_level);
4324 }
4325 else if (level < 0) {
4326 /* flatten recursively */
4327 rb_funcallv(ary, id_flatten_bang, 0, 0);
4328 }
4329 }
4330 else {
4331 ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
4332 rb_hash_foreach(hash, flatten_i, ary);
4333 }
4334
4335 return ary;
4336}
4337
4338static int
4339delete_if_nil(VALUE key, VALUE value, VALUE hash)
4340{
4341 if (NIL_P(value)) {
4342 return ST_DELETE;
4343 }
4344 return ST_CONTINUE;
4345}
4346
4347/*
4348 * call-seq:
4349 * hash.compact -> new_hash
4350 *
4351 * Returns a copy of +self+ with all +nil+-valued entries removed:
4352 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4353 * h1 = h.compact
4354 * h1 # => {:foo=>0, :baz=>2}
4355 */
4356
4357static VALUE
4358rb_hash_compact(VALUE hash)
4359{
4360 VALUE result = rb_hash_dup(hash);
4361 if (!RHASH_EMPTY_P(hash)) {
4362 rb_hash_foreach(result, delete_if_nil, result);
4363 compact_after_delete(result);
4364 }
4365 else if (rb_hash_compare_by_id_p(hash)) {
4366 result = rb_hash_compare_by_id(result);
4367 }
4368 return result;
4369}
4370
4371/*
4372 * call-seq:
4373 * hash.compact! -> self or nil
4374 *
4375 * Returns +self+ with all its +nil+-valued entries removed (in place):
4376 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4377 * h.compact! # => {:foo=>0, :baz=>2}
4378 *
4379 * Returns +nil+ if no entries were removed.
4380 */
4381
4382static VALUE
4383rb_hash_compact_bang(VALUE hash)
4384{
4385 st_index_t n;
4386 rb_hash_modify_check(hash);
4387 n = RHASH_SIZE(hash);
4388 if (n) {
4389 rb_hash_foreach(hash, delete_if_nil, hash);
4390 if (n != RHASH_SIZE(hash))
4391 return hash;
4392 }
4393 return Qnil;
4394}
4395
4396/*
4397 * call-seq:
4398 * hash.compare_by_identity -> self
4399 *
4400 * Sets +self+ to consider only identity in comparing keys;
4401 * two keys are considered the same only if they are the same object;
4402 * returns +self+.
4403 *
4404 * By default, these two object are considered to be the same key,
4405 * so +s1+ will overwrite +s0+:
4406 * s0 = 'x'
4407 * s1 = 'x'
4408 * h = {}
4409 * h.compare_by_identity? # => false
4410 * h[s0] = 0
4411 * h[s1] = 1
4412 * h # => {"x"=>1}
4413 *
4414 * After calling \#compare_by_identity, the keys are considered to be different,
4415 * and therefore do not overwrite each other:
4416 * h = {}
4417 * h.compare_by_identity # => {}
4418 * h.compare_by_identity? # => true
4419 * h[s0] = 0
4420 * h[s1] = 1
4421 * h # => {"x"=>0, "x"=>1}
4422 */
4423
4424 VALUE
4425rb_hash_compare_by_id(VALUE hash)
4426{
4427 VALUE tmp;
4428 st_table *identtable;
4429
4430 if (rb_hash_compare_by_id_p(hash)) return hash;
4431
4432 rb_hash_modify_check(hash);
4433 if (hash_iterating_p(hash)) {
4434 rb_raise(rb_eRuntimeError, "compare_by_identity during iteration");
4435 }
4436
4437 if (RHASH_TABLE_EMPTY_P(hash)) {
4438 // Fast path: There's nothing to rehash, so we don't need a `tmp` table.
4439 // We're most likely an AR table, so this will need an allocation.
4440 ar_force_convert_table(hash, __FILE__, __LINE__);
4441 HASH_ASSERT(RHASH_ST_TABLE_P(hash));
4442
4443 RHASH_ST_TABLE(hash)->type = &identhash;
4444 }
4445 else {
4446 // Slow path: Need to rehash the members of `self` into a new
4447 // `tmp` table using the new `identhash` compare/hash functions.
4448 tmp = hash_alloc(0);
4449 hash_st_table_init(tmp, &identhash, RHASH_SIZE(hash));
4450 identtable = RHASH_ST_TABLE(tmp);
4451
4452 rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
4453 rb_hash_free(hash);
4454
4455 // We know for sure `identtable` is an st table,
4456 // so we can skip `ar_force_convert_table` here.
4457 RHASH_ST_TABLE_SET(hash, identtable);
4458 RHASH_ST_CLEAR(tmp);
4459 }
4460
4461 return hash;
4462}
4463
4464/*
4465 * call-seq:
4466 * hash.compare_by_identity? -> true or false
4467 *
4468 * Returns +true+ if #compare_by_identity has been called, +false+ otherwise.
4469 */
4470
4471 VALUE
4472rb_hash_compare_by_id_p(VALUE hash)
4473{
4474 return RBOOL(RHASH_IDENTHASH_P(hash));
4475}
4476
4477 VALUE
4478rb_ident_hash_new(void)
4479{
4480 VALUE hash = rb_hash_new();
4481 hash_st_table_init(hash, &identhash, 0);
4482 return hash;
4483}
4484
4485 VALUE
4486rb_ident_hash_new_with_size(st_index_t size)
4487{
4488 VALUE hash = rb_hash_new();
4489 hash_st_table_init(hash, &identhash, size);
4490 return hash;
4491}
4492
4493 st_table *
4494rb_init_identtable(void)
4495{
4496 return st_init_table(&identhash);
4497}
4498
4499static int
4500any_p_i(VALUE key, VALUE value, VALUE arg)
4501{
4502 VALUE ret = rb_yield(rb_assoc_new(key, value));
4503 if (RTEST(ret)) {
4504 *(VALUE *)arg = Qtrue;
4505 return ST_STOP;
4506 }
4507 return ST_CONTINUE;
4508}
4509
4510static int
4511any_p_i_fast(VALUE key, VALUE value, VALUE arg)
4512{
4513 VALUE ret = rb_yield_values(2, key, value);
4514 if (RTEST(ret)) {
4515 *(VALUE *)arg = Qtrue;
4516 return ST_STOP;
4517 }
4518 return ST_CONTINUE;
4519}
4520
4521static int
4522any_p_i_pattern(VALUE key, VALUE value, VALUE arg)
4523{
4524 VALUE ret = rb_funcall(((VALUE *)arg)[1], idEqq, 1, rb_assoc_new(key, value));
4525 if (RTEST(ret)) {
4526 *(VALUE *)arg = Qtrue;
4527 return ST_STOP;
4528 }
4529 return ST_CONTINUE;
4530}
4531
4532/*
4533 * call-seq:
4534 * hash.any? -> true or false
4535 * hash.any?(object) -> true or false
4536 * hash.any? {|key, value| ... } -> true or false
4537 *
4538 * Returns +true+ if any element satisfies a given criterion;
4539 * +false+ otherwise.
4540 *
4541 * If +self+ has no element, returns +false+ and argument or block
4542 * are not used.
4543 *
4544 * With no argument and no block,
4545 * returns +true+ if +self+ is non-empty; +false+ if empty.
4546 *
4547 * With argument +object+ and no block,
4548 * returns +true+ if for any key +key+
4549 * <tt>h.assoc(key) == object</tt>:
4550 * h = {foo: 0, bar: 1, baz: 2}
4551 * h.any?([:bar, 1]) # => true
4552 * h.any?([:bar, 0]) # => false
4553 * h.any?([:baz, 1]) # => false
4554 *
4555 * With no argument and a block,
4556 * calls the block with each key-value pair;
4557 * returns +true+ if the block returns any truthy value,
4558 * +false+ otherwise:
4559 * h = {foo: 0, bar: 1, baz: 2}
4560 * h.any? {|key, value| value < 3 } # => true
4561 * h.any? {|key, value| value > 3 } # => false
4562 *
4563 * Related: Enumerable#any?
4564 */
4565
4566static VALUE
4567rb_hash_any_p(int argc, VALUE *argv, VALUE hash)
4568{
4569 VALUE args[2];
4570 args[0] = Qfalse;
4571
4572 rb_check_arity(argc, 0, 1);
4573 if (RHASH_EMPTY_P(hash)) return Qfalse;
4574 if (argc) {
4575 if (rb_block_given_p()) {
4576 rb_warn("given block not used");
4577 }
4578 args[1] = argv[0];
4579
4580 rb_hash_foreach(hash, any_p_i_pattern, (VALUE)args);
4581 }
4582 else {
4583 if (!rb_block_given_p()) {
4584 /* yields pairs, never false */
4585 return Qtrue;
4586 }
4587 if (rb_block_pair_yield_optimizable())
4588 rb_hash_foreach(hash, any_p_i_fast, (VALUE)args);
4589 else
4590 rb_hash_foreach(hash, any_p_i, (VALUE)args);
4591 }
4592 return args[0];
4593}
4594
4595/*
4596 * call-seq:
4597 * hash.dig(key, *identifiers) -> object
4598 *
4599 * Finds and returns the object in nested objects
4600 * that is specified by +key+ and +identifiers+.
4601 * The nested objects may be instances of various classes.
4602 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
4603 *
4604 * Nested Hashes:
4605 * h = {foo: {bar: {baz: 2}}}
4606 * h.dig(:foo) # => {:bar=>{:baz=>2}}
4607 * h.dig(:foo, :bar) # => {:baz=>2}
4608 * h.dig(:foo, :bar, :baz) # => 2
4609 * h.dig(:foo, :bar, :BAZ) # => nil
4610 *
4611 * Nested Hashes and Arrays:
4612 * h = {foo: {bar: [:a, :b, :c]}}
4613 * h.dig(:foo, :bar, 2) # => :c
4614 *
4615 * This method will use the {default values}[rdoc-ref:Hash@Default+Values]
4616 * for keys that are not present:
4617 * h = {foo: {bar: [:a, :b, :c]}}
4618 * h.dig(:hello) # => nil
4619 * h.default_proc = -> (hash, _key) { hash }
4620 * h.dig(:hello, :world) # => h
4621 * h.dig(:hello, :world, :foo, :bar, 2) # => :c
4622 */
4623
4624static VALUE
4625rb_hash_dig(int argc, VALUE *argv, VALUE self)
4626{
4627 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
4628 self = rb_hash_aref(self, *argv);
4629 if (!--argc) return self;
4630 ++argv;
4631 return rb_obj_dig(argc, argv, self, Qnil);
4632}
4633
4634static int
4635hash_le_i(VALUE key, VALUE value, VALUE arg)
4636{
4637 VALUE *args = (VALUE *)arg;
4638 VALUE v = rb_hash_lookup2(args[0], key, Qundef);
4639 if (!UNDEF_P(v) && rb_equal(value, v)) return ST_CONTINUE;
4640 args[1] = Qfalse;
4641 return ST_STOP;
4642}
4643
4644static VALUE
4645hash_le(VALUE hash1, VALUE hash2)
4646{
4647 VALUE args[2];
4648 args[0] = hash2;
4649 args[1] = Qtrue;
4650 rb_hash_foreach(hash1, hash_le_i, (VALUE)args);
4651 return args[1];
4652}
4653
4654/*
4655 * call-seq:
4656 * hash <= other_hash -> true or false
4657 *
4658 * Returns +true+ if +hash+ is a subset of +other_hash+, +false+ otherwise:
4659 * h1 = {foo: 0, bar: 1}
4660 * h2 = {foo: 0, bar: 1, baz: 2}
4661 * h1 <= h2 # => true
4662 * h2 <= h1 # => false
4663 * h1 <= h1 # => true
4664 */
4665static VALUE
4666rb_hash_le(VALUE hash, VALUE other)
4667{
4668 other = to_hash(other);
4669 if (RHASH_SIZE(hash) > RHASH_SIZE(other)) return Qfalse;
4670 return hash_le(hash, other);
4671}
4672
4673/*
4674 * call-seq:
4675 * hash < other_hash -> true or false
4676 *
4677 * Returns +true+ if +hash+ is a proper subset of +other_hash+, +false+ otherwise:
4678 * h1 = {foo: 0, bar: 1}
4679 * h2 = {foo: 0, bar: 1, baz: 2}
4680 * h1 < h2 # => true
4681 * h2 < h1 # => false
4682 * h1 < h1 # => false
4683 */
4684static VALUE
4685rb_hash_lt(VALUE hash, VALUE other)
4686{
4687 other = to_hash(other);
4688 if (RHASH_SIZE(hash) >= RHASH_SIZE(other)) return Qfalse;
4689 return hash_le(hash, other);
4690}
4691
4692/*
4693 * call-seq:
4694 * hash >= other_hash -> true or false
4695 *
4696 * Returns +true+ if +hash+ is a superset of +other_hash+, +false+ otherwise:
4697 * h1 = {foo: 0, bar: 1, baz: 2}
4698 * h2 = {foo: 0, bar: 1}
4699 * h1 >= h2 # => true
4700 * h2 >= h1 # => false
4701 * h1 >= h1 # => true
4702 */
4703static VALUE
4704rb_hash_ge(VALUE hash, VALUE other)
4705{
4706 other = to_hash(other);
4707 if (RHASH_SIZE(hash) < RHASH_SIZE(other)) return Qfalse;
4708 return hash_le(other, hash);
4709}
4710
4711/*
4712 * call-seq:
4713 * hash > other_hash -> true or false
4714 *
4715 * Returns +true+ if +hash+ is a proper superset of +other_hash+, +false+ otherwise:
4716 * h1 = {foo: 0, bar: 1, baz: 2}
4717 * h2 = {foo: 0, bar: 1}
4718 * h1 > h2 # => true
4719 * h2 > h1 # => false
4720 * h1 > h1 # => false
4721 */
4722static VALUE
4723rb_hash_gt(VALUE hash, VALUE other)
4724{
4725 other = to_hash(other);
4726 if (RHASH_SIZE(hash) <= RHASH_SIZE(other)) return Qfalse;
4727 return hash_le(other, hash);
4728}
4729
4730static VALUE
4731hash_proc_call(RB_BLOCK_CALL_FUNC_ARGLIST(key, hash))
4732{
4733 rb_check_arity(argc, 1, 1);
4734 return rb_hash_aref(hash, *argv);
4735}
4736
4737/*
4738 * call-seq:
4739 * hash.to_proc -> proc
4740 *
4741 * Returns a Proc object that maps a key to its value:
4742 * h = {foo: 0, bar: 1, baz: 2}
4743 * proc = h.to_proc
4744 * proc.class # => Proc
4745 * proc.call(:foo) # => 0
4746 * proc.call(:bar) # => 1
4747 * proc.call(:nosuch) # => nil
4748 */
4749static VALUE
4750rb_hash_to_proc(VALUE hash)
4751{
4752 return rb_func_lambda_new(hash_proc_call, hash, 1, 1);
4753}
4754
4755/* :nodoc: */
4756static VALUE
4757rb_hash_deconstruct_keys(VALUE hash, VALUE keys)
4758{
4759 return hash;
4760}
4761
4762static int
4763add_new_i(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
4764{
4765 VALUE *args = (VALUE *)arg;
4766 if (existing) return ST_STOP;
4767 RB_OBJ_WRITTEN(args[0], Qundef, (VALUE)*key);
4768 RB_OBJ_WRITE(args[0], (VALUE *)val, args[1]);
4769 return ST_CONTINUE;
4770}
4771
4772/*
4773 * add +key+ to +val+ pair if +hash+ does not contain +key+.
4774 * returns non-zero if +key+ was contained.
4775 */
4776int
4777rb_hash_add_new_element(VALUE hash, VALUE key, VALUE val)
4778{
4779 st_table *tbl;
4780 int ret = 0;
4781 VALUE args[2];
4782 args[0] = hash;
4783 args[1] = val;
4784
4785 if (RHASH_AR_TABLE_P(hash)) {
4786 ret = ar_update(hash, (st_data_t)key, add_new_i, (st_data_t)args);
4787 if (ret != -1) {
4788 return ret;
4789 }
4790 ar_force_convert_table(hash, __FILE__, __LINE__);
4791 }
4792
4793 tbl = RHASH_TBL_RAW(hash);
4794 return st_update(tbl, (st_data_t)key, add_new_i, (st_data_t)args);
4795
4796}
4797
4798static st_data_t
4799key_stringify(VALUE key)
4800{
4801 return (rb_obj_class(key) == rb_cString && !RB_OBJ_FROZEN(key)) ?
4802 rb_hash_key_str(key) : key;
4803}
4804
4805static void
4806ar_bulk_insert(VALUE hash, long argc, const VALUE *argv)
4807{
4808 long i;
4809 for (i = 0; i < argc; ) {
4810 st_data_t k = key_stringify(argv[i++]);
4811 st_data_t v = argv[i++];
4812 ar_insert(hash, k, v);
4813 RB_OBJ_WRITTEN(hash, Qundef, k);
4814 RB_OBJ_WRITTEN(hash, Qundef, v);
4815 }
4816}
4817
4818void
4819rb_hash_bulk_insert(long argc, const VALUE *argv, VALUE hash)
4820{
4821 HASH_ASSERT(argc % 2 == 0);
4822 if (argc > 0) {
4823 st_index_t size = argc / 2;
4824
4825 if (RHASH_AR_TABLE_P(hash) &&
4826 (RHASH_AR_TABLE_SIZE(hash) + size <= RHASH_AR_TABLE_MAX_SIZE)) {
4827 ar_bulk_insert(hash, argc, argv);
4828 }
4829 else {
4830 rb_hash_bulk_insert_into_st_table(argc, argv, hash);
4831 }
4832 }
4833}
4834
4835static char **origenviron;
4836#ifdef _WIN32
4837#define GET_ENVIRON(e) ((e) = rb_w32_get_environ())
4838#define FREE_ENVIRON(e) rb_w32_free_environ(e)
4839static char **my_environ;
4840#undef environ
4841#define environ my_environ
4842#undef getenv
4843#define getenv(n) rb_w32_ugetenv(n)
4844#elif defined(__APPLE__)
4845#undef environ
4846#define environ (*_NSGetEnviron())
4847#define GET_ENVIRON(e) (e)
4848#define FREE_ENVIRON(e)
4849#else
4850extern char **environ;
4851#define GET_ENVIRON(e) (e)
4852#define FREE_ENVIRON(e)
4853#endif
4854#ifdef ENV_IGNORECASE
4855#define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
4856#define ENVNMATCH(s1, s2, n) (STRNCASECMP((s1), (s2), (n)) == 0)
4857#else
4858#define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
4859#define ENVNMATCH(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
4860#endif
4861
4862#define ENV_LOCK() RB_VM_LOCK_ENTER()
4863#define ENV_UNLOCK() RB_VM_LOCK_LEAVE()
4864
4865static inline rb_encoding *
4866env_encoding(void)
4867{
4868#ifdef _WIN32
4869 return rb_utf8_encoding();
4870#else
4871 return rb_locale_encoding();
4872#endif
4873}
4874
4875static VALUE
4876env_enc_str_new(const char *ptr, long len, rb_encoding *enc)
4877{
4878 VALUE str = rb_external_str_new_with_enc(ptr, len, enc);
4879
4880 rb_obj_freeze(str);
4881 return str;
4882}
4883
4884static VALUE
4885env_str_new(const char *ptr, long len)
4886{
4887 return env_enc_str_new(ptr, len, env_encoding());
4888}
4889
4890static VALUE
4891env_str_new2(const char *ptr)
4892{
4893 if (!ptr) return Qnil;
4894 return env_str_new(ptr, strlen(ptr));
4895}
4896
4897static VALUE
4898getenv_with_lock(const char *name)
4899{
4900 VALUE ret;
4901 ENV_LOCK();
4902 {
4903 const char *val = getenv(name);
4904 ret = env_str_new2(val);
4905 }
4906 ENV_UNLOCK();
4907 return ret;
4908}
4909
4910static bool
4911has_env_with_lock(const char *name)
4912{
4913 const char *val;
4914
4915 ENV_LOCK();
4916 {
4917 val = getenv(name);
4918 }
4919 ENV_UNLOCK();
4920
4921 return val ? true : false;
4922}
4923
4924static const char TZ_ENV[] = "TZ";
4925
4926static void *
4927get_env_cstr(VALUE str, const char *name)
4928{
4929 char *var;
4930 rb_encoding *enc = rb_enc_get(str);
4931 if (!rb_enc_asciicompat(enc)) {
4932 rb_raise(rb_eArgError, "bad environment variable %s: ASCII incompatible encoding: %s",
4933 name, rb_enc_name(enc));
4934 }
4935 var = RSTRING_PTR(str);
4936 if (memchr(var, '\0', RSTRING_LEN(str))) {
4937 rb_raise(rb_eArgError, "bad environment variable %s: contains null byte", name);
4938 }
4939 return rb_str_fill_terminator(str, 1); /* ASCII compatible */
4940}
4941
4942#define get_env_ptr(var, val) \
4943 (var = get_env_cstr(val, #var))
4944
4945static inline const char *
4946env_name(volatile VALUE *s)
4947{
4948 const char *name;
4949 StringValue(*s);
4950 get_env_ptr(name, *s);
4951 return name;
4952}
4953
4954#define env_name(s) env_name(&(s))
4955
4956static VALUE env_aset(VALUE nm, VALUE val);
4957
4958static void
4959reset_by_modified_env(const char *nam, const char *val)
4960{
4961 /*
4962 * ENV['TZ'] = nil has a special meaning.
4963 * TZ is no longer considered up-to-date and ruby call tzset() as needed.
4964 * It could be useful if sysadmin change /etc/localtime.
4965 * This hack might works only on Linux glibc.
4966 */
4967 if (ENVMATCH(nam, TZ_ENV)) {
4968 ruby_reset_timezone(val);
4969 }
4970}
4971
4972static VALUE
4973env_delete(VALUE name)
4974{
4975 const char *nam = env_name(name);
4976 reset_by_modified_env(nam, NULL);
4977 VALUE val = getenv_with_lock(nam);
4978
4979 if (!NIL_P(val)) {
4980 ruby_setenv(nam, 0);
4981 }
4982 return val;
4983}
4984
4985/*
4986 * call-seq:
4987 * ENV.delete(name) -> value
4988 * ENV.delete(name) { |name| block } -> value
4989 * ENV.delete(missing_name) -> nil
4990 * ENV.delete(missing_name) { |name| block } -> block_value
4991 *
4992 * Deletes the environment variable with +name+ if it exists and returns its value:
4993 * ENV['foo'] = '0'
4994 * ENV.delete('foo') # => '0'
4995 *
4996 * If a block is not given and the named environment variable does not exist, returns +nil+.
4997 *
4998 * If a block given and the environment variable does not exist,
4999 * yields +name+ to the block and returns the value of the block:
5000 * ENV.delete('foo') { |name| name * 2 } # => "foofoo"
5001 *
5002 * If a block given and the environment variable exists,
5003 * deletes the environment variable and returns its value (ignoring the block):
5004 * ENV['foo'] = '0'
5005 * ENV.delete('foo') { |name| raise 'ignored' } # => "0"
5006 *
5007 * Raises an exception if +name+ is invalid.
5008 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5009 */
5010static VALUE
5011env_delete_m(VALUE obj, VALUE name)
5012{
5013 VALUE val;
5014
5015 val = env_delete(name);
5016 if (NIL_P(val) && rb_block_given_p()) val = rb_yield(name);
5017 return val;
5018}
5019
5020/*
5021 * call-seq:
5022 * ENV[name] -> value
5023 *
5024 * Returns the value for the environment variable +name+ if it exists:
5025 * ENV['foo'] = '0'
5026 * ENV['foo'] # => "0"
5027 * Returns +nil+ if the named variable does not exist.
5028 *
5029 * Raises an exception if +name+ is invalid.
5030 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5031 */
5032static VALUE
5033rb_f_getenv(VALUE obj, VALUE name)
5034{
5035 const char *nam = env_name(name);
5036 VALUE env = getenv_with_lock(nam);
5037 return env;
5038}
5039
5040/*
5041 * call-seq:
5042 * ENV.fetch(name) -> value
5043 * ENV.fetch(name, default) -> value
5044 * ENV.fetch(name) { |name| block } -> value
5045 *
5046 * If +name+ is the name of an environment variable, returns its value:
5047 * ENV['foo'] = '0'
5048 * ENV.fetch('foo') # => '0'
5049 * Otherwise if a block is given (but not a default value),
5050 * yields +name+ to the block and returns the block's return value:
5051 * ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string
5052 * Otherwise if a default value is given (but not a block), returns the default value:
5053 * ENV.delete('foo')
5054 * ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string
5055 * If the environment variable does not exist and both default and block are given,
5056 * issues a warning ("warning: block supersedes default value argument"),
5057 * yields +name+ to the block, and returns the block's return value:
5058 * ENV.fetch('foo', :default) { |name| :block_return } # => :block_return
5059 * Raises KeyError if +name+ is valid, but not found,
5060 * and neither default value nor block is given:
5061 * ENV.fetch('foo') # Raises KeyError (key not found: "foo")
5062 * Raises an exception if +name+ is invalid.
5063 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5064 */
5065static VALUE
5066env_fetch(int argc, VALUE *argv, VALUE _)
5067{
5068 VALUE key;
5069 long block_given;
5070 const char *nam;
5071 VALUE env;
5072
5073 rb_check_arity(argc, 1, 2);
5074 key = argv[0];
5075 block_given = rb_block_given_p();
5076 if (block_given && argc == 2) {
5077 rb_warn("block supersedes default value argument");
5078 }
5079 nam = env_name(key);
5080 env = getenv_with_lock(nam);
5081
5082 if (NIL_P(env)) {
5083 if (block_given) return rb_yield(key);
5084 if (argc == 1) {
5085 rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE"\"", key), envtbl, key);
5086 }
5087 return argv[1];
5088 }
5089 return env;
5090}
5091
5092#if defined(_WIN32) || (defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
5093#elif defined __sun
5094static int
5095in_origenv(const char *str)
5096{
5097 char **env;
5098 for (env = origenviron; *env; ++env) {
5099 if (*env == str) return 1;
5100 }
5101 return 0;
5102}
5103#else
5104static int
5105envix(const char *nam)
5106{
5107 // should be locked
5108
5109 register int i, len = strlen(nam);
5110 char **env;
5111
5112 env = GET_ENVIRON(environ);
5113 for (i = 0; env[i]; i++) {
5114 if (ENVNMATCH(env[i],nam,len) && env[i][len] == '=')
5115 break; /* memcmp must come first to avoid */
5116 } /* potential SEGV's */
5117 FREE_ENVIRON(environ);
5118 return i;
5119}
5120#endif
5121
5122#if defined(_WIN32) || \
5123 (defined(__sun) && !(defined(HAVE_SETENV) && defined(HAVE_UNSETENV)))
5124
5125NORETURN(static void invalid_envname(const char *name));
5126
5127static void
5128invalid_envname(const char *name)
5129{
5130 rb_syserr_fail_str(EINVAL, rb_sprintf("ruby_setenv(%s)", name));
5131}
5132
5133static const char *
5134check_envname(const char *name)
5135{
5136 if (strchr(name, '=')) {
5137 invalid_envname(name);
5138 }
5139 return name;
5140}
5141#endif
5142
5143void
5144ruby_setenv(const char *name, const char *value)
5145{
5146#if defined(_WIN32)
5147 VALUE buf;
5148 WCHAR *wname;
5149 WCHAR *wvalue = 0;
5150 int failed = 0;
5151 int len;
5152 check_envname(name);
5153 len = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0);
5154 if (value) {
5155 int len2;
5156 len2 = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0);
5157 wname = ALLOCV_N(WCHAR, buf, len + len2);
5158 wvalue = wname + len;
5159 MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len);
5160 MultiByteToWideChar(CP_UTF8, 0, value, -1, wvalue, len2);
5161 }
5162 else {
5163 wname = ALLOCV_N(WCHAR, buf, len + 1);
5164 MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len);
5165 wvalue = wname + len;
5166 *wvalue = L'\0';
5167 }
5168
5169 ENV_LOCK();
5170 {
5171 /* Use _wputenv_s() instead of SetEnvironmentVariableW() to make sure
5172 * special variables like "TZ" are interpret by libc. */
5173 failed = _wputenv_s(wname, wvalue);
5174 }
5175 ENV_UNLOCK();
5176
5177 ALLOCV_END(buf);
5178 /* even if putenv() failed, clean up and try to delete the
5179 * variable from the system area. */
5180 if (!value || !*value) {
5181 /* putenv() doesn't handle empty value */
5182 if (!SetEnvironmentVariableW(wname, value ? wvalue : NULL) &&
5183 GetLastError() != ERROR_ENVVAR_NOT_FOUND) goto fail;
5184 }
5185 if (failed) {
5186 fail:
5187 invalid_envname(name);
5188 }
5189#elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
5190 if (value) {
5191 int ret;
5192 ENV_LOCK();
5193 {
5194 ret = setenv(name, value, 1);
5195 }
5196 ENV_UNLOCK();
5197
5198 if (ret) rb_sys_fail_sprintf("setenv(%s)", name);
5199 }
5200 else {
5201#ifdef VOID_UNSETENV
5202 ENV_LOCK();
5203 {
5204 unsetenv(name);
5205 }
5206 ENV_UNLOCK();
5207#else
5208 int ret;
5209 ENV_LOCK();
5210 {
5211 ret = unsetenv(name);
5212 }
5213 ENV_UNLOCK();
5214
5215 if (ret) rb_sys_fail_sprintf("unsetenv(%s)", name);
5216#endif
5217 }
5218#elif defined __sun
5219 /* Solaris 9 (or earlier) does not have setenv(3C) and unsetenv(3C). */
5220 /* The below code was tested on Solaris 10 by:
5221 % ./configure ac_cv_func_setenv=no ac_cv_func_unsetenv=no
5222 */
5223 size_t len, mem_size;
5224 char **env_ptr, *str, *mem_ptr;
5225
5226 check_envname(name);
5227 len = strlen(name);
5228 if (value) {
5229 mem_size = len + strlen(value) + 2;
5230 mem_ptr = malloc(mem_size);
5231 if (mem_ptr == NULL)
5232 rb_sys_fail_sprintf("malloc(%"PRIuSIZE")", mem_size);
5233 snprintf(mem_ptr, mem_size, "%s=%s", name, value);
5234 }
5235
5236 ENV_LOCK();
5237 {
5238 for (env_ptr = GET_ENVIRON(environ); (str = *env_ptr) != 0; ++env_ptr) {
5239 if (!strncmp(str, name, len) && str[len] == '=') {
5240 if (!in_origenv(str)) free(str);
5241 while ((env_ptr[0] = env_ptr[1]) != 0) env_ptr++;
5242 break;
5243 }
5244 }
5245 }
5246 ENV_UNLOCK();
5247
5248 if (value) {
5249 int ret;
5250 ENV_LOCK();
5251 {
5252 ret = putenv(mem_ptr);
5253 }
5254 ENV_UNLOCK();
5255
5256 if (ret) {
5257 free(mem_ptr);
5258 rb_sys_fail_sprintf("putenv(%s)", name);
5259 }
5260 }
5261#else /* WIN32 */
5262 size_t len;
5263 int i;
5264
5265 ENV_LOCK();
5266 {
5267 i = envix(name); /* where does it go? */
5268
5269 if (environ == origenviron) { /* need we copy environment? */
5270 int j;
5271 int max;
5272 char **tmpenv;
5273
5274 for (max = i; environ[max]; max++) ;
5275 tmpenv = ALLOC_N(char*, max+2);
5276 for (j=0; j<max; j++) /* copy environment */
5277 tmpenv[j] = ruby_strdup(environ[j]);
5278 tmpenv[max] = 0;
5279 environ = tmpenv; /* tell exec where it is now */
5280 }
5281
5282 if (environ[i]) {
5283 char **envp = origenviron;
5284 while (*envp && *envp != environ[i]) envp++;
5285 if (!*envp)
5286 xfree(environ[i]);
5287 if (!value) {
5288 while (environ[i]) {
5289 environ[i] = environ[i+1];
5290 i++;
5291 }
5292 goto finish;
5293 }
5294 }
5295 else { /* does not exist yet */
5296 if (!value) goto finish;
5297 REALLOC_N(environ, char*, i+2); /* just expand it a bit */
5298 environ[i+1] = 0; /* make sure it's null terminated */
5299 }
5300
5301 len = strlen(name) + strlen(value) + 2;
5302 environ[i] = ALLOC_N(char, len);
5303 snprintf(environ[i],len,"%s=%s",name,value); /* all that work just for this */
5304
5305 finish:;
5306 }
5307 ENV_UNLOCK();
5308#endif /* WIN32 */
5309}
5310
5311void
5312ruby_unsetenv(const char *name)
5313{
5314 ruby_setenv(name, 0);
5315}
5316
5317/*
5318 * call-seq:
5319 * ENV[name] = value -> value
5320 * ENV.store(name, value) -> value
5321 *
5322 * Creates, updates, or deletes the named environment variable, returning the value.
5323 * Both +name+ and +value+ may be instances of String.
5324 * See {Valid Names and Values}[rdoc-ref:ENV@Valid+Names+and+Values].
5325 *
5326 * - If the named environment variable does not exist:
5327 * - If +value+ is +nil+, does nothing.
5328 * ENV.clear
5329 * ENV['foo'] = nil # => nil
5330 * ENV.include?('foo') # => false
5331 * ENV.store('bar', nil) # => nil
5332 * ENV.include?('bar') # => false
5333 * - If +value+ is not +nil+, creates the environment variable with +name+ and +value+:
5334 * # Create 'foo' using ENV.[]=.
5335 * ENV['foo'] = '0' # => '0'
5336 * ENV['foo'] # => '0'
5337 * # Create 'bar' using ENV.store.
5338 * ENV.store('bar', '1') # => '1'
5339 * ENV['bar'] # => '1'
5340 * - If the named environment variable exists:
5341 * - If +value+ is not +nil+, updates the environment variable with value +value+:
5342 * # Update 'foo' using ENV.[]=.
5343 * ENV['foo'] = '2' # => '2'
5344 * ENV['foo'] # => '2'
5345 * # Update 'bar' using ENV.store.
5346 * ENV.store('bar', '3') # => '3'
5347 * ENV['bar'] # => '3'
5348 * - If +value+ is +nil+, deletes the environment variable:
5349 * # Delete 'foo' using ENV.[]=.
5350 * ENV['foo'] = nil # => nil
5351 * ENV.include?('foo') # => false
5352 * # Delete 'bar' using ENV.store.
5353 * ENV.store('bar', nil) # => nil
5354 * ENV.include?('bar') # => false
5355 *
5356 * Raises an exception if +name+ or +value+ is invalid.
5357 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5358 */
5359static VALUE
5360env_aset_m(VALUE obj, VALUE nm, VALUE val)
5361{
5362 return env_aset(nm, val);
5363}
5364
5365static VALUE
5366env_aset(VALUE nm, VALUE val)
5367{
5368 char *name, *value;
5369
5370 if (NIL_P(val)) {
5371 env_delete(nm);
5372 return Qnil;
5373 }
5374 StringValue(nm);
5375 StringValue(val);
5376 /* nm can be modified in `val.to_str`, don't get `name` before
5377 * check for `val` */
5378 get_env_ptr(name, nm);
5379 get_env_ptr(value, val);
5380
5381 ruby_setenv(name, value);
5382 reset_by_modified_env(name, value);
5383 return val;
5384}
5385
5386static VALUE
5387env_keys(int raw)
5388{
5389 rb_encoding *enc = raw ? 0 : rb_locale_encoding();
5390 VALUE ary = rb_ary_new();
5391
5392 ENV_LOCK();
5393 {
5394 char **env = GET_ENVIRON(environ);
5395 while (*env) {
5396 char *s = strchr(*env, '=');
5397 if (s) {
5398 const char *p = *env;
5399 size_t l = s - p;
5400 VALUE e = raw ? rb_utf8_str_new(p, l) : env_enc_str_new(p, l, enc);
5401 rb_ary_push(ary, e);
5402 }
5403 env++;
5404 }
5405 FREE_ENVIRON(environ);
5406 }
5407 ENV_UNLOCK();
5408
5409 return ary;
5410}
5411
5412/*
5413 * call-seq:
5414 * ENV.keys -> array of names
5415 *
5416 * Returns all variable names in an Array:
5417 * ENV.replace('foo' => '0', 'bar' => '1')
5418 * ENV.keys # => ['bar', 'foo']
5419 * The order of the names is OS-dependent.
5420 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
5421 *
5422 * Returns the empty Array if ENV is empty.
5423 */
5424
5425static VALUE
5426env_f_keys(VALUE _)
5427{
5428 return env_keys(FALSE);
5429}
5430
5431static VALUE
5432rb_env_size(VALUE ehash, VALUE args, VALUE eobj)
5433{
5434 char **env;
5435 long cnt = 0;
5436
5437 ENV_LOCK();
5438 {
5439 env = GET_ENVIRON(environ);
5440 for (; *env ; ++env) {
5441 if (strchr(*env, '=')) {
5442 cnt++;
5443 }
5444 }
5445 FREE_ENVIRON(environ);
5446 }
5447 ENV_UNLOCK();
5448
5449 return LONG2FIX(cnt);
5450}
5451
5452/*
5453 * call-seq:
5454 * ENV.each_key { |name| block } -> ENV
5455 * ENV.each_key -> an_enumerator
5456 *
5457 * Yields each environment variable name:
5458 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5459 * names = []
5460 * ENV.each_key { |name| names.push(name) } # => ENV
5461 * names # => ["bar", "foo"]
5462 *
5463 * Returns an Enumerator if no block given:
5464 * e = ENV.each_key # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_key>
5465 * names = []
5466 * e.each { |name| names.push(name) } # => ENV
5467 * names # => ["bar", "foo"]
5468 */
5469static VALUE
5470env_each_key(VALUE ehash)
5471{
5472 VALUE keys;
5473 long i;
5474
5475 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5476 keys = env_keys(FALSE);
5477 for (i=0; i<RARRAY_LEN(keys); i++) {
5478 rb_yield(RARRAY_AREF(keys, i));
5479 }
5480 return ehash;
5481}
5482
5483static VALUE
5484env_values(void)
5485{
5486 VALUE ary = rb_ary_new();
5487
5488 ENV_LOCK();
5489 {
5490 char **env = GET_ENVIRON(environ);
5491
5492 while (*env) {
5493 char *s = strchr(*env, '=');
5494 if (s) {
5495 rb_ary_push(ary, env_str_new2(s+1));
5496 }
5497 env++;
5498 }
5499 FREE_ENVIRON(environ);
5500 }
5501 ENV_UNLOCK();
5502
5503 return ary;
5504}
5505
5506/*
5507 * call-seq:
5508 * ENV.values -> array of values
5509 *
5510 * Returns all environment variable values in an Array:
5511 * ENV.replace('foo' => '0', 'bar' => '1')
5512 * ENV.values # => ['1', '0']
5513 * The order of the values is OS-dependent.
5514 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
5515 *
5516 * Returns the empty Array if ENV is empty.
5517 */
5518static VALUE
5519env_f_values(VALUE _)
5520{
5521 return env_values();
5522}
5523
5524/*
5525 * call-seq:
5526 * ENV.each_value { |value| block } -> ENV
5527 * ENV.each_value -> an_enumerator
5528 *
5529 * Yields each environment variable value:
5530 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5531 * values = []
5532 * ENV.each_value { |value| values.push(value) } # => ENV
5533 * values # => ["1", "0"]
5534 *
5535 * Returns an Enumerator if no block given:
5536 * e = ENV.each_value # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_value>
5537 * values = []
5538 * e.each { |value| values.push(value) } # => ENV
5539 * values # => ["1", "0"]
5540 */
5541static VALUE
5542env_each_value(VALUE ehash)
5543{
5544 VALUE values;
5545 long i;
5546
5547 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5548 values = env_values();
5549 for (i=0; i<RARRAY_LEN(values); i++) {
5550 rb_yield(RARRAY_AREF(values, i));
5551 }
5552 return ehash;
5553}
5554
5555/*
5556 * call-seq:
5557 * ENV.each { |name, value| block } -> ENV
5558 * ENV.each -> an_enumerator
5559 * ENV.each_pair { |name, value| block } -> ENV
5560 * ENV.each_pair -> an_enumerator
5561 *
5562 * Yields each environment variable name and its value as a 2-element Array:
5563 * h = {}
5564 * ENV.each_pair { |name, value| h[name] = value } # => ENV
5565 * h # => {"bar"=>"1", "foo"=>"0"}
5566 *
5567 * Returns an Enumerator if no block given:
5568 * h = {}
5569 * e = ENV.each_pair # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_pair>
5570 * e.each { |name, value| h[name] = value } # => ENV
5571 * h # => {"bar"=>"1", "foo"=>"0"}
5572 */
5573static VALUE
5574env_each_pair(VALUE ehash)
5575{
5576 long i;
5577
5578 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5579
5580 VALUE ary = rb_ary_new();
5581
5582 ENV_LOCK();
5583 {
5584 char **env = GET_ENVIRON(environ);
5585
5586 while (*env) {
5587 char *s = strchr(*env, '=');
5588 if (s) {
5589 rb_ary_push(ary, env_str_new(*env, s-*env));
5590 rb_ary_push(ary, env_str_new2(s+1));
5591 }
5592 env++;
5593 }
5594 FREE_ENVIRON(environ);
5595 }
5596 ENV_UNLOCK();
5597
5598 if (rb_block_pair_yield_optimizable()) {
5599 for (i=0; i<RARRAY_LEN(ary); i+=2) {
5600 rb_yield_values(2, RARRAY_AREF(ary, i), RARRAY_AREF(ary, i+1));
5601 }
5602 }
5603 else {
5604 for (i=0; i<RARRAY_LEN(ary); i+=2) {
5605 rb_yield(rb_assoc_new(RARRAY_AREF(ary, i), RARRAY_AREF(ary, i+1)));
5606 }
5607 }
5608
5609 return ehash;
5610}
5611
5612/*
5613 * call-seq:
5614 * ENV.reject! { |name, value| block } -> ENV or nil
5615 * ENV.reject! -> an_enumerator
5616 *
5617 * Similar to ENV.delete_if, but returns +nil+ if no changes were made.
5618 *
5619 * Yields each environment variable name and its value as a 2-element Array,
5620 * deleting each environment variable for which the block returns a truthy value,
5621 * and returning ENV (if any deletions) or +nil+ (if not):
5622 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5623 * ENV.reject! { |name, value| name.start_with?('b') } # => ENV
5624 * ENV # => {"foo"=>"0"}
5625 * ENV.reject! { |name, value| name.start_with?('b') } # => nil
5626 *
5627 * Returns an Enumerator if no block given:
5628 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5629 * e = ENV.reject! # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:reject!>
5630 * e.each { |name, value| name.start_with?('b') } # => ENV
5631 * ENV # => {"foo"=>"0"}
5632 * e.each { |name, value| name.start_with?('b') } # => nil
5633 */
5634static VALUE
5635env_reject_bang(VALUE ehash)
5636{
5637 VALUE keys;
5638 long i;
5639 int del = 0;
5640
5641 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5642 keys = env_keys(FALSE);
5643 RBASIC_CLEAR_CLASS(keys);
5644 for (i=0; i<RARRAY_LEN(keys); i++) {
5645 VALUE val = rb_f_getenv(Qnil, RARRAY_AREF(keys, i));
5646 if (!NIL_P(val)) {
5647 if (RTEST(rb_yield_values(2, RARRAY_AREF(keys, i), val))) {
5648 env_delete(RARRAY_AREF(keys, i));
5649 del++;
5650 }
5651 }
5652 }
5653 RB_GC_GUARD(keys);
5654 if (del == 0) return Qnil;
5655 return envtbl;
5656}
5657
5658/*
5659 * call-seq:
5660 * ENV.delete_if { |name, value| block } -> ENV
5661 * ENV.delete_if -> an_enumerator
5662 *
5663 * Yields each environment variable name and its value as a 2-element Array,
5664 * deleting each environment variable for which the block returns a truthy value,
5665 * and returning ENV (regardless of whether any deletions):
5666 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5667 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5668 * ENV # => {"foo"=>"0"}
5669 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5670 *
5671 * Returns an Enumerator if no block given:
5672 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5673 * e = ENV.delete_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:delete_if!>
5674 * e.each { |name, value| name.start_with?('b') } # => ENV
5675 * ENV # => {"foo"=>"0"}
5676 * e.each { |name, value| name.start_with?('b') } # => ENV
5677 */
5678static VALUE
5679env_delete_if(VALUE ehash)
5680{
5681 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5682 env_reject_bang(ehash);
5683 return envtbl;
5684}
5685
5686/*
5687 * call-seq:
5688 * ENV.values_at(*names) -> array of values
5689 *
5690 * Returns an Array containing the environment variable values associated with
5691 * the given names:
5692 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5693 * ENV.values_at('foo', 'baz') # => ["0", "2"]
5694 *
5695 * Returns +nil+ in the Array for each name that is not an ENV name:
5696 * ENV.values_at('foo', 'bat', 'bar', 'bam') # => ["0", nil, "1", nil]
5697 *
5698 * Returns an empty Array if no names given.
5699 *
5700 * Raises an exception if any name is invalid.
5701 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5702 */
5703static VALUE
5704env_values_at(int argc, VALUE *argv, VALUE _)
5705{
5706 VALUE result;
5707 long i;
5708
5709 result = rb_ary_new();
5710 for (i=0; i<argc; i++) {
5711 rb_ary_push(result, rb_f_getenv(Qnil, argv[i]));
5712 }
5713 return result;
5714}
5715
5716/*
5717 * call-seq:
5718 * ENV.select { |name, value| block } -> hash of name/value pairs
5719 * ENV.select -> an_enumerator
5720 * ENV.filter { |name, value| block } -> hash of name/value pairs
5721 * ENV.filter -> an_enumerator
5722 *
5723 * Yields each environment variable name and its value as a 2-element Array,
5724 * returning a Hash of the names and values for which the block returns a truthy value:
5725 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5726 * ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5727 * ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5728 *
5729 * Returns an Enumerator if no block given:
5730 * e = ENV.select # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:select>
5731 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5732 * e = ENV.filter # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:filter>
5733 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5734 */
5735static VALUE
5736env_select(VALUE ehash)
5737{
5738 VALUE result;
5739 VALUE keys;
5740 long i;
5741
5742 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5743 result = rb_hash_new();
5744 keys = env_keys(FALSE);
5745 for (i = 0; i < RARRAY_LEN(keys); ++i) {
5746 VALUE key = RARRAY_AREF(keys, i);
5747 VALUE val = rb_f_getenv(Qnil, key);
5748 if (!NIL_P(val)) {
5749 if (RTEST(rb_yield_values(2, key, val))) {
5750 rb_hash_aset(result, key, val);
5751 }
5752 }
5753 }
5754 RB_GC_GUARD(keys);
5755
5756 return result;
5757}
5758
5759/*
5760 * call-seq:
5761 * ENV.select! { |name, value| block } -> ENV or nil
5762 * ENV.select! -> an_enumerator
5763 * ENV.filter! { |name, value| block } -> ENV or nil
5764 * ENV.filter! -> an_enumerator
5765 *
5766 * Yields each environment variable name and its value as a 2-element Array,
5767 * deleting each entry for which the block returns +false+ or +nil+,
5768 * and returning ENV if any deletions made, or +nil+ otherwise:
5769 *
5770 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5771 * ENV.select! { |name, value| name.start_with?('b') } # => ENV
5772 * ENV # => {"bar"=>"1", "baz"=>"2"}
5773 * ENV.select! { |name, value| true } # => nil
5774 *
5775 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5776 * ENV.filter! { |name, value| name.start_with?('b') } # => ENV
5777 * ENV # => {"bar"=>"1", "baz"=>"2"}
5778 * ENV.filter! { |name, value| true } # => nil
5779 *
5780 * Returns an Enumerator if no block given:
5781 *
5782 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5783 * e = ENV.select! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:select!>
5784 * e.each { |name, value| name.start_with?('b') } # => ENV
5785 * ENV # => {"bar"=>"1", "baz"=>"2"}
5786 * e.each { |name, value| true } # => nil
5787 *
5788 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5789 * e = ENV.filter! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:filter!>
5790 * e.each { |name, value| name.start_with?('b') } # => ENV
5791 * ENV # => {"bar"=>"1", "baz"=>"2"}
5792 * e.each { |name, value| true } # => nil
5793 */
5794static VALUE
5795env_select_bang(VALUE ehash)
5796{
5797 VALUE keys;
5798 long i;
5799 int del = 0;
5800
5801 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5802 keys = env_keys(FALSE);
5803 RBASIC_CLEAR_CLASS(keys);
5804 for (i=0; i<RARRAY_LEN(keys); i++) {
5805 VALUE val = rb_f_getenv(Qnil, RARRAY_AREF(keys, i));
5806 if (!NIL_P(val)) {
5807 if (!RTEST(rb_yield_values(2, RARRAY_AREF(keys, i), val))) {
5808 env_delete(RARRAY_AREF(keys, i));
5809 del++;
5810 }
5811 }
5812 }
5813 RB_GC_GUARD(keys);
5814 if (del == 0) return Qnil;
5815 return envtbl;
5816}
5817
5818/*
5819 * call-seq:
5820 * ENV.keep_if { |name, value| block } -> ENV
5821 * ENV.keep_if -> an_enumerator
5822 *
5823 * Yields each environment variable name and its value as a 2-element Array,
5824 * deleting each environment variable for which the block returns +false+ or +nil+,
5825 * and returning ENV:
5826 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5827 * ENV.keep_if { |name, value| name.start_with?('b') } # => ENV
5828 * ENV # => {"bar"=>"1", "baz"=>"2"}
5829 *
5830 * Returns an Enumerator if no block given:
5831 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5832 * e = ENV.keep_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:keep_if>
5833 * e.each { |name, value| name.start_with?('b') } # => ENV
5834 * ENV # => {"bar"=>"1", "baz"=>"2"}
5835 */
5836static VALUE
5837env_keep_if(VALUE ehash)
5838{
5839 RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
5840 env_select_bang(ehash);
5841 return envtbl;
5842}
5843
5844/*
5845 * call-seq:
5846 * ENV.slice(*names) -> hash of name/value pairs
5847 *
5848 * Returns a Hash of the given ENV names and their corresponding values:
5849 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2', 'bat' => '3')
5850 * ENV.slice('foo', 'baz') # => {"foo"=>"0", "baz"=>"2"}
5851 * ENV.slice('baz', 'foo') # => {"baz"=>"2", "foo"=>"0"}
5852 * Raises an exception if any of the +names+ is invalid
5853 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
5854 * ENV.slice('foo', 'bar', :bat) # Raises TypeError (no implicit conversion of Symbol into String)
5855 */
5856static VALUE
5857env_slice(int argc, VALUE *argv, VALUE _)
5858{
5859 int i;
5860 VALUE key, value, result;
5861
5862 if (argc == 0) {
5863 return rb_hash_new();
5864 }
5865 result = rb_hash_new_with_size(argc);
5866
5867 for (i = 0; i < argc; i++) {
5868 key = argv[i];
5869 value = rb_f_getenv(Qnil, key);
5870 if (value != Qnil)
5871 rb_hash_aset(result, key, value);
5872 }
5873
5874 return result;
5875}
5876
5877 VALUE
5878rb_env_clear(void)
5879{
5880 VALUE keys;
5881 long i;
5882
5883 keys = env_keys(TRUE);
5884 for (i=0; i<RARRAY_LEN(keys); i++) {
5885 VALUE key = RARRAY_AREF(keys, i);
5886 const char *nam = RSTRING_PTR(key);
5887 ruby_setenv(nam, 0);
5888 }
5889 RB_GC_GUARD(keys);
5890 return envtbl;
5891}
5892
5893/*
5894 * call-seq:
5895 * ENV.clear -> ENV
5896 *
5897 * Removes every environment variable; returns ENV:
5898 * ENV.replace('foo' => '0', 'bar' => '1')
5899 * ENV.size # => 2
5900 * ENV.clear # => ENV
5901 * ENV.size # => 0
5902 */
5903static VALUE
5904env_clear(VALUE _)
5905{
5906 return rb_env_clear();
5907}
5908
5909/*
5910 * call-seq:
5911 * ENV.to_s -> "ENV"
5912 *
5913 * Returns String 'ENV':
5914 * ENV.to_s # => "ENV"
5915 */
5916static VALUE
5917env_to_s(VALUE _)
5918{
5919 return rb_usascii_str_new2("ENV");
5920}
5921
5922/*
5923 * call-seq:
5924 * ENV.inspect -> a_string
5925 *
5926 * Returns the contents of the environment as a String:
5927 * ENV.replace('foo' => '0', 'bar' => '1')
5928 * ENV.inspect # => "{\"bar\"=>\"1\", \"foo\"=>\"0\"}"
5929 */
5930static VALUE
5931env_inspect(VALUE _)
5932{
5933 VALUE str = rb_str_buf_new2("{");
5934 rb_encoding *enc = env_encoding();
5935
5936 ENV_LOCK();
5937 {
5938 char **env = GET_ENVIRON(environ);
5939 while (*env) {
5940 const char *s = strchr(*env, '=');
5941
5942 if (env != environ) {
5943 rb_str_buf_cat2(str, ", ");
5944 }
5945 if (s) {
5946 rb_str_buf_append(str, rb_str_inspect(env_enc_str_new(*env, s-*env, enc)));
5947 rb_str_buf_cat2(str, " => ");
5948 s++;
5949 rb_str_buf_append(str, rb_str_inspect(env_enc_str_new(s, strlen(s), enc)));
5950 }
5951 env++;
5952 }
5953 FREE_ENVIRON(environ);
5954 }
5955 ENV_UNLOCK();
5956
5957 rb_str_buf_cat2(str, "}");
5958
5959 return str;
5960}
5961
5962/*
5963 * call-seq:
5964 * ENV.to_a -> array of 2-element arrays
5965 *
5966 * Returns the contents of ENV as an Array of 2-element Arrays,
5967 * each of which is a name/value pair:
5968 * ENV.replace('foo' => '0', 'bar' => '1')
5969 * ENV.to_a # => [["bar", "1"], ["foo", "0"]]
5970 */
5971static VALUE
5972env_to_a(VALUE _)
5973{
5974 VALUE ary = rb_ary_new();
5975
5976 ENV_LOCK();
5977 {
5978 char **env = GET_ENVIRON(environ);
5979 while (*env) {
5980 char *s = strchr(*env, '=');
5981 if (s) {
5982 rb_ary_push(ary, rb_assoc_new(env_str_new(*env, s-*env),
5983 env_str_new2(s+1)));
5984 }
5985 env++;
5986 }
5987 FREE_ENVIRON(environ);
5988 }
5989 ENV_UNLOCK();
5990
5991 return ary;
5992}
5993
5994/*
5995 * call-seq:
5996 * ENV.rehash -> nil
5997 *
5998 * (Provided for compatibility with Hash.)
5999 *
6000 * Does not modify ENV; returns +nil+.
6001 */
6002static VALUE
6003env_none(VALUE _)
6004{
6005 return Qnil;
6006}
6007
6008static int
6009env_size_with_lock(void)
6010{
6011 int i = 0;
6012
6013 ENV_LOCK();
6014 {
6015 char **env = GET_ENVIRON(environ);
6016 while (env[i]) i++;
6017 FREE_ENVIRON(environ);
6018 }
6019 ENV_UNLOCK();
6020
6021 return i;
6022}
6023
6024/*
6025 * call-seq:
6026 * ENV.length -> an_integer
6027 * ENV.size -> an_integer
6028 *
6029 * Returns the count of environment variables:
6030 * ENV.replace('foo' => '0', 'bar' => '1')
6031 * ENV.length # => 2
6032 * ENV.size # => 2
6033 */
6034static VALUE
6035env_size(VALUE _)
6036{
6037 return INT2FIX(env_size_with_lock());
6038}
6039
6040/*
6041 * call-seq:
6042 * ENV.empty? -> true or false
6043 *
6044 * Returns +true+ when there are no environment variables, +false+ otherwise:
6045 * ENV.clear
6046 * ENV.empty? # => true
6047 * ENV['foo'] = '0'
6048 * ENV.empty? # => false
6049 */
6050static VALUE
6051env_empty_p(VALUE _)
6052{
6053 bool empty = true;
6054
6055 ENV_LOCK();
6056 {
6057 char **env = GET_ENVIRON(environ);
6058 if (env[0] != 0) {
6059 empty = false;
6060 }
6061 FREE_ENVIRON(environ);
6062 }
6063 ENV_UNLOCK();
6064
6065 return RBOOL(empty);
6066}
6067
6068/*
6069 * call-seq:
6070 * ENV.include?(name) -> true or false
6071 * ENV.has_key?(name) -> true or false
6072 * ENV.member?(name) -> true or false
6073 * ENV.key?(name) -> true or false
6074 *
6075 * Returns +true+ if there is an environment variable with the given +name+:
6076 * ENV.replace('foo' => '0', 'bar' => '1')
6077 * ENV.include?('foo') # => true
6078 * Returns +false+ if +name+ is a valid String and there is no such environment variable:
6079 * ENV.include?('baz') # => false
6080 * Returns +false+ if +name+ is the empty String or is a String containing character <code>'='</code>:
6081 * ENV.include?('') # => false
6082 * ENV.include?('=') # => false
6083 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6084 * ENV.include?("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6085 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6086 * ENV.include?("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6087 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6088 * Raises an exception if +name+ is not a String:
6089 * ENV.include?(Object.new) # TypeError (no implicit conversion of Object into String)
6090 */
6091static VALUE
6092env_has_key(VALUE env, VALUE key)
6093{
6094 const char *s = env_name(key);
6095 return RBOOL(has_env_with_lock(s));
6096}
6097
6098/*
6099 * call-seq:
6100 * ENV.assoc(name) -> [name, value] or nil
6101 *
6102 * Returns a 2-element Array containing the name and value of the environment variable
6103 * for +name+ if it exists:
6104 * ENV.replace('foo' => '0', 'bar' => '1')
6105 * ENV.assoc('foo') # => ['foo', '0']
6106 * Returns +nil+ if +name+ is a valid String and there is no such environment variable.
6107 *
6108 * Returns +nil+ if +name+ is the empty String or is a String containing character <code>'='</code>.
6109 *
6110 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6111 * ENV.assoc("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6112 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6113 * ENV.assoc("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6114 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6115 * Raises an exception if +name+ is not a String:
6116 * ENV.assoc(Object.new) # TypeError (no implicit conversion of Object into String)
6117 */
6118static VALUE
6119env_assoc(VALUE env, VALUE key)
6120{
6121 const char *s = env_name(key);
6122 VALUE e = getenv_with_lock(s);
6123
6124 if (!NIL_P(e)) {
6125 return rb_assoc_new(key, e);
6126 }
6127 else {
6128 return Qnil;
6129 }
6130}
6131
6132/*
6133 * call-seq:
6134 * ENV.value?(value) -> true or false
6135 * ENV.has_value?(value) -> true or false
6136 *
6137 * Returns +true+ if +value+ is the value for some environment variable name, +false+ otherwise:
6138 * ENV.replace('foo' => '0', 'bar' => '1')
6139 * ENV.value?('0') # => true
6140 * ENV.has_value?('0') # => true
6141 * ENV.value?('2') # => false
6142 * ENV.has_value?('2') # => false
6143 */
6144static VALUE
6145env_has_value(VALUE dmy, VALUE obj)
6146{
6147 obj = rb_check_string_type(obj);
6148 if (NIL_P(obj)) return Qnil;
6149
6150 VALUE ret = Qfalse;
6151
6152 ENV_LOCK();
6153 {
6154 char **env = GET_ENVIRON(environ);
6155 while (*env) {
6156 char *s = strchr(*env, '=');
6157 if (s++) {
6158 long len = strlen(s);
6159 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
6160 ret = Qtrue;
6161 break;
6162 }
6163 }
6164 env++;
6165 }
6166 FREE_ENVIRON(environ);
6167 }
6168 ENV_UNLOCK();
6169
6170 return ret;
6171}
6172
6173/*
6174 * call-seq:
6175 * ENV.rassoc(value) -> [name, value] or nil
6176 *
6177 * Returns a 2-element Array containing the name and value of the
6178 * *first* *found* environment variable that has value +value+, if one
6179 * exists:
6180 * ENV.replace('foo' => '0', 'bar' => '0')
6181 * ENV.rassoc('0') # => ["bar", "0"]
6182 * The order in which environment variables are examined is OS-dependent.
6183 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6184 *
6185 * Returns +nil+ if there is no such environment variable.
6186 */
6187static VALUE
6188env_rassoc(VALUE dmy, VALUE obj)
6189{
6190 obj = rb_check_string_type(obj);
6191 if (NIL_P(obj)) return Qnil;
6192
6193 VALUE result = Qnil;
6194
6195 ENV_LOCK();
6196 {
6197 char **env = GET_ENVIRON(environ);
6198
6199 while (*env) {
6200 const char *p = *env;
6201 char *s = strchr(p, '=');
6202 if (s++) {
6203 long len = strlen(s);
6204 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
6205 result = rb_assoc_new(rb_str_new(p, s-p-1), obj);
6206 break;
6207 }
6208 }
6209 env++;
6210 }
6211 FREE_ENVIRON(environ);
6212 }
6213 ENV_UNLOCK();
6214
6215 return result;
6216}
6217
6218/*
6219 * call-seq:
6220 * ENV.key(value) -> name or nil
6221 *
6222 * Returns the name of the first environment variable with +value+, if it exists:
6223 * ENV.replace('foo' => '0', 'bar' => '0')
6224 * ENV.key('0') # => "foo"
6225 * The order in which environment variables are examined is OS-dependent.
6226 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6227 *
6228 * Returns +nil+ if there is no such value.
6229 *
6230 * Raises an exception if +value+ is invalid:
6231 * ENV.key(Object.new) # raises TypeError (no implicit conversion of Object into String)
6232 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
6233 */
6234static VALUE
6235env_key(VALUE dmy, VALUE value)
6236{
6237 StringValue(value);
6238 VALUE str = Qnil;
6239
6240 ENV_LOCK();
6241 {
6242 char **env = GET_ENVIRON(environ);
6243 while (*env) {
6244 char *s = strchr(*env, '=');
6245 if (s++) {
6246 long len = strlen(s);
6247 if (RSTRING_LEN(value) == len && strncmp(s, RSTRING_PTR(value), len) == 0) {
6248 str = env_str_new(*env, s-*env-1);
6249 break;
6250 }
6251 }
6252 env++;
6253 }
6254 FREE_ENVIRON(environ);
6255 }
6256 ENV_UNLOCK();
6257
6258 return str;
6259}
6260
6261static VALUE
6262env_to_hash(void)
6263{
6264 VALUE hash = rb_hash_new();
6265
6266 ENV_LOCK();
6267 {
6268 char **env = GET_ENVIRON(environ);
6269 while (*env) {
6270 char *s = strchr(*env, '=');
6271 if (s) {
6272 rb_hash_aset(hash, env_str_new(*env, s-*env),
6273 env_str_new2(s+1));
6274 }
6275 env++;
6276 }
6277 FREE_ENVIRON(environ);
6278 }
6279 ENV_UNLOCK();
6280
6281 return hash;
6282}
6283
6284 VALUE
6285rb_envtbl(void)
6286{
6287 return envtbl;
6288}
6289
6290 VALUE
6291rb_env_to_hash(void)
6292{
6293 return env_to_hash();
6294}
6295
6296/*
6297 * call-seq:
6298 * ENV.to_hash -> hash of name/value pairs
6299 *
6300 * Returns a Hash containing all name/value pairs from ENV:
6301 * ENV.replace('foo' => '0', 'bar' => '1')
6302 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6303 */
6304
6305static VALUE
6306env_f_to_hash(VALUE _)
6307{
6308 return env_to_hash();
6309}
6310
6311/*
6312 * call-seq:
6313 * ENV.to_h -> hash of name/value pairs
6314 * ENV.to_h {|name, value| block } -> hash of name/value pairs
6315 *
6316 * With no block, returns a Hash containing all name/value pairs from ENV:
6317 * ENV.replace('foo' => '0', 'bar' => '1')
6318 * ENV.to_h # => {"bar"=>"1", "foo"=>"0"}
6319 * With a block, returns a Hash whose items are determined by the block.
6320 * Each name/value pair in ENV is yielded to the block.
6321 * The block must return a 2-element Array (name/value pair)
6322 * that is added to the return Hash as a key and value:
6323 * ENV.to_h { |name, value| [name.to_sym, value.to_i] } # => {:bar=>1, :foo=>0}
6324 * Raises an exception if the block does not return an Array:
6325 * ENV.to_h { |name, value| name } # Raises TypeError (wrong element type String (expected array))
6326 * Raises an exception if the block returns an Array of the wrong size:
6327 * ENV.to_h { |name, value| [name] } # Raises ArgumentError (element has wrong array length (expected 2, was 1))
6328 */
6329static VALUE
6330env_to_h(VALUE _)
6331{
6332 VALUE hash = env_to_hash();
6333 if (rb_block_given_p()) {
6334 hash = rb_hash_to_h_block(hash);
6335 }
6336 return hash;
6337}
6338
6339/*
6340 * call-seq:
6341 * ENV.except(*keys) -> a_hash
6342 *
6343 * Returns a hash except the given keys from ENV and their values.
6344 *
6345 * ENV #=> {"LANG"=>"en_US.UTF-8", "TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"}
6346 * ENV.except("TERM","HOME") #=> {"LANG"=>"en_US.UTF-8"}
6347 */
6348static VALUE
6349env_except(int argc, VALUE *argv, VALUE _)
6350{
6351 int i;
6352 VALUE key, hash = env_to_hash();
6353
6354 for (i = 0; i < argc; i++) {
6355 key = argv[i];
6356 rb_hash_delete(hash, key);
6357 }
6358
6359 return hash;
6360}
6361
6362/*
6363 * call-seq:
6364 * ENV.reject { |name, value| block } -> hash of name/value pairs
6365 * ENV.reject -> an_enumerator
6366 *
6367 * Yields each environment variable name and its value as a 2-element Array.
6368 * Returns a Hash whose items are determined by the block.
6369 * When the block returns a truthy value, the name/value pair is added to the return Hash;
6370 * otherwise the pair is ignored:
6371 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
6372 * ENV.reject { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6373 * Returns an Enumerator if no block given:
6374 * e = ENV.reject
6375 * e.each { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6376 */
6377static VALUE
6378env_reject(VALUE _)
6379{
6380 return rb_hash_delete_if(env_to_hash());
6381}
6382
6383NORETURN(static VALUE env_freeze(VALUE self));
6384/*
6385 * call-seq:
6386 * ENV.freeze
6387 *
6388 * Raises an exception:
6389 * ENV.freeze # Raises TypeError (cannot freeze ENV)
6390 */
6391static VALUE
6392env_freeze(VALUE self)
6393{
6394 rb_raise(rb_eTypeError, "cannot freeze ENV");
6395 UNREACHABLE_RETURN(self);
6396}
6397
6398/*
6399 * call-seq:
6400 * ENV.shift -> [name, value] or nil
6401 *
6402 * Removes the first environment variable from ENV and returns
6403 * a 2-element Array containing its name and value:
6404 * ENV.replace('foo' => '0', 'bar' => '1')
6405 * ENV.to_hash # => {'bar' => '1', 'foo' => '0'}
6406 * ENV.shift # => ['bar', '1']
6407 * ENV.to_hash # => {'foo' => '0'}
6408 * Exactly which environment variable is "first" is OS-dependent.
6409 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6410 *
6411 * Returns +nil+ if the environment is empty.
6412 */
6413static VALUE
6414env_shift(VALUE _)
6415{
6416 VALUE result = Qnil;
6417 VALUE key = Qnil;
6418
6419 ENV_LOCK();
6420 {
6421 char **env = GET_ENVIRON(environ);
6422 if (*env) {
6423 const char *p = *env;
6424 char *s = strchr(p, '=');
6425 if (s) {
6426 key = env_str_new(p, s-p);
6427 VALUE val = env_str_new2(getenv(RSTRING_PTR(key)));
6428 result = rb_assoc_new(key, val);
6429 }
6430 }
6431 FREE_ENVIRON(environ);
6432 }
6433 ENV_UNLOCK();
6434
6435 if (!NIL_P(key)) {
6436 env_delete(key);
6437 }
6438
6439 return result;
6440}
6441
6442/*
6443 * call-seq:
6444 * ENV.invert -> hash of value/name pairs
6445 *
6446 * Returns a Hash whose keys are the ENV values,
6447 * and whose values are the corresponding ENV names:
6448 * ENV.replace('foo' => '0', 'bar' => '1')
6449 * ENV.invert # => {"1"=>"bar", "0"=>"foo"}
6450 * For a duplicate ENV value, overwrites the hash entry:
6451 * ENV.replace('foo' => '0', 'bar' => '0')
6452 * ENV.invert # => {"0"=>"foo"}
6453 * Note that the order of the ENV processing is OS-dependent,
6454 * which means that the order of overwriting is also OS-dependent.
6455 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6456 */
6457static VALUE
6458env_invert(VALUE _)
6459{
6460 return rb_hash_invert(env_to_hash());
6461}
6462
6463static void
6464keylist_delete(VALUE keys, VALUE key)
6465{
6466 long keylen, elen;
6467 const char *keyptr, *eptr;
6468 RSTRING_GETMEM(key, keyptr, keylen);
6469 /* Don't stop at first key, as it is possible to have
6470 multiple environment values with the same key.
6471 */
6472 for (long i=0; i<RARRAY_LEN(keys); i++) {
6473 VALUE e = RARRAY_AREF(keys, i);
6474 RSTRING_GETMEM(e, eptr, elen);
6475 if (elen != keylen) continue;
6476 if (!ENVNMATCH(keyptr, eptr, elen)) continue;
6477 rb_ary_delete_at(keys, i);
6478 i--;
6479 }
6480}
6481
6482static int
6483env_replace_i(VALUE key, VALUE val, VALUE keys)
6484{
6485 env_name(key);
6486 env_aset(key, val);
6487
6488 keylist_delete(keys, key);
6489 return ST_CONTINUE;
6490}
6491
6492/*
6493 * call-seq:
6494 * ENV.replace(hash) -> ENV
6495 *
6496 * Replaces the entire content of the environment variables
6497 * with the name/value pairs in the given +hash+;
6498 * returns ENV.
6499 *
6500 * Replaces the content of ENV with the given pairs:
6501 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
6502 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6503 *
6504 * Raises an exception if a name or value is invalid
6505 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
6506 * ENV.replace('foo' => '0', :bar => '1') # Raises TypeError (no implicit conversion of Symbol into String)
6507 * ENV.replace('foo' => '0', 'bar' => 1) # Raises TypeError (no implicit conversion of Integer into String)
6508 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6509 */
6510static VALUE
6511env_replace(VALUE env, VALUE hash)
6512{
6513 VALUE keys;
6514 long i;
6515
6516 keys = env_keys(TRUE);
6517 if (env == hash) return env;
6518 hash = to_hash(hash);
6519 rb_hash_foreach(hash, env_replace_i, keys);
6520
6521 for (i=0; i<RARRAY_LEN(keys); i++) {
6522 env_delete(RARRAY_AREF(keys, i));
6523 }
6524 RB_GC_GUARD(keys);
6525 return env;
6526}
6527
6528static int
6529env_update_i(VALUE key, VALUE val, VALUE _)
6530{
6531 env_aset(key, val);
6532 return ST_CONTINUE;
6533}
6534
6535static int
6536env_update_block_i(VALUE key, VALUE val, VALUE _)
6537{
6538 VALUE oldval = rb_f_getenv(Qnil, key);
6539 if (!NIL_P(oldval)) {
6540 val = rb_yield_values(3, key, oldval, val);
6541 }
6542 env_aset(key, val);
6543 return ST_CONTINUE;
6544}
6545
6546/*
6547 * call-seq:
6548 * ENV.update -> ENV
6549 * ENV.update(*hashes) -> ENV
6550 * ENV.update(*hashes) { |name, env_val, hash_val| block } -> ENV
6551 * ENV.merge! -> ENV
6552 * ENV.merge!(*hashes) -> ENV
6553 * ENV.merge!(*hashes) { |name, env_val, hash_val| block } -> ENV
6554 *
6555 * Adds to ENV each key/value pair in the given +hash+; returns ENV:
6556 * ENV.replace('foo' => '0', 'bar' => '1')
6557 * ENV.merge!('baz' => '2', 'bat' => '3') # => {"bar"=>"1", "bat"=>"3", "baz"=>"2", "foo"=>"0"}
6558 * Deletes the ENV entry for a hash value that is +nil+:
6559 * ENV.merge!('baz' => nil, 'bat' => nil) # => {"bar"=>"1", "foo"=>"0"}
6560 * For an already-existing name, if no block given, overwrites the ENV value:
6561 * ENV.merge!('foo' => '4') # => {"bar"=>"1", "foo"=>"4"}
6562 * For an already-existing name, if block given,
6563 * yields the name, its ENV value, and its hash value;
6564 * the block's return value becomes the new name:
6565 * ENV.merge!('foo' => '5') { |name, env_val, hash_val | env_val + hash_val } # => {"bar"=>"1", "foo"=>"45"}
6566 * Raises an exception if a name or value is invalid
6567 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]);
6568 * ENV.replace('foo' => '0', 'bar' => '1')
6569 * ENV.merge!('foo' => '6', :bar => '7', 'baz' => '9') # Raises TypeError (no implicit conversion of Symbol into String)
6570 * ENV # => {"bar"=>"1", "foo"=>"6"}
6571 * ENV.merge!('foo' => '7', 'bar' => 8, 'baz' => '9') # Raises TypeError (no implicit conversion of Integer into String)
6572 * ENV # => {"bar"=>"1", "foo"=>"7"}
6573 * Raises an exception if the block returns an invalid name:
6574 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
6575 * ENV.merge!('bat' => '8', 'foo' => '9') { |name, env_val, hash_val | 10 } # Raises TypeError (no implicit conversion of Integer into String)
6576 * ENV # => {"bar"=>"1", "bat"=>"8", "foo"=>"7"}
6577 *
6578 * Note that for the exceptions above,
6579 * hash pairs preceding an invalid name or value are processed normally;
6580 * those following are ignored.
6581 */
6582static VALUE
6583env_update(int argc, VALUE *argv, VALUE env)
6584{
6585 rb_foreach_func *func = rb_block_given_p() ?
6586 env_update_block_i : env_update_i;
6587 for (int i = 0; i < argc; ++i) {
6588 VALUE hash = argv[i];
6589 if (env == hash) continue;
6590 hash = to_hash(hash);
6591 rb_hash_foreach(hash, func, 0);
6592 }
6593 return env;
6594}
6595
6596NORETURN(static VALUE env_clone(int, VALUE *, VALUE));
6597/*
6598 * call-seq:
6599 * ENV.clone(freeze: nil) # raises TypeError
6600 *
6601 * Raises TypeError, because ENV is a wrapper for the process-wide
6602 * environment variables and a clone is useless.
6603 * Use #to_h to get a copy of ENV data as a hash.
6604 */
6605static VALUE
6606env_clone(int argc, VALUE *argv, VALUE obj)
6607{
6608 if (argc) {
6609 VALUE opt;
6610 if (rb_scan_args(argc, argv, "0:", &opt) < argc) {
6611 rb_get_freeze_opt(1, &opt);
6612 }
6613 }
6614
6615 rb_raise(rb_eTypeError, "Cannot clone ENV, use ENV.to_h to get a copy of ENV as a hash");
6616}
6617
6618NORETURN(static VALUE env_dup(VALUE));
6619/*
6620 * call-seq:
6621 * ENV.dup # raises TypeError
6622 *
6623 * Raises TypeError, because ENV is a singleton object.
6624 * Use #to_h to get a copy of ENV data as a hash.
6625 */
6626static VALUE
6627env_dup(VALUE obj)
6628{
6629 rb_raise(rb_eTypeError, "Cannot dup ENV, use ENV.to_h to get a copy of ENV as a hash");
6630}
6631
6632static const rb_data_type_t env_data_type = {
6633 "ENV",
6634 {
6635 NULL,
6636 NULL,
6637 NULL,
6638 NULL,
6639 },
6640 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
6641};
6642
6643/*
6644 * A +Hash+ maps each of its unique keys to a specific value.
6645 *
6646 * A +Hash+ has certain similarities to an Array, but:
6647 * - An Array index is always an Integer.
6648 * - A +Hash+ key can be (almost) any object.
6649 *
6650 * === +Hash+ \Data Syntax
6651 *
6652 * The older syntax for +Hash+ data uses the "hash rocket," <tt>=></tt>:
6653 *
6654 * h = {:foo => 0, :bar => 1, :baz => 2}
6655 * h # => {:foo=>0, :bar=>1, :baz=>2}
6656 *
6657 * Alternatively, but only for a +Hash+ key that's a Symbol,
6658 * you can use a newer JSON-style syntax,
6659 * where each bareword becomes a Symbol:
6660 *
6661 * h = {foo: 0, bar: 1, baz: 2}
6662 * h # => {:foo=>0, :bar=>1, :baz=>2}
6663 *
6664 * You can also use a String in place of a bareword:
6665 *
6666 * h = {'foo': 0, 'bar': 1, 'baz': 2}
6667 * h # => {:foo=>0, :bar=>1, :baz=>2}
6668 *
6669 * And you can mix the styles:
6670 *
6671 * h = {foo: 0, :bar => 1, 'baz': 2}
6672 * h # => {:foo=>0, :bar=>1, :baz=>2}
6673 *
6674 * But it's an error to try the JSON-style syntax
6675 * for a key that's not a bareword or a String:
6676 *
6677 * # Raises SyntaxError (syntax error, unexpected ':', expecting =>):
6678 * h = {0: 'zero'}
6679 *
6680 * +Hash+ value can be omitted, meaning that value will be fetched from the context
6681 * by the name of the key:
6682 *
6683 * x = 0
6684 * y = 100
6685 * h = {x:, y:}
6686 * h # => {:x=>0, :y=>100}
6687 *
6688 * === Common Uses
6689 *
6690 * You can use a +Hash+ to give names to objects:
6691 *
6692 * person = {name: 'Matz', language: 'Ruby'}
6693 * person # => {:name=>"Matz", :language=>"Ruby"}
6694 *
6695 * You can use a +Hash+ to give names to method arguments:
6696 *
6697 * def some_method(hash)
6698 * p hash
6699 * end
6700 * some_method({foo: 0, bar: 1, baz: 2}) # => {:foo=>0, :bar=>1, :baz=>2}
6701 *
6702 * Note: when the last argument in a method call is a +Hash+,
6703 * the curly braces may be omitted:
6704 *
6705 * some_method(foo: 0, bar: 1, baz: 2) # => {:foo=>0, :bar=>1, :baz=>2}
6706 *
6707 * You can use a +Hash+ to initialize an object:
6708 *
6709 * class Dev
6710 * attr_accessor :name, :language
6711 * def initialize(hash)
6712 * self.name = hash[:name]
6713 * self.language = hash[:language]
6714 * end
6715 * end
6716 * matz = Dev.new(name: 'Matz', language: 'Ruby')
6717 * matz # => #<Dev: @name="Matz", @language="Ruby">
6718 *
6719 * === Creating a +Hash+
6720 *
6721 * You can create a +Hash+ object explicitly with:
6722 *
6723 * - A {hash literal}[rdoc-ref:syntax/literals.rdoc@Hash+Literals].
6724 *
6725 * You can convert certain objects to Hashes with:
6726 *
6727 * - \Method #Hash.
6728 *
6729 * You can create a +Hash+ by calling method Hash.new.
6730 *
6731 * Create an empty +Hash+:
6732 *
6733 * h = Hash.new
6734 * h # => {}
6735 * h.class # => Hash
6736 *
6737 * You can create a +Hash+ by calling method Hash.[].
6738 *
6739 * Create an empty +Hash+:
6740 *
6741 * h = Hash[]
6742 * h # => {}
6743 *
6744 * Create a +Hash+ with initial entries:
6745 *
6746 * h = Hash[foo: 0, bar: 1, baz: 2]
6747 * h # => {:foo=>0, :bar=>1, :baz=>2}
6748 *
6749 * You can create a +Hash+ by using its literal form (curly braces).
6750 *
6751 * Create an empty +Hash+:
6752 *
6753 * h = {}
6754 * h # => {}
6755 *
6756 * Create a +Hash+ with initial entries:
6757 *
6758 * h = {foo: 0, bar: 1, baz: 2}
6759 * h # => {:foo=>0, :bar=>1, :baz=>2}
6760 *
6761 *
6762 * === +Hash+ Value Basics
6763 *
6764 * The simplest way to retrieve a +Hash+ value (instance method #[]):
6765 *
6766 * h = {foo: 0, bar: 1, baz: 2}
6767 * h[:foo] # => 0
6768 *
6769 * The simplest way to create or update a +Hash+ value (instance method #[]=):
6770 *
6771 * h = {foo: 0, bar: 1, baz: 2}
6772 * h[:bat] = 3 # => 3
6773 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
6774 * h[:foo] = 4 # => 4
6775 * h # => {:foo=>4, :bar=>1, :baz=>2, :bat=>3}
6776 *
6777 * The simplest way to delete a +Hash+ entry (instance method #delete):
6778 *
6779 * h = {foo: 0, bar: 1, baz: 2}
6780 * h.delete(:bar) # => 1
6781 * h # => {:foo=>0, :baz=>2}
6782 *
6783 * === Entry Order
6784 *
6785 * A +Hash+ object presents its entries in the order of their creation. This is seen in:
6786 *
6787 * - Iterative methods such as <tt>each</tt>, <tt>each_key</tt>, <tt>each_pair</tt>, <tt>each_value</tt>.
6788 * - Other order-sensitive methods such as <tt>shift</tt>, <tt>keys</tt>, <tt>values</tt>.
6789 * - The String returned by method <tt>inspect</tt>.
6790 *
6791 * A new +Hash+ has its initial ordering per the given entries:
6792 *
6793 * h = Hash[foo: 0, bar: 1]
6794 * h # => {:foo=>0, :bar=>1}
6795 *
6796 * New entries are added at the end:
6797 *
6798 * h[:baz] = 2
6799 * h # => {:foo=>0, :bar=>1, :baz=>2}
6800 *
6801 * Updating a value does not affect the order:
6802 *
6803 * h[:baz] = 3
6804 * h # => {:foo=>0, :bar=>1, :baz=>3}
6805 *
6806 * But re-creating a deleted entry can affect the order:
6807 *
6808 * h.delete(:foo)
6809 * h[:foo] = 5
6810 * h # => {:bar=>1, :baz=>3, :foo=>5}
6811 *
6812 * === +Hash+ Keys
6813 *
6814 * ==== +Hash+ Key Equivalence
6815 *
6816 * Two objects are treated as the same \hash key when their <code>hash</code> value
6817 * is identical and the two objects are <code>eql?</code> to each other.
6818 *
6819 * ==== Modifying an Active +Hash+ Key
6820 *
6821 * Modifying a +Hash+ key while it is in use damages the hash's index.
6822 *
6823 * This +Hash+ has keys that are Arrays:
6824 *
6825 * a0 = [ :foo, :bar ]
6826 * a1 = [ :baz, :bat ]
6827 * h = {a0 => 0, a1 => 1}
6828 * h.include?(a0) # => true
6829 * h[a0] # => 0
6830 * a0.hash # => 110002110
6831 *
6832 * Modifying array element <tt>a0[0]</tt> changes its hash value:
6833 *
6834 * a0[0] = :bam
6835 * a0.hash # => 1069447059
6836 *
6837 * And damages the +Hash+ index:
6838 *
6839 * h.include?(a0) # => false
6840 * h[a0] # => nil
6841 *
6842 * You can repair the hash index using method +rehash+:
6843 *
6844 * h.rehash # => {[:bam, :bar]=>0, [:baz, :bat]=>1}
6845 * h.include?(a0) # => true
6846 * h[a0] # => 0
6847 *
6848 * A String key is always safe.
6849 * That's because an unfrozen String
6850 * passed as a key will be replaced by a duplicated and frozen String:
6851 *
6852 * s = 'foo'
6853 * s.frozen? # => false
6854 * h = {s => 0}
6855 * first_key = h.keys.first
6856 * first_key.frozen? # => true
6857 *
6858 * ==== User-Defined +Hash+ Keys
6859 *
6860 * To be usable as a +Hash+ key, objects must implement the methods <code>hash</code> and <code>eql?</code>.
6861 * Note: this requirement does not apply if the +Hash+ uses #compare_by_identity since comparison will then
6862 * rely on the keys' object id instead of <code>hash</code> and <code>eql?</code>.
6863 *
6864 * Object defines basic implementation for <code>hash</code> and <code>eq?</code> that makes each object
6865 * a distinct key. Typically, user-defined classes will want to override these methods to provide meaningful
6866 * behavior, or for example inherit Struct that has useful definitions for these.
6867 *
6868 * A typical implementation of <code>hash</code> is based on the
6869 * object's data while <code>eql?</code> is usually aliased to the overridden
6870 * <code>==</code> method:
6871 *
6872 * class Book
6873 * attr_reader :author, :title
6874 *
6875 * def initialize(author, title)
6876 * @author = author
6877 * @title = title
6878 * end
6879 *
6880 * def ==(other)
6881 * self.class === other &&
6882 * other.author == @author &&
6883 * other.title == @title
6884 * end
6885 *
6886 * alias eql? ==
6887 *
6888 * def hash
6889 * [self.class, @author, @title].hash
6890 * end
6891 * end
6892 *
6893 * book1 = Book.new 'matz', 'Ruby in a Nutshell'
6894 * book2 = Book.new 'matz', 'Ruby in a Nutshell'
6895 *
6896 * reviews = {}
6897 *
6898 * reviews[book1] = 'Great reference!'
6899 * reviews[book2] = 'Nice and compact!'
6900 *
6901 * reviews.length #=> 1
6902 *
6903 * === Default Values
6904 *
6905 * The methods #[], #values_at and #dig need to return the value associated to a certain key.
6906 * When that key is not found, that value will be determined by its default proc (if any)
6907 * or else its default (initially `nil`).
6908 *
6909 * You can retrieve the default value with method #default:
6910 *
6911 * h = Hash.new
6912 * h.default # => nil
6913 *
6914 * You can set the default value by passing an argument to method Hash.new or
6915 * with method #default=
6916 *
6917 * h = Hash.new(-1)
6918 * h.default # => -1
6919 * h.default = 0
6920 * h.default # => 0
6921 *
6922 * This default value is returned for #[], #values_at and #dig when a key is
6923 * not found:
6924 *
6925 * counts = {foo: 42}
6926 * counts.default # => nil (default)
6927 * counts[:foo] = 42
6928 * counts[:bar] # => nil
6929 * counts.default = 0
6930 * counts[:bar] # => 0
6931 * counts.values_at(:foo, :bar, :baz) # => [42, 0, 0]
6932 * counts.dig(:bar) # => 0
6933 *
6934 * Note that the default value is used without being duplicated. It is not advised to set
6935 * the default value to a mutable object:
6936 *
6937 * synonyms = Hash.new([])
6938 * synonyms[:hello] # => []
6939 * synonyms[:hello] << :hi # => [:hi], but this mutates the default!
6940 * synonyms.default # => [:hi]
6941 * synonyms[:world] << :universe
6942 * synonyms[:world] # => [:hi, :universe], oops
6943 * synonyms.keys # => [], oops
6944 *
6945 * To use a mutable object as default, it is recommended to use a default proc
6946 *
6947 * ==== Default Proc
6948 *
6949 * When the default proc for a +Hash+ is set (i.e., not +nil+),
6950 * the default value returned by method #[] is determined by the default proc alone.
6951 *
6952 * You can retrieve the default proc with method #default_proc:
6953 *
6954 * h = Hash.new
6955 * h.default_proc # => nil
6956 *
6957 * You can set the default proc by calling Hash.new with a block or
6958 * calling the method #default_proc=
6959 *
6960 * h = Hash.new { |hash, key| "Default value for #{key}" }
6961 * h.default_proc.class # => Proc
6962 * h.default_proc = proc { |hash, key| "Default value for #{key.inspect}" }
6963 * h.default_proc.class # => Proc
6964 *
6965 * When the default proc is set (i.e., not +nil+)
6966 * and method #[] is called with with a non-existent key,
6967 * #[] calls the default proc with both the +Hash+ object itself and the missing key,
6968 * then returns the proc's return value:
6969 *
6970 * h = Hash.new { |hash, key| "Default value for #{key}" }
6971 * h[:nosuch] # => "Default value for nosuch"
6972 *
6973 * Note that in the example above no entry for key +:nosuch+ is created:
6974 *
6975 * h.include?(:nosuch) # => false
6976 *
6977 * However, the proc itself can add a new entry:
6978 *
6979 * synonyms = Hash.new { |hash, key| hash[key] = [] }
6980 * synonyms.include?(:hello) # => false
6981 * synonyms[:hello] << :hi # => [:hi]
6982 * synonyms[:world] << :universe # => [:universe]
6983 * synonyms.keys # => [:hello, :world]
6984 *
6985 * Note that setting the default proc will clear the default value and vice versa.
6986 *
6987 * Be aware that a default proc that modifies the hash is not thread-safe in the
6988 * sense that multiple threads can call into the default proc concurrently for the
6989 * same key.
6990 *
6991 * === What's Here
6992 *
6993 * First, what's elsewhere. \Class +Hash+:
6994 *
6995 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
6996 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
6997 * which provides dozens of additional methods.
6998 *
6999 * Here, class +Hash+ provides methods that are useful for:
7000 *
7001 * - {Creating a Hash}[rdoc-ref:Hash@Methods+for+Creating+a+Hash]
7002 * - {Setting Hash State}[rdoc-ref:Hash@Methods+for+Setting+Hash+State]
7003 * - {Querying}[rdoc-ref:Hash@Methods+for+Querying]
7004 * - {Comparing}[rdoc-ref:Hash@Methods+for+Comparing]
7005 * - {Fetching}[rdoc-ref:Hash@Methods+for+Fetching]
7006 * - {Assigning}[rdoc-ref:Hash@Methods+for+Assigning]
7007 * - {Deleting}[rdoc-ref:Hash@Methods+for+Deleting]
7008 * - {Iterating}[rdoc-ref:Hash@Methods+for+Iterating]
7009 * - {Converting}[rdoc-ref:Hash@Methods+for+Converting]
7010 * - {Transforming Keys and Values}[rdoc-ref:Hash@Methods+for+Transforming+Keys+and+Values]
7011 * - {And more....}[rdoc-ref:Hash@Other+Methods]
7012 *
7013 * \Class +Hash+ also includes methods from module Enumerable.
7014 *
7015 * ==== Methods for Creating a +Hash+
7016 *
7017 * - ::[]: Returns a new hash populated with given objects.
7018 * - ::new: Returns a new empty hash.
7019 * - ::try_convert: Returns a new hash created from a given object.
7020 *
7021 * ==== Methods for Setting +Hash+ State
7022 *
7023 * - #compare_by_identity: Sets +self+ to consider only identity in comparing keys.
7024 * - #default=: Sets the default to a given value.
7025 * - #default_proc=: Sets the default proc to a given proc.
7026 * - #rehash: Rebuilds the hash table by recomputing the hash index for each key.
7027 *
7028 * ==== Methods for Querying
7029 *
7030 * - #any?: Returns whether any element satisfies a given criterion.
7031 * - #compare_by_identity?: Returns whether the hash considers only identity when comparing keys.
7032 * - #default: Returns the default value, or the default value for a given key.
7033 * - #default_proc: Returns the default proc.
7034 * - #empty?: Returns whether there are no entries.
7035 * - #eql?: Returns whether a given object is equal to +self+.
7036 * - #hash: Returns the integer hash code.
7037 * - #has_value? (aliased as #value?): Returns whether a given object is a value in +self+.
7038 * - #include? (aliased as #has_key?, #member?, #key?): Returns whether a given object is a key in +self+.
7039 * - #size (aliased as #length): Returns the count of entries.
7040 *
7041 * ==== Methods for Comparing
7042 *
7043 * - #<: Returns whether +self+ is a proper subset of a given object.
7044 * - #<=: Returns whether +self+ is a subset of a given object.
7045 * - #==: Returns whether a given object is equal to +self+.
7046 * - #>: Returns whether +self+ is a proper superset of a given object
7047 * - #>=: Returns whether +self+ is a superset of a given object.
7048 *
7049 * ==== Methods for Fetching
7050 *
7051 * - #[]: Returns the value associated with a given key.
7052 * - #assoc: Returns a 2-element array containing a given key and its value.
7053 * - #dig: Returns the object in nested objects that is specified
7054 * by a given key and additional arguments.
7055 * - #fetch: Returns the value for a given key.
7056 * - #fetch_values: Returns array containing the values associated with given keys.
7057 * - #key: Returns the key for the first-found entry with a given value.
7058 * - #keys: Returns an array containing all keys in +self+.
7059 * - #rassoc: Returns a 2-element array consisting of the key and value
7060 * of the first-found entry having a given value.
7061 * - #values: Returns an array containing all values in +self+/
7062 * - #values_at: Returns an array containing values for given keys.
7063 *
7064 * ==== Methods for Assigning
7065 *
7066 * - #[]= (aliased as #store): Associates a given key with a given value.
7067 * - #merge: Returns the hash formed by merging each given hash into a copy of +self+.
7068 * - #update (aliased as #merge!): Merges each given hash into +self+.
7069 * - #replace (aliased as #initialize_copy): Replaces the entire contents of +self+ with the contents of a given hash.
7070 *
7071 * ==== Methods for Deleting
7072 *
7073 * These methods remove entries from +self+:
7074 *
7075 * - #clear: Removes all entries from +self+.
7076 * - #compact!: Removes all +nil+-valued entries from +self+.
7077 * - #delete: Removes the entry for a given key.
7078 * - #delete_if: Removes entries selected by a given block.
7079 * - #select! (aliased as #filter!): Keep only those entries selected by a given block.
7080 * - #keep_if: Keep only those entries selected by a given block.
7081 * - #reject!: Removes entries selected by a given block.
7082 * - #shift: Removes and returns the first entry.
7083 *
7084 * These methods return a copy of +self+ with some entries removed:
7085 *
7086 * - #compact: Returns a copy of +self+ with all +nil+-valued entries removed.
7087 * - #except: Returns a copy of +self+ with entries removed for specified keys.
7088 * - #select (aliased as #filter): Returns a copy of +self+ with only those entries selected by a given block.
7089 * - #reject: Returns a copy of +self+ with entries removed as specified by a given block.
7090 * - #slice: Returns a hash containing the entries for given keys.
7091 *
7092 * ==== Methods for Iterating
7093 * - #each_pair (aliased as #each): Calls a given block with each key-value pair.
7094 * - #each_key: Calls a given block with each key.
7095 * - #each_value: Calls a given block with each value.
7096 *
7097 * ==== Methods for Converting
7098 *
7099 * - #inspect (aliased as #to_s): Returns a new String containing the hash entries.
7100 * - #to_a: Returns a new array of 2-element arrays;
7101 * each nested array contains a key-value pair from +self+.
7102 * - #to_h: Returns +self+ if a +Hash+;
7103 * if a subclass of +Hash+, returns a +Hash+ containing the entries from +self+.
7104 * - #to_hash: Returns +self+.
7105 * - #to_proc: Returns a proc that maps a given key to its value.
7106 *
7107 * ==== Methods for Transforming Keys and Values
7108 *
7109 * - #transform_keys: Returns a copy of +self+ with modified keys.
7110 * - #transform_keys!: Modifies keys in +self+
7111 * - #transform_values: Returns a copy of +self+ with modified values.
7112 * - #transform_values!: Modifies values in +self+.
7113 *
7114 * ==== Other Methods
7115 * - #flatten: Returns an array that is a 1-dimensional flattening of +self+.
7116 * - #invert: Returns a hash with the each key-value pair inverted.
7117 *
7118 */
7119
7120void
7121Init_Hash(void)
7122{
7123 id_hash = rb_intern_const("hash");
7124 id_flatten_bang = rb_intern_const("flatten!");
7125 id_hash_iter_lev = rb_make_internal_id();
7126
7127 rb_cHash = rb_define_class("Hash", rb_cObject);
7128
7129 rb_include_module(rb_cHash, rb_mEnumerable);
7130
7131 rb_define_alloc_func(rb_cHash, empty_hash_alloc);
7132 rb_define_singleton_method(rb_cHash, "[]", rb_hash_s_create, -1);
7133 rb_define_singleton_method(rb_cHash, "try_convert", rb_hash_s_try_convert, 1);
7134 rb_define_method(rb_cHash, "initialize_copy", rb_hash_replace, 1);
7135 rb_define_method(rb_cHash, "rehash", rb_hash_rehash, 0);
7136 rb_define_method(rb_cHash, "freeze", rb_hash_freeze, 0);
7137
7138 rb_define_method(rb_cHash, "to_hash", rb_hash_to_hash, 0);
7139 rb_define_method(rb_cHash, "to_h", rb_hash_to_h, 0);
7140 rb_define_method(rb_cHash, "to_a", rb_hash_to_a, 0);
7141 rb_define_method(rb_cHash, "inspect", rb_hash_inspect, 0);
7142 rb_define_alias(rb_cHash, "to_s", "inspect");
7143 rb_define_method(rb_cHash, "to_proc", rb_hash_to_proc, 0);
7144
7145 rb_define_method(rb_cHash, "==", rb_hash_equal, 1);
7146 rb_define_method(rb_cHash, "[]", rb_hash_aref, 1);
7147 rb_define_method(rb_cHash, "hash", rb_hash_hash, 0);
7148 rb_define_method(rb_cHash, "eql?", rb_hash_eql, 1);
7149 rb_define_method(rb_cHash, "fetch", rb_hash_fetch_m, -1);
7150 rb_define_method(rb_cHash, "[]=", rb_hash_aset, 2);
7151 rb_define_method(rb_cHash, "store", rb_hash_aset, 2);
7152 rb_define_method(rb_cHash, "default", rb_hash_default, -1);
7153 rb_define_method(rb_cHash, "default=", rb_hash_set_default, 1);
7154 rb_define_method(rb_cHash, "default_proc", rb_hash_default_proc, 0);
7155 rb_define_method(rb_cHash, "default_proc=", rb_hash_set_default_proc, 1);
7156 rb_define_method(rb_cHash, "key", rb_hash_key, 1);
7157 rb_define_method(rb_cHash, "size", rb_hash_size, 0);
7158 rb_define_method(rb_cHash, "length", rb_hash_size, 0);
7159 rb_define_method(rb_cHash, "empty?", rb_hash_empty_p, 0);
7160
7161 rb_define_method(rb_cHash, "each_value", rb_hash_each_value, 0);
7162 rb_define_method(rb_cHash, "each_key", rb_hash_each_key, 0);
7163 rb_define_method(rb_cHash, "each_pair", rb_hash_each_pair, 0);
7164 rb_define_method(rb_cHash, "each", rb_hash_each_pair, 0);
7165
7166 rb_define_method(rb_cHash, "transform_keys", rb_hash_transform_keys, -1);
7167 rb_define_method(rb_cHash, "transform_keys!", rb_hash_transform_keys_bang, -1);
7168 rb_define_method(rb_cHash, "transform_values", rb_hash_transform_values, 0);
7169 rb_define_method(rb_cHash, "transform_values!", rb_hash_transform_values_bang, 0);
7170
7171 rb_define_method(rb_cHash, "keys", rb_hash_keys, 0);
7172 rb_define_method(rb_cHash, "values", rb_hash_values, 0);
7173 rb_define_method(rb_cHash, "values_at", rb_hash_values_at, -1);
7174 rb_define_method(rb_cHash, "fetch_values", rb_hash_fetch_values, -1);
7175
7176 rb_define_method(rb_cHash, "shift", rb_hash_shift, 0);
7177 rb_define_method(rb_cHash, "delete", rb_hash_delete_m, 1);
7178 rb_define_method(rb_cHash, "delete_if", rb_hash_delete_if, 0);
7179 rb_define_method(rb_cHash, "keep_if", rb_hash_keep_if, 0);
7180 rb_define_method(rb_cHash, "select", rb_hash_select, 0);
7181 rb_define_method(rb_cHash, "select!", rb_hash_select_bang, 0);
7182 rb_define_method(rb_cHash, "filter", rb_hash_select, 0);
7183 rb_define_method(rb_cHash, "filter!", rb_hash_select_bang, 0);
7184 rb_define_method(rb_cHash, "reject", rb_hash_reject, 0);
7185 rb_define_method(rb_cHash, "reject!", rb_hash_reject_bang, 0);
7186 rb_define_method(rb_cHash, "slice", rb_hash_slice, -1);
7187 rb_define_method(rb_cHash, "except", rb_hash_except, -1);
7188 rb_define_method(rb_cHash, "clear", rb_hash_clear, 0);
7189 rb_define_method(rb_cHash, "invert", rb_hash_invert, 0);
7190 rb_define_method(rb_cHash, "update", rb_hash_update, -1);
7191 rb_define_method(rb_cHash, "replace", rb_hash_replace, 1);
7192 rb_define_method(rb_cHash, "merge!", rb_hash_update, -1);
7193 rb_define_method(rb_cHash, "merge", rb_hash_merge, -1);
7194 rb_define_method(rb_cHash, "assoc", rb_hash_assoc, 1);
7195 rb_define_method(rb_cHash, "rassoc", rb_hash_rassoc, 1);
7196 rb_define_method(rb_cHash, "flatten", rb_hash_flatten, -1);
7197 rb_define_method(rb_cHash, "compact", rb_hash_compact, 0);
7198 rb_define_method(rb_cHash, "compact!", rb_hash_compact_bang, 0);
7199
7200 rb_define_method(rb_cHash, "include?", rb_hash_has_key, 1);
7201 rb_define_method(rb_cHash, "member?", rb_hash_has_key, 1);
7202 rb_define_method(rb_cHash, "has_key?", rb_hash_has_key, 1);
7203 rb_define_method(rb_cHash, "has_value?", rb_hash_has_value, 1);
7204 rb_define_method(rb_cHash, "key?", rb_hash_has_key, 1);
7205 rb_define_method(rb_cHash, "value?", rb_hash_has_value, 1);
7206
7207 rb_define_method(rb_cHash, "compare_by_identity", rb_hash_compare_by_id, 0);
7208 rb_define_method(rb_cHash, "compare_by_identity?", rb_hash_compare_by_id_p, 0);
7209
7210 rb_define_method(rb_cHash, "any?", rb_hash_any_p, -1);
7211 rb_define_method(rb_cHash, "dig", rb_hash_dig, -1);
7212
7213 rb_define_method(rb_cHash, "<=", rb_hash_le, 1);
7214 rb_define_method(rb_cHash, "<", rb_hash_lt, 1);
7215 rb_define_method(rb_cHash, ">=", rb_hash_ge, 1);
7216 rb_define_method(rb_cHash, ">", rb_hash_gt, 1);
7217
7218 rb_define_method(rb_cHash, "deconstruct_keys", rb_hash_deconstruct_keys, 1);
7219
7220 rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash?", rb_hash_s_ruby2_keywords_hash_p, 1);
7221 rb_define_singleton_method(rb_cHash, "ruby2_keywords_hash", rb_hash_s_ruby2_keywords_hash, 1);
7222
7223 rb_cHash_empty_frozen = rb_hash_freeze(rb_hash_new());
7224 rb_vm_register_global_object(rb_cHash_empty_frozen);
7225
7226 /* Document-class: ENV
7227 *
7228 * +ENV+ is a hash-like accessor for environment variables.
7229 *
7230 * === Interaction with the Operating System
7231 *
7232 * The +ENV+ object interacts with the operating system's environment variables:
7233 *
7234 * - When you get the value for a name in +ENV+, the value is retrieved from among the current environment variables.
7235 * - When you create or set a name-value pair in +ENV+, the name and value are immediately set in the environment variables.
7236 * - When you delete a name-value pair in +ENV+, it is immediately deleted from the environment variables.
7237 *
7238 * === Names and Values
7239 *
7240 * Generally, a name or value is a String.
7241 *
7242 * ==== Valid Names and Values
7243 *
7244 * Each name or value must be one of the following:
7245 *
7246 * - A String.
7247 * - An object that responds to \#to_str by returning a String, in which case that String will be used as the name or value.
7248 *
7249 * ==== Invalid Names and Values
7250 *
7251 * A new name:
7252 *
7253 * - May not be the empty string:
7254 * ENV[''] = '0'
7255 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv())
7256 *
7257 * - May not contain character <code>"="</code>:
7258 * ENV['='] = '0'
7259 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv(=))
7260 *
7261 * A new name or value:
7262 *
7263 * - May not be a non-String that does not respond to \#to_str:
7264 *
7265 * ENV['foo'] = Object.new
7266 * # Raises TypeError (no implicit conversion of Object into String)
7267 * ENV[Object.new] = '0'
7268 * # Raises TypeError (no implicit conversion of Object into String)
7269 *
7270 * - May not contain the NUL character <code>"\0"</code>:
7271 *
7272 * ENV['foo'] = "\0"
7273 * # Raises ArgumentError (bad environment variable value: contains null byte)
7274 * ENV["\0"] == '0'
7275 * # Raises ArgumentError (bad environment variable name: contains null byte)
7276 *
7277 * - May not have an ASCII-incompatible encoding such as UTF-16LE or ISO-2022-JP:
7278 *
7279 * ENV['foo'] = '0'.force_encoding(Encoding::ISO_2022_JP)
7280 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7281 * ENV["foo".force_encoding(Encoding::ISO_2022_JP)] = '0'
7282 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7283 *
7284 * === About Ordering
7285 *
7286 * +ENV+ enumerates its name/value pairs in the order found
7287 * in the operating system's environment variables.
7288 * Therefore the ordering of +ENV+ content is OS-dependent, and may be indeterminate.
7289 *
7290 * This will be seen in:
7291 * - A Hash returned by an +ENV+ method.
7292 * - An Enumerator returned by an +ENV+ method.
7293 * - An Array returned by ENV.keys, ENV.values, or ENV.to_a.
7294 * - The String returned by ENV.inspect.
7295 * - The Array returned by ENV.shift.
7296 * - The name returned by ENV.key.
7297 *
7298 * === About the Examples
7299 * Some methods in +ENV+ return +ENV+ itself. Typically, there are many environment variables.
7300 * It's not useful to display a large +ENV+ in the examples here,
7301 * so most example snippets begin by resetting the contents of +ENV+:
7302 * - ENV.replace replaces +ENV+ with a new collection of entries.
7303 * - ENV.clear empties +ENV+.
7304 *
7305 * === What's Here
7306 *
7307 * First, what's elsewhere. \Class +ENV+:
7308 *
7309 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
7310 * - Extends {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
7311 *
7312 * Here, class +ENV+ provides methods that are useful for:
7313 *
7314 * - {Querying}[rdoc-ref:ENV@Methods+for+Querying]
7315 * - {Assigning}[rdoc-ref:ENV@Methods+for+Assigning]
7316 * - {Deleting}[rdoc-ref:ENV@Methods+for+Deleting]
7317 * - {Iterating}[rdoc-ref:ENV@Methods+for+Iterating]
7318 * - {Converting}[rdoc-ref:ENV@Methods+for+Converting]
7319 * - {And more ....}[rdoc-ref:ENV@More+Methods]
7320 *
7321 * ==== Methods for Querying
7322 *
7323 * - ::[]: Returns the value for the given environment variable name if it exists:
7324 * - ::empty?: Returns whether +ENV+ is empty.
7325 * - ::has_value?, ::value?: Returns whether the given value is in +ENV+.
7326 * - ::include?, ::has_key?, ::key?, ::member?: Returns whether the given name
7327 is in +ENV+.
7328 * - ::key: Returns the name of the first entry with the given value.
7329 * - ::size, ::length: Returns the number of entries.
7330 * - ::value?: Returns whether any entry has the given value.
7331 *
7332 * ==== Methods for Assigning
7333 *
7334 * - ::[]=, ::store: Creates, updates, or deletes the named environment variable.
7335 * - ::clear: Removes every environment variable; returns +ENV+:
7336 * - ::update, ::merge!: Adds to +ENV+ each key/value pair in the given hash.
7337 * - ::replace: Replaces the entire content of the +ENV+
7338 * with the name/value pairs in the given hash.
7339 *
7340 * ==== Methods for Deleting
7341 *
7342 * - ::delete: Deletes the named environment variable name if it exists.
7343 * - ::delete_if: Deletes entries selected by the block.
7344 * - ::keep_if: Deletes entries not selected by the block.
7345 * - ::reject!: Similar to #delete_if, but returns +nil+ if no change was made.
7346 * - ::select!, ::filter!: Deletes entries selected by the block.
7347 * - ::shift: Removes and returns the first entry.
7348 *
7349 * ==== Methods for Iterating
7350 *
7351 * - ::each, ::each_pair: Calls the block with each name/value pair.
7352 * - ::each_key: Calls the block with each name.
7353 * - ::each_value: Calls the block with each value.
7354 *
7355 * ==== Methods for Converting
7356 *
7357 * - ::assoc: Returns a 2-element array containing the name and value
7358 * of the named environment variable if it exists:
7359 * - ::clone: Returns +ENV+ (and issues a warning).
7360 * - ::except: Returns a hash of all name/value pairs except those given.
7361 * - ::fetch: Returns the value for the given name.
7362 * - ::inspect: Returns the contents of +ENV+ as a string.
7363 * - ::invert: Returns a hash whose keys are the +ENV+ values,
7364 and whose values are the corresponding +ENV+ names.
7365 * - ::keys: Returns an array of all names.
7366 * - ::rassoc: Returns the name and value of the first found entry
7367 * that has the given value.
7368 * - ::reject: Returns a hash of those entries not rejected by the block.
7369 * - ::select, ::filter: Returns a hash of name/value pairs selected by the block.
7370 * - ::slice: Returns a hash of the given names and their corresponding values.
7371 * - ::to_a: Returns the entries as an array of 2-element Arrays.
7372 * - ::to_h: Returns a hash of entries selected by the block.
7373 * - ::to_hash: Returns a hash of all entries.
7374 * - ::to_s: Returns the string <tt>'ENV'</tt>.
7375 * - ::values: Returns all values as an array.
7376 * - ::values_at: Returns an array of the values for the given name.
7377 *
7378 * ==== More Methods
7379 *
7380 * - ::dup: Raises an exception.
7381 * - ::freeze: Raises an exception.
7382 * - ::rehash: Returns +nil+, without modifying +ENV+.
7383 *
7384 */
7385
7386 /*
7387 * Hack to get RDoc to regard ENV as a class:
7388 * envtbl = rb_define_class("ENV", rb_cObject);
7389 */
7390 origenviron = environ;
7391 envtbl = TypedData_Wrap_Struct(rb_cObject, &env_data_type, NULL);
7392 rb_extend_object(envtbl, rb_mEnumerable);
7393 FL_SET_RAW(envtbl, RUBY_FL_SHAREABLE);
7394
7395
7396 rb_define_singleton_method(envtbl, "[]", rb_f_getenv, 1);
7397 rb_define_singleton_method(envtbl, "fetch", env_fetch, -1);
7398 rb_define_singleton_method(envtbl, "[]=", env_aset_m, 2);
7399 rb_define_singleton_method(envtbl, "store", env_aset_m, 2);
7400 rb_define_singleton_method(envtbl, "each", env_each_pair, 0);
7401 rb_define_singleton_method(envtbl, "each_pair", env_each_pair, 0);
7402 rb_define_singleton_method(envtbl, "each_key", env_each_key, 0);
7403 rb_define_singleton_method(envtbl, "each_value", env_each_value, 0);
7404 rb_define_singleton_method(envtbl, "delete", env_delete_m, 1);
7405 rb_define_singleton_method(envtbl, "delete_if", env_delete_if, 0);
7406 rb_define_singleton_method(envtbl, "keep_if", env_keep_if, 0);
7407 rb_define_singleton_method(envtbl, "slice", env_slice, -1);
7408 rb_define_singleton_method(envtbl, "except", env_except, -1);
7409 rb_define_singleton_method(envtbl, "clear", env_clear, 0);
7410 rb_define_singleton_method(envtbl, "reject", env_reject, 0);
7411 rb_define_singleton_method(envtbl, "reject!", env_reject_bang, 0);
7412 rb_define_singleton_method(envtbl, "select", env_select, 0);
7413 rb_define_singleton_method(envtbl, "select!", env_select_bang, 0);
7414 rb_define_singleton_method(envtbl, "filter", env_select, 0);
7415 rb_define_singleton_method(envtbl, "filter!", env_select_bang, 0);
7416 rb_define_singleton_method(envtbl, "shift", env_shift, 0);
7417 rb_define_singleton_method(envtbl, "freeze", env_freeze, 0);
7418 rb_define_singleton_method(envtbl, "invert", env_invert, 0);
7419 rb_define_singleton_method(envtbl, "replace", env_replace, 1);
7420 rb_define_singleton_method(envtbl, "update", env_update, -1);
7421 rb_define_singleton_method(envtbl, "merge!", env_update, -1);
7422 rb_define_singleton_method(envtbl, "inspect", env_inspect, 0);
7423 rb_define_singleton_method(envtbl, "rehash", env_none, 0);
7424 rb_define_singleton_method(envtbl, "to_a", env_to_a, 0);
7425 rb_define_singleton_method(envtbl, "to_s", env_to_s, 0);
7426 rb_define_singleton_method(envtbl, "key", env_key, 1);
7427 rb_define_singleton_method(envtbl, "size", env_size, 0);
7428 rb_define_singleton_method(envtbl, "length", env_size, 0);
7429 rb_define_singleton_method(envtbl, "empty?", env_empty_p, 0);
7430 rb_define_singleton_method(envtbl, "keys", env_f_keys, 0);
7431 rb_define_singleton_method(envtbl, "values", env_f_values, 0);
7432 rb_define_singleton_method(envtbl, "values_at", env_values_at, -1);
7433 rb_define_singleton_method(envtbl, "include?", env_has_key, 1);
7434 rb_define_singleton_method(envtbl, "member?", env_has_key, 1);
7435 rb_define_singleton_method(envtbl, "has_key?", env_has_key, 1);
7436 rb_define_singleton_method(envtbl, "has_value?", env_has_value, 1);
7437 rb_define_singleton_method(envtbl, "key?", env_has_key, 1);
7438 rb_define_singleton_method(envtbl, "value?", env_has_value, 1);
7439 rb_define_singleton_method(envtbl, "to_hash", env_f_to_hash, 0);
7440 rb_define_singleton_method(envtbl, "to_h", env_to_h, 0);
7441 rb_define_singleton_method(envtbl, "assoc", env_assoc, 1);
7442 rb_define_singleton_method(envtbl, "rassoc", env_rassoc, 1);
7443 rb_define_singleton_method(envtbl, "clone", env_clone, -1);
7444 rb_define_singleton_method(envtbl, "dup", env_dup, 0);
7445
7446 VALUE envtbl_class = rb_singleton_class(envtbl);
7447 rb_undef_method(envtbl_class, "initialize");
7448 rb_undef_method(envtbl_class, "initialize_clone");
7449 rb_undef_method(envtbl_class, "initialize_copy");
7450 rb_undef_method(envtbl_class, "initialize_dup");
7451
7452 /*
7453 * +ENV+ is a Hash-like accessor for environment variables.
7454 *
7455 * See ENV (the class) for more details.
7456 */
7457 rb_define_global_const("ENV", envtbl);
7458
7459 HASH_ASSERT(sizeof(ar_hint_t) * RHASH_AR_TABLE_MAX_SIZE == sizeof(VALUE));
7460}
7461
7462#include "hash.rbinc"
RUBY_ASSERT
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
rb_define_method
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
Definition cxxanyargs.hpp:670
rb_define_singleton_method
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition cxxanyargs.hpp:685
RB_FL_ANY_RAW
static bool RB_FL_ANY_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_ANY().
Definition fl_type.h:518
RB_OBJ_FROZEN
static bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition fl_type.h:898
RUBY_FL_SHAREABLE
@ RUBY_FL_SHAREABLE
This flag has something to do with Ractor.
Definition fl_type.h:266
rb_include_module
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1187
rb_define_class
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:980
rb_extend_object
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition eval.c:1756
rb_singleton_class
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2302
rb_define_alias
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2350
rb_undef_method
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2171
rb_scan_args
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:2640
rb_block_given_p
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:937
TYPE
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
rb_str_buf_cat2
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1682
FL_EXIVAR
#define FL_EXIVAR
Old name of RUBY_FL_EXIVAR.
Definition fl_type.h:66
NUM2LL
#define NUM2LL
Old name of RB_NUM2LL.
Definition long_long.h:34
REALLOC_N
#define REALLOC_N
Old name of RB_REALLOC_N.
Definition memory.h:403
T_STRING
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
xfree
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
Qundef
#define Qundef
Old name of RUBY_Qundef.
Definition special_consts.h:62
INT2FIX
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
T_NIL
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
T_FLOAT
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
T_BIGNUM
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
rb_str_buf_new2
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition string.h:1679
T_FIXNUM
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
UNREACHABLE_RETURN
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
T_DATA
#define T_DATA
Old name of RUBY_T_DATA.
Definition value_type.h:60
CLASS_OF
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:203
LONG2FIX
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
STATIC_SYM_P
#define STATIC_SYM_P
Old name of RB_STATIC_SYM_P.
Definition special_consts.h:57
T_TRUE
#define T_TRUE
Old name of RUBY_T_TRUE.
Definition value_type.h:81
T_HASH
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
ALLOC_N
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
FL_TEST_RAW
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:132
rb_usascii_str_new2
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1680
T_FALSE
#define T_FALSE
Old name of RUBY_T_FALSE.
Definition value_type.h:61
FIXNUM_MIN
#define FIXNUM_MIN
Old name of RUBY_FIXNUM_MIN.
Definition fixnum.h:27
FLONUM_P
#define FLONUM_P
Old name of RB_FLONUM_P.
Definition special_consts.h:67
Qtrue
#define Qtrue
Old name of RUBY_Qtrue.
Definition special_consts.h:61
ST2FIX
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
FIXNUM_MAX
#define FIXNUM_MAX
Old name of RUBY_FIXNUM_MAX.
Definition fixnum.h:26
NUM2INT
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
Qnil
#define Qnil
Old name of RUBY_Qnil.
Definition special_consts.h:60
Qfalse
#define Qfalse
Old name of RUBY_Qfalse.
Definition special_consts.h:59
FIX2LONG
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
NIL_P
#define NIL_P
Old name of RB_NIL_P.
Definition special_consts.h:55
ALLOCV_N
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
FL_WB_PROTECTED
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
POSFIXABLE
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
T_SYMBOL
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
FL_TEST
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:131
NUM2LONG
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
FIXNUM_P
#define FIXNUM_P
Old name of RB_FIXNUM_P.
Definition special_consts.h:53
OBJ_WB_UNPROTECT
#define OBJ_WB_UNPROTECT
Old name of RB_OBJ_WB_UNPROTECT.
Definition gc.h:621
rb_ary_new2
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
FL_SET_RAW
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:130
ALLOCV_END
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
SYMBOL_P
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
rb_syserr_fail_str
void rb_syserr_fail_str(int e, VALUE mesg)
Identical to rb_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition error.c:3883
rb_eTypeError
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1430
rb_eRuntimeError
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1428
rb_warn
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
rb_ensure
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition eval.c:1066
rb_mKernel
VALUE rb_mKernel
Kernel module.
Definition object.c:65
rb_any_to_s
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:669
rb_mEnumerable
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:27
rb_eql
int rb_eql(VALUE lhs, VALUE rhs)
Checks for equality of the passed objects, in terms of Object#eql?.
Definition object.c:192
rb_cHash
VALUE rb_cHash
Hash class.
Definition hash.c:113
rb_obj_class
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:247
rb_inspect
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:680
rb_equal
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:179
rb_obj_freeze
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1260
rb_cString
VALUE rb_cString
String class.
Definition string.c:79
rb_to_int
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3192
RB_OBJ_WRITTEN
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:615
RB_OBJ_WRITE
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
rb_external_str_new_with_enc
VALUE rb_external_str_new_with_enc(const char *ptr, long len, rb_encoding *enc)
Identical to rb_external_str_new(), except it additionally takes an encoding.
Definition string.c:1296
rb_funcall
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1099
RGENGC_WB_PROTECTED_HASH
#define RGENGC_WB_PROTECTED_HASH
This is a compile-time flag to enable/disable write barrier for struct RHash.
Definition gc.h:457
builtin.h
Defines RBIMPL_HAS_BUILTIN.
INTEGER_PACK_NATIVE_BYTE_ORDER
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition bignum.h:546
RETURN_SIZED_ENUMERATOR
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:206
UNLIMITED_ARGUMENTS
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
rb_check_arity
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
rb_hash_update_func
VALUE rb_hash_update_func(VALUE newkey, VALUE oldkey, VALUE value)
Type of callback functions to pass to rb_hash_update_by().
Definition hash.h:269
st_foreach_safe
#define st_foreach_safe
Just another name of rb_st_foreach_safe.
Definition hash.h:51
rb_proc_lambda_p
VALUE rb_proc_lambda_p(VALUE recv)
Queries if the given object is a lambda.
Definition proc.c:245
rb_proc_call_with_block
VALUE rb_proc_call_with_block(VALUE recv, int argc, const VALUE *argv, VALUE proc)
Identical to rb_proc_call(), except you can additionally pass another proc object,...
Definition proc.c:1021
rb_proc_arity
int rb_proc_arity(VALUE recv)
Queries the number of mandatory arguments of the given Proc.
Definition proc.c:1128
rb_obj_is_proc
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:120
rb_hash_uint
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:942
rb_hash_end
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:945
rb_str_hash_cmp
int rb_str_hash_cmp(VALUE str1, VALUE str2)
Compares two strings.
Definition string.c:4050
rb_str_ellipsize
VALUE rb_str_ellipsize(VALUE str, long len)
Shortens str and adds three dots, an ellipsis, if it is longer than len characters.
Definition string.c:11457
rb_memhash
st_index_t rb_memhash(const void *ptr, long len)
This is a universal hash function.
Definition random.c:1770
rb_str_new
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1498
rb_str_new_frozen
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1466
rb_str_hash
st_index_t rb_str_hash(VALUE str)
Calculates a hash value of a string.
Definition string.c:4036
rb_str_buf_append
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3647
rb_hash_start
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1764
rb_str_inspect
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
Definition string.c:7202
rb_str_buf_cat_ascii
VALUE rb_str_buf_cat_ascii(VALUE dst, const char *src)
Identical to rb_str_cat_cstr(), except it additionally assumes the source string be a NUL terminated ...
Definition string.c:3623
rb_check_string_type
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2855
rb_utf8_str_new
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
Definition string.h:1549
rb_exec_recursive
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
rb_exec_recursive_paired
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
rb_ivar_get
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1426
rb_respond_to
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:2973
rb_define_alloc_func
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
rb_intern_const
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:284
rb_sym2str
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:971
rb_define_global_const
void rb_define_global_const(const char *name, VALUE val)
Identical to rb_define_const(), except it defines that of "global", i.e.
Definition variable.c:3811
capa
int capa
Designed capacity of the buffer.
Definition io.h:11
len
int len
Length of the buffer.
Definition io.h:8
ractor.h
util.h
ruby_strdup
char * ruby_strdup(const char *str)
This is our own version of strdup(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
Definition util.c:536
RB_BLOCK_CALL_FUNC_ARGLIST
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
rb_yield_values
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1366
rb_yield_values2
VALUE rb_yield_values2(int n, const VALUE *argv)
Identical to rb_yield_values(), except it takes the parameters as a C array instead of variadic argum...
Definition vm_eval.c:1388
rb_yield
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1354
RB_GC_GUARD
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
ruby::backward::cxxanyargs::type
VALUE type(ANYARGS)
ANYARGS-ed function type.
Definition cxxanyargs.hpp:56
rb_copy_generic_ivar
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c:2116
RARRAY_LEN
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
RARRAY_PTR_USE
#define RARRAY_PTR_USE(ary, ptr_name, expr)
Declares a section of code where raw pointers are used.
Definition rarray.h:348
RARRAY_AREF
#define RARRAY_AREF(a, i)
Definition rarray.h:403
RBASIC_CLASS
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:153
RBASIC
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
RHASH_SET_IFNONE
#define RHASH_SET_IFNONE(h, ifnone)
Destructively updates the default value of the hash.
Definition rhash.h:92
RHASH_IFNONE
#define RHASH_IFNONE(h)
Definition rhash.h:59
RHASH_SIZE
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:69
RHASH_EMPTY_P
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:79
StringValue
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
RSTRING_END
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
RSTRING_GETMEM
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
TypedData_Wrap_Struct
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:449
rb_obj_classname
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:507
RUBY_SPECIAL_SHIFT
@ RUBY_SPECIAL_SHIFT
Least significant 8 bits are reserved.
Definition special_consts.h:119
RTEST
#define RTEST
This is an old name of RB_TEST.
Definition special_consts.h:51
_
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
__sFILE
Definition vsnprintf.c:160
OnigEncodingTypeST
Definition onigmo.h:160
RBasic::flags
VALUE flags
Per-object flags.
Definition rbasic.h:75
RHash
Definition hash.h:53
ar_table_pair_struct
Definition hash.h:39
ar_table_struct
Definition hash.h:44
assoc_arg
Definition hash.c:4153
equal_data
Definition hash.c:3706
foreach_safe_arg
Definition hash.c:1207
functor
Definition hash.c:875
hash_foreach_arg
Definition hash.c:1242
rb_callable_method_entry_struct
Definition method.h:62
rb_data_type_struct
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:200
rb_execution_context_struct
Definition vm_core.h:1022
rehash_arg
Definition hash.c:1939
shift_var
Definition hash.c:2416
st_hash_type
Definition st.h:61
st_table
Definition st.h:79
transform_keys_args
Definition hash.c:3113
update_arg
Definition hash.c:1633
update_call_args
Definition hash.c:3913
update_callback_arg
Definition hash.c:1614
update_func_arg
Definition hash.c:4041
thread_native.h
SIGNED_VALUE
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
ID
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
VALUE
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
Check_Type
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:433
RB_TYPE_P
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376