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