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