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