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