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