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